blob: d27f11fd7dfa5485b7c4bdd78706d7460eb7ce4c [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"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080064
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080065#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080066#include <tuple>
67
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080068using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080069using namespace android::hardware::camera;
70using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080071
72namespace android {
73
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080074Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080075 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080076 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070077 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070078 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070079 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070080 mUsePartialResult(false),
81 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080082 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070083 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070084 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070085 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070086 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070087 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070088 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000089 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010090 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070091 mLastTemplateId(-1),
92 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080093{
94 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080095 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080096}
97
98Camera3Device::~Camera3Device()
99{
100 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700102 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800103}
104
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800105const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800106 return mId;
107}
108
Emilian Peevbd8c5032018-02-14 23:05:40 +0000109status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800110 ATRACE_CALL();
111 Mutex::Autolock il(mInterfaceLock);
112 Mutex::Autolock l(mLock);
113
114 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
115 if (mStatus != STATUS_UNINITIALIZED) {
116 CLOGE("Already initialized!");
117 return INVALID_OPERATION;
118 }
119 if (manager == nullptr) return INVALID_OPERATION;
120
121 sp<ICameraDeviceSession> session;
122 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800123 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800124 /*out*/ &session);
125 ATRACE_END();
126 if (res != OK) {
127 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
128 return res;
129 }
130
Steven Moreland5ff9c912017-03-09 23:13:00 -0800131 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800132 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700133 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800134 session->close();
135 return res;
136 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800137 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800138
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700139 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700140 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700141 if (isLogical) {
142 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700143 res = manager->getCameraCharacteristics(
144 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700145 if (res != OK) {
146 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
147 physicalId.c_str(), strerror(-res), res);
148 session->close();
149 return res;
150 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700151
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800152 bool usePrecorrectArray =
153 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
154 if (usePrecorrectArray) {
155 res = mDistortionMappers[physicalId].setupStaticInfo(
156 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700157 if (res != OK) {
158 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
159 "correction", physicalId.c_str());
160 session->close();
161 return res;
162 }
163 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800164
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800165 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800166 &mPhysicalDeviceInfoMap[physicalId],
167 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700168 }
169 }
170
Yifan Hongf79b5542017-04-11 14:44:25 -0700171 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700172 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
173 [&queue](const auto& descriptor) {
174 queue = std::make_shared<RequestMetadataQueue>(descriptor);
175 if (!queue->isValid() || queue->availableToWrite() <= 0) {
176 ALOGE("HAL returns empty request metadata fmq, not use it");
177 queue = nullptr;
178 // don't use the queue onwards.
179 }
180 });
181 if (!requestQueueRet.isOk()) {
182 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
183 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700184 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700185 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700186
187 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700188 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700189 [&resQueue](const auto& descriptor) {
190 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
191 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700192 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700193 resQueue = nullptr;
194 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700195 }
196 });
197 if (!resultQueueRet.isOk()) {
198 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
199 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700200 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700201 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700202 IF_ALOGV() {
203 session->interfaceChain([](
204 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
205 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800206 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700207 ALOGV(" %s", iface.c_str());
208 }
209 });
210 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700211
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800212 camera_metadata_entry bufMgrMode =
213 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
214 if (bufMgrMode.count > 0) {
215 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
216 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
217 }
218
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700219 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
220 for (size_t i = 0; i < capabilities.count; i++) {
221 uint8_t capability = capabilities.data.u8[i];
222 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
223 mSupportOfflineProcessing = true;
224 }
225 }
226
227 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000228 std::string providerType;
229 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000230 mTagMonitor.initialize(mVendorTagId);
231 if (!monitorTags.isEmpty()) {
232 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
233 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800234
Shuzhen Wang268a1362018-10-16 16:32:59 -0700235 // Metadata tags needs fixup for monochrome camera device version less
236 // than 3.5.
237 hardware::hidl_version maxVersion{0,0};
238 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
239 if (res != OK) {
240 ALOGE("%s: Error in getting camera device version id: %s (%d)",
241 __FUNCTION__, strerror(-res), res);
242 return res;
243 }
244 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
245 maxVersion.get_major(), maxVersion.get_minor());
246
247 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700248 for (size_t i = 0; i < capabilities.count; i++) {
249 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700250 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
251 isMonochrome = true;
252 }
253 }
254 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
255
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800256 return initializeCommonLocked();
257}
258
259status_t Camera3Device::initializeCommonLocked() {
260
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700261 /** Start up status tracker thread */
262 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800263 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700264 if (res != OK) {
265 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
266 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800267 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700268 mStatusTracker.clear();
269 return res;
270 }
271
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700272 /** Register in-flight map to the status tracker */
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -0700273 mInFlightStatusId = mStatusTracker->addComponent("InflightRequests");
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700274
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700275 if (mUseHalBufManager) {
276 res = mRequestBufferSM.initialize(mStatusTracker);
277 if (res != OK) {
278 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
279 strerror(-res), res);
280 mInterface->close();
281 mStatusTracker.clear();
282 return res;
283 }
284 }
285
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800286 /** Create buffer manager */
287 mBufferManager = new Camera3BufferManager();
288
289 Vector<int32_t> sessionParamKeys;
290 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
291 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
292 if (sessionKeysEntry.count > 0) {
293 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
294 }
295
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700296 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700297 mRequestThread = new RequestThread(
298 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800299 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800300 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700301 SET_ERR_L("Unable to start request queue thread: %s (%d)",
302 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800303 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800304 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800305 return res;
306 }
307
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700308 mPreparerThread = new PreparerThread();
309
Ruben Brunk183f0562015-08-12 12:55:02 -0700310 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800311 mNextStreamId = 0;
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -0400312 mFakeStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700313 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700314 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800315
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800316 // Measure the clock domain offset between camera and video/hw_composer
317 camera_metadata_entry timestampSource =
318 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
319 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
320 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
321 mTimestampOffset = getMonoToBoottimeOffset();
322 }
323
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700324 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100325 camera_metadata_entry partialResultsCount =
326 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
327 if (partialResultsCount.count > 0) {
328 mNumPartialResults = partialResultsCount.data.i32[0];
329 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700330 }
331
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700332 camera_metadata_entry configs =
333 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
334 for (uint32_t i = 0; i < configs.count; i += 4) {
335 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
336 configs.data.i32[i + 3] ==
337 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
338 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
339 configs.data.i32[i + 2]));
340 }
341 }
342
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800343 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
344 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700345 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700346 if (res != OK) {
347 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
348 return res;
349 }
350 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800351
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800352 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800353 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800354
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800355 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
356 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
357 }
358
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800359 return OK;
360}
361
362status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700363 return disconnectImpl();
364}
365
366status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800367 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700368 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800369
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700370 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700371 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700372 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800373 Mutex::Autolock il(mInterfaceLock);
374 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
375 {
376 Mutex::Autolock l(mLock);
377 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700378
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800379 if (mStatus == STATUS_ACTIVE ||
380 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
381 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700382 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800383 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700384 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800385 } else {
386 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
387 if (res != OK) {
388 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
389 maxExpectedDuration);
390 // Continue to close device even in case of error
391 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700392 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700393 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800394
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800395 if (mStatus == STATUS_ERROR) {
396 CLOGE("Shutting down in an error state");
397 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700398
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800399 if (mStatusTracker != NULL) {
400 mStatusTracker->requestExit();
401 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700402
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800403 if (mRequestThread != NULL) {
404 mRequestThread->requestExit();
405 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700406
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800407 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
408 for (size_t i = 0; i < mOutputStreams.size(); i++) {
409 streams.push_back(mOutputStreams[i]);
410 }
411 if (mInputStream != nullptr) {
412 streams.push_back(mInputStream);
413 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700414 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700415 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800416 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
417 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700418 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
419 // HAL may be in a bad state, so waiting for request thread
420 // (which may be stuck in the HAL processCaptureRequest call)
421 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800422 // give up mInterfaceLock here and then lock it again. Could this lead
423 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700424 mRequestThread->join();
425 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700426 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800427 Mutex::Autolock il(mInterfaceLock);
428 if (mStatusTracker != NULL) {
429 mStatusTracker->join();
430 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800431
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800432 HalInterface* interface;
433 {
434 Mutex::Autolock l(mLock);
435 mRequestThread.clear();
436 Mutex::Autolock stLock(mTrackerLock);
437 mStatusTracker.clear();
438 interface = mInterface.get();
439 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700440
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800441 // Call close without internal mutex held, as the HAL close may need to
442 // wait on assorted callbacks,etc, to complete before it can return.
443 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700444
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800445 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800446
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800447 {
448 Mutex::Autolock l(mLock);
449 mInterface->clear();
450 mOutputStreams.clear();
451 mInputStream.clear();
452 mDeletedStreams.clear();
453 mBufferManager.clear();
454 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
455 }
456
457 for (auto& weakStream : streams) {
458 sp<Camera3StreamInterface> stream = weakStream.promote();
459 if (stream != nullptr) {
460 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
461 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
462 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700463 }
464 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700465 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700466 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800467}
468
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700469// For dumping/debugging only -
470// try to acquire a lock a few times, eventually give up to proceed with
471// debug/dump operations
472bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
473 bool gotLock = false;
474 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
475 if (lock.tryLock() == NO_ERROR) {
476 gotLock = true;
477 break;
478 } else {
479 usleep(kDumpSleepDuration);
480 }
481 }
482 return gotLock;
483}
484
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700485Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
486 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100487 const int STREAM_CONFIGURATION_SIZE = 4;
488 const int STREAM_FORMAT_OFFSET = 0;
489 const int STREAM_WIDTH_OFFSET = 1;
490 const int STREAM_HEIGHT_OFFSET = 2;
491 const int STREAM_IS_INPUT_OFFSET = 3;
492 camera_metadata_ro_entry_t availableStreamConfigs =
493 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
494 if (availableStreamConfigs.count == 0 ||
495 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
496 return Size(0, 0);
497 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700498
Emilian Peev08dd2452017-04-06 16:55:14 +0100499 // Get max jpeg size (area-wise).
500 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
501 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
502 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
503 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
504 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
505 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
506 && format == HAL_PIXEL_FORMAT_BLOB &&
507 (width * height > maxJpegWidth * maxJpegHeight)) {
508 maxJpegWidth = width;
509 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700510 }
511 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100512
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700513 return Size(maxJpegWidth, maxJpegHeight);
514}
515
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800516nsecs_t Camera3Device::getMonoToBoottimeOffset() {
517 // try three times to get the clock offset, choose the one
518 // with the minimum gap in measurements.
519 const int tries = 3;
520 nsecs_t bestGap, measured;
521 for (int i = 0; i < tries; ++i) {
522 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
523 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
524 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
525 const nsecs_t gap = tmono2 - tmono;
526 if (i == 0 || gap < bestGap) {
527 bestGap = gap;
528 measured = tbase - ((tmono + tmono2) >> 1);
529 }
530 }
531 return measured;
532}
533
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
535 int frameworkFormat) {
536 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
537}
538
539DataspaceFlags Camera3Device::mapToHidlDataspace(
540 android_dataspace dataSpace) {
541 return dataSpace;
542}
543
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700544BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100545 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700546 return usage;
547}
548
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800549StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
550 switch (rotation) {
551 case CAMERA3_STREAM_ROTATION_0:
552 return StreamRotation::ROTATION_0;
553 case CAMERA3_STREAM_ROTATION_90:
554 return StreamRotation::ROTATION_90;
555 case CAMERA3_STREAM_ROTATION_180:
556 return StreamRotation::ROTATION_180;
557 case CAMERA3_STREAM_ROTATION_270:
558 return StreamRotation::ROTATION_270;
559 }
560 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
561 return StreamRotation::ROTATION_0;
562}
563
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800564status_t Camera3Device::mapToStreamConfigurationMode(
565 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
566 if (mode == nullptr) return BAD_VALUE;
567 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
568 switch(operationMode) {
569 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
570 *mode = StreamConfigurationMode::NORMAL_MODE;
571 break;
572 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
573 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
574 break;
575 default:
576 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
577 return BAD_VALUE;
578 }
579 } else {
580 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800581 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800582 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800583}
584
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800585int Camera3Device::mapToFrameworkFormat(
586 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
587 return static_cast<uint32_t>(pixelFormat);
588}
589
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700590android_dataspace Camera3Device::mapToFrameworkDataspace(
591 DataspaceFlags dataSpace) {
592 return static_cast<android_dataspace>(dataSpace);
593}
594
Emilian Peev050f5dc2017-05-18 14:43:56 +0100595uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700596 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700597 return usage;
598}
599
Emilian Peev050f5dc2017-05-18 14:43:56 +0100600uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700601 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700602 return usage;
603}
604
Zhijun Hef7da0962014-04-24 13:27:56 -0700605ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700606 // Get max jpeg size (area-wise).
607 Size maxJpegResolution = getMaxJpegResolution();
608 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800609 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
610 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700611 return BAD_VALUE;
612 }
613
Zhijun Hef7da0962014-04-24 13:27:56 -0700614 // Get max jpeg buffer size
615 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700616 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
617 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800618 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
619 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700620 return BAD_VALUE;
621 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700622 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800623 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700624
625 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700626 float scaleFactor = ((float) (width * height)) /
627 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800628 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
629 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700630 if (jpegBufferSize > maxJpegBufferSize) {
631 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700632 }
633
634 return jpegBufferSize;
635}
636
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700637ssize_t Camera3Device::getPointCloudBufferSize() const {
638 const int FLOATS_PER_POINT=4;
639 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
640 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800641 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
642 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700643 return BAD_VALUE;
644 }
645 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
646 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
647 return maxBytesForPointCloud;
648}
649
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800650ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800651 const int PER_CONFIGURATION_SIZE = 3;
652 const int WIDTH_OFFSET = 0;
653 const int HEIGHT_OFFSET = 1;
654 const int SIZE_OFFSET = 2;
655 camera_metadata_ro_entry rawOpaqueSizes =
656 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800657 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800658 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800659 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
660 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800661 return BAD_VALUE;
662 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700663
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800664 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
665 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
666 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
667 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
668 }
669 }
670
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800671 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
672 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800673 return BAD_VALUE;
674}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700675
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800676status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
677 ATRACE_CALL();
678 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700679
680 // Try to lock, but continue in case of failure (to avoid blocking in
681 // deadlocks)
682 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
683 bool gotLock = tryLockSpinRightRound(mLock);
684
685 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800686 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
687 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700688 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800689 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
690 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700691
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800692 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700693
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800694 String16 templatesOption("-t");
695 int n = args.size();
696 for (int i = 0; i < n; i++) {
697 if (args[i] == templatesOption) {
698 dumpTemplates = true;
699 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000700 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700701 if (i + 1 < n) {
702 String8 monitorTags = String8(args[i + 1]);
703 if (monitorTags == "off") {
704 mTagMonitor.disableMonitoring();
705 } else {
706 mTagMonitor.parseTagsToMonitor(monitorTags);
707 }
708 } else {
709 mTagMonitor.disableMonitoring();
710 }
711 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800712 }
713
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800714 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800715
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800716 const char *status =
717 mStatus == STATUS_ERROR ? "ERROR" :
718 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700719 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
720 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800721 mStatus == STATUS_ACTIVE ? "ACTIVE" :
722 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700723
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800724 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700725 if (mStatus == STATUS_ERROR) {
726 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
727 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800728 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800729 const char *mode =
730 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
731 mOperatingMode == static_cast<int>(
732 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
733 "CUSTOM";
734 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800735
736 if (mInputStream != NULL) {
737 write(fd, lines.string(), lines.size());
738 mInputStream->dump(fd, args);
739 } else {
740 lines.appendFormat(" No input stream.\n");
741 write(fd, lines.string(), lines.size());
742 }
743 for (size_t i = 0; i < mOutputStreams.size(); i++) {
744 mOutputStreams[i]->dump(fd,args);
745 }
746
Zhijun He431503c2016-03-07 17:30:16 -0800747 if (mBufferManager != NULL) {
748 lines = String8(" Camera3 Buffer Manager:\n");
749 write(fd, lines.string(), lines.size());
750 mBufferManager->dump(fd, args);
751 }
Zhijun He125684a2015-12-26 15:07:30 -0800752
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700753 lines = String8(" In-flight requests:\n");
754 if (mInFlightMap.size() == 0) {
755 lines.append(" None\n");
756 } else {
757 for (size_t i = 0; i < mInFlightMap.size(); i++) {
758 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700759 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Greg Kaiser51b882c2020-06-10 05:41:44 +0000760 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800761 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Greg Kaiser51b882c2020-06-10 05:41:44 +0000762 r.numBuffersLeft);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700763 }
764 }
765 write(fd, lines.string(), lines.size());
766
Shuzhen Wang686f6442017-06-20 16:16:04 -0700767 if (mRequestThread != NULL) {
768 mRequestThread->dumpCaptureRequestLatency(fd,
769 " ProcessCaptureRequest latency histogram:");
770 }
771
Igor Murashkin1e479c02013-09-06 16:55:14 -0700772 {
773 lines = String8(" Last request sent:\n");
774 write(fd, lines.string(), lines.size());
775
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700776 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700777 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
778 }
779
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800780 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800781 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800782 "TEMPLATE_PREVIEW",
783 "TEMPLATE_STILL_CAPTURE",
784 "TEMPLATE_VIDEO_RECORD",
785 "TEMPLATE_VIDEO_SNAPSHOT",
786 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800787 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800788 };
789
790 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800791 camera_metadata_t *templateRequest = nullptr;
792 mInterface->constructDefaultRequestSettings(
793 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800794 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800795 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800796 lines.append(" Not supported\n");
797 write(fd, lines.string(), lines.size());
798 } else {
799 write(fd, lines.string(), lines.size());
800 dump_indented_camera_metadata(templateRequest,
801 fd, /*verbosity*/2, /*indentation*/8);
802 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800803 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800804 }
805 }
806
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700807 mTagMonitor.dumpMonitoredMetadata(fd);
808
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800809 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800810 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800811 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800812 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800813 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800814
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700815 if (gotLock) mLock.unlock();
816 if (gotInterfaceLock) mInterfaceLock.unlock();
817
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800818 return OK;
819}
820
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800821const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800822 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800823 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
824 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700825 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800826 mStatus == STATUS_ERROR ?
827 "when in error state" : "before init");
828 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700829 if (physicalId.isEmpty()) {
830 return mDeviceInfo;
831 } else {
832 std::string id(physicalId.c_str());
833 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
834 return mPhysicalDeviceInfoMap.at(id);
835 } else {
836 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
837 return mDeviceInfo;
838 }
839 }
840}
841
842const CameraMetadata& Camera3Device::info() const {
843 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800844 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800845}
846
Jianing Wei90e59c92014-03-12 18:29:36 -0700847status_t Camera3Device::checkStatusOkToCaptureLocked() {
848 switch (mStatus) {
849 case STATUS_ERROR:
850 CLOGE("Device has encountered a serious error");
851 return INVALID_OPERATION;
852 case STATUS_UNINITIALIZED:
853 CLOGE("Device not initialized");
854 return INVALID_OPERATION;
855 case STATUS_UNCONFIGURED:
856 case STATUS_CONFIGURED:
857 case STATUS_ACTIVE:
858 // OK
859 break;
860 default:
861 SET_ERR_L("Unexpected status: %d", mStatus);
862 return INVALID_OPERATION;
863 }
864 return OK;
865}
866
867status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000868 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700869 const std::list<const SurfaceMap> &surfaceMaps,
870 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700871 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700872 if (requestList == NULL) {
873 CLOGE("requestList cannot be NULL.");
874 return BAD_VALUE;
875 }
876
Jianing Weicb0652e2014-03-12 18:29:36 -0700877 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000878 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700879 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
880 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
881 ++metadataIt, ++surfaceMapIt) {
882 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700883 if (newRequest == 0) {
884 CLOGE("Can't create capture request");
885 return BAD_VALUE;
886 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700887
Shuzhen Wang9d066012016-09-30 11:30:20 -0700888 newRequest->mRepeating = repeating;
889
Jianing Weicb0652e2014-03-12 18:29:36 -0700890 // Setup burst Id and request Id
891 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800892 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
893 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700894 CLOGE("RequestID does not exist in metadata");
895 return BAD_VALUE;
896 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800897 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700898
Jianing Wei90e59c92014-03-12 18:29:36 -0700899 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700900
901 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700902 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700903 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
904 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
905 return BAD_VALUE;
906 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700907
908 // Setup batch size if this is a high speed video recording request.
909 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
910 auto firstRequest = requestList->begin();
911 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
912 if (outputStream->isVideoStream()) {
913 (*firstRequest)->mBatchSize = requestList->size();
914 break;
915 }
916 }
917 }
918
Jianing Wei90e59c92014-03-12 18:29:36 -0700919 return OK;
920}
921
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800922status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800923 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800924
Emilian Peevaebbe412018-01-15 13:53:24 +0000925 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700926 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000927 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700928
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800929 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700930}
931
Emilian Peevaebbe412018-01-15 13:53:24 +0000932void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700933 std::list<const SurfaceMap>& surfaceMaps,
934 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000935 PhysicalCameraSettingsList requestList;
936 requestList.push_back({std::string(getId().string()), request});
937 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700938
939 SurfaceMap surfaceMap;
940 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
941 // With no surface list passed in, stream and surface will have 1-to-1
942 // mapping. So the surface index is 0 for each stream in the surfaceMap.
943 for (size_t i = 0; i < streams.count; i++) {
944 surfaceMap[streams.data.i32[i]].push_back(0);
945 }
946 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800947}
948
Jianing Wei90e59c92014-03-12 18:29:36 -0700949status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000950 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700951 const std::list<const SurfaceMap> &surfaceMaps,
952 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700953 /*out*/
954 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700955 ATRACE_CALL();
956 Mutex::Autolock il(mInterfaceLock);
957 Mutex::Autolock l(mLock);
958
959 status_t res = checkStatusOkToCaptureLocked();
960 if (res != OK) {
961 // error logged by previous call
962 return res;
963 }
964
965 RequestList requestList;
966
Shuzhen Wang0129d522016-10-30 22:43:41 -0700967 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
968 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700969 if (res != OK) {
970 // error logged by previous call
971 return res;
972 }
973
974 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700975 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700976 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700977 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700978 }
979
980 if (res == OK) {
981 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
982 if (res != OK) {
983 SET_ERR_L("Can't transition to active in %f seconds!",
984 kActiveTimeout/1e9);
985 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800986 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700987 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700988 } else {
989 CLOGE("Cannot queue request. Impossible.");
990 return BAD_VALUE;
991 }
992
993 return res;
994}
995
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700996hardware::Return<void> Camera3Device::requestStreamBuffers(
997 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
998 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -0800999 RequestBufferStates states {
1000 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams,
1001 *this, *mInterface, *this};
1002 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001003 return hardware::Void();
1004}
1005
1006hardware::Return<void> Camera3Device::returnStreamBuffers(
1007 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001008 ReturnBufferStates states {
1009 mId, mUseHalBufManager, mOutputStreams, *mInterface};
1010 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001011 return hardware::Void();
1012}
1013
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001014hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001015 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001016 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001017 // Ideally we should grab mLock, but that can lead to deadlock, and
1018 // it's not super important to get up to date value of mStatus for this
1019 // warning print, hence skipping the lock here
1020 if (mStatus == STATUS_ERROR) {
1021 // Per API contract, HAL should act as closed after device error
1022 // But mStatus can be set to error by framework as well, so just log
1023 // a warning here.
1024 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001025 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001026
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001027 sp<NotificationListener> listener;
1028 {
1029 std::lock_guard<std::mutex> l(mOutputLock);
1030 listener = mListener.promote();
1031 }
1032
Yifan Honga640c5a2017-04-12 16:30:31 -07001033 if (mProcessCaptureResultLock.tryLock() != OK) {
1034 // This should never happen; it indicates a wrong client implementation
1035 // that doesn't follow the contract. But, we can be tolerant here.
1036 ALOGE("%s: callback overlapped! waiting 1s...",
1037 __FUNCTION__);
1038 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1039 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1040 __FUNCTION__);
1041 // really don't know what to do, so bail out.
1042 return hardware::Void();
1043 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001044 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001045 CaptureOutputStates states {
1046 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001047 mInFlightLock, mLastCompletedRegularFrameNumber,
1048 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1049 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001050 mNextShutterFrameNumber,
1051 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1052 mNextResultFrameNumber,
1053 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1054 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1055 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001056 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1057 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001058 };
1059
Yifan Honga640c5a2017-04-12 16:30:31 -07001060 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001061 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001062 }
1063 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001064 return hardware::Void();
1065}
1066
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001067// Only one processCaptureResult should be called at a time, so
1068// the locks won't block. The locks are present here simply to enforce this.
1069hardware::Return<void> Camera3Device::processCaptureResult(
1070 const hardware::hidl_vec<
1071 hardware::camera::device::V3_2::CaptureResult>& results) {
1072 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1073
1074 // Ideally we should grab mLock, but that can lead to deadlock, and
1075 // it's not super important to get up to date value of mStatus for this
1076 // warning print, hence skipping the lock here
1077 if (mStatus == STATUS_ERROR) {
1078 // Per API contract, HAL should act as closed after device error
1079 // But mStatus can be set to error by framework as well, so just log
1080 // a warning here.
1081 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1082 }
1083
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001084 sp<NotificationListener> listener;
1085 {
1086 std::lock_guard<std::mutex> l(mOutputLock);
1087 listener = mListener.promote();
1088 }
1089
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001090 if (mProcessCaptureResultLock.tryLock() != OK) {
1091 // This should never happen; it indicates a wrong client implementation
1092 // that doesn't follow the contract. But, we can be tolerant here.
1093 ALOGE("%s: callback overlapped! waiting 1s...",
1094 __FUNCTION__);
1095 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1096 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1097 __FUNCTION__);
1098 // really don't know what to do, so bail out.
1099 return hardware::Void();
1100 }
1101 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001102
1103 CaptureOutputStates states {
1104 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001105 mInFlightLock, mLastCompletedRegularFrameNumber,
1106 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1107 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001108 mNextShutterFrameNumber,
1109 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1110 mNextResultFrameNumber,
1111 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1112 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1113 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001114 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1115 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001116 };
1117
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001118 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001119 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001120 }
1121 mProcessCaptureResultLock.unlock();
1122 return hardware::Void();
1123}
1124
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001125hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001126 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001127 // Ideally we should grab mLock, but that can lead to deadlock, and
1128 // it's not super important to get up to date value of mStatus for this
1129 // warning print, hence skipping the lock here
1130 if (mStatus == STATUS_ERROR) {
1131 // Per API contract, HAL should act as closed after device error
1132 // But mStatus can be set to error by framework as well, so just log
1133 // a warning here.
1134 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001135 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001136
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001137 sp<NotificationListener> listener;
1138 {
1139 std::lock_guard<std::mutex> l(mOutputLock);
1140 listener = mListener.promote();
1141 }
1142
1143 CaptureOutputStates states {
1144 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001145 mInFlightLock, mLastCompletedRegularFrameNumber,
1146 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1147 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001148 mNextShutterFrameNumber,
1149 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1150 mNextResultFrameNumber,
1151 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1152 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1153 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001154 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1155 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001156 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001157 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001158 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001159 }
1160 return hardware::Void();
1161}
1162
Emilian Peevaebbe412018-01-15 13:53:24 +00001163status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001164 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001165 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001166 ATRACE_CALL();
1167
Emilian Peevaebbe412018-01-15 13:53:24 +00001168 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001169}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001170
Jianing Weicb0652e2014-03-12 18:29:36 -07001171status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1172 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001173 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001174
Emilian Peevaebbe412018-01-15 13:53:24 +00001175 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001176 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001177 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001178
Emilian Peevaebbe412018-01-15 13:53:24 +00001179 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001180 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001181}
1182
Emilian Peevaebbe412018-01-15 13:53:24 +00001183status_t Camera3Device::setStreamingRequestList(
1184 const List<const PhysicalCameraSettingsList> &requestsList,
1185 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001186 ATRACE_CALL();
1187
Emilian Peevaebbe412018-01-15 13:53:24 +00001188 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001189}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001190
1191sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001192 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001193 status_t res;
1194
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001195 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001196 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1197 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001198 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1199 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001200 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001202 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001203 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001204 } else if (mStatus == STATUS_UNCONFIGURED) {
1205 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001206 CLOGE("No streams configured");
1207 return NULL;
1208 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001209 }
1210
Shuzhen Wang0129d522016-10-30 22:43:41 -07001211 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001212 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001213}
1214
Jianing Weicb0652e2014-03-12 18:29:36 -07001215status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001216 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001217 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001218 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001219
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 switch (mStatus) {
1221 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001222 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001223 return INVALID_OPERATION;
1224 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001225 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001227 case STATUS_UNCONFIGURED:
1228 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229 case STATUS_ACTIVE:
1230 // OK
1231 break;
1232 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001233 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001234 return INVALID_OPERATION;
1235 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001236 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001237
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001238 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001239}
1240
1241status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1242 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001243 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001244
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001245 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001246}
1247
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001248status_t Camera3Device::createInputStream(
1249 uint32_t width, uint32_t height, int format, int *id) {
1250 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001251 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001252 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001253 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001254 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1255 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001256
1257 status_t res;
1258 bool wasActive = false;
1259
1260 switch (mStatus) {
1261 case STATUS_ERROR:
1262 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1263 return INVALID_OPERATION;
1264 case STATUS_UNINITIALIZED:
1265 ALOGE("%s: Device not initialized", __FUNCTION__);
1266 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001267 case STATUS_UNCONFIGURED:
1268 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001269 // OK
1270 break;
1271 case STATUS_ACTIVE:
1272 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001273 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001274 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001275 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001276 return res;
1277 }
1278 wasActive = true;
1279 break;
1280 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001281 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001282 return INVALID_OPERATION;
1283 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001284 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001285
1286 if (mInputStream != 0) {
1287 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1288 return INVALID_OPERATION;
1289 }
1290
1291 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1292 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001293 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001294
1295 mInputStream = newStream;
1296
1297 *id = mNextStreamId++;
1298
1299 // Continue captures if active at start
1300 if (wasActive) {
1301 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001302 // Reuse current operating mode and session parameters for new stream config
1303 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001304 if (res != OK) {
1305 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1306 __FUNCTION__, mNextStreamId, strerror(-res), res);
1307 return res;
1308 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001309 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001310 }
1311
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001312 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001313 return OK;
1314}
1315
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001316status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001317 uint32_t width, uint32_t height, int format,
1318 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001319 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001320 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001321 ATRACE_CALL();
1322
1323 if (consumer == nullptr) {
1324 ALOGE("%s: consumer must not be null", __FUNCTION__);
1325 return BAD_VALUE;
1326 }
1327
1328 std::vector<sp<Surface>> consumers;
1329 consumers.push_back(consumer);
1330
1331 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001332 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1333 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001334}
1335
1336status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1337 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1338 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001339 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001340 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001341 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001342
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001343 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001344 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001345 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001346 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001347 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1348 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1349 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001350
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001351 status_t res;
1352 bool wasActive = false;
1353
1354 switch (mStatus) {
1355 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001356 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001357 return INVALID_OPERATION;
1358 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001359 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001360 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001361 case STATUS_UNCONFIGURED:
1362 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001363 // OK
1364 break;
1365 case STATUS_ACTIVE:
1366 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001367 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001368 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001369 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001370 return res;
1371 }
1372 wasActive = true;
1373 break;
1374 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001375 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001376 return INVALID_OPERATION;
1377 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001378 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001379
1380 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001381
Shuzhen Wang0129d522016-10-30 22:43:41 -07001382 if (consumers.size() == 0 && !hasDeferredConsumer) {
1383 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1384 return BAD_VALUE;
1385 }
Zhijun He5d677d12016-05-29 16:52:39 -07001386
Shuzhen Wang0129d522016-10-30 22:43:41 -07001387 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001388 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1389 return BAD_VALUE;
1390 }
1391
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001392 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001393 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001394 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001395 blobBufferSize = getPointCloudBufferSize();
1396 if (blobBufferSize <= 0) {
1397 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1398 return BAD_VALUE;
1399 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001400 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1401 blobBufferSize = width * height;
1402 } else {
1403 blobBufferSize = getJpegBufferSize(width, height);
1404 if (blobBufferSize <= 0) {
1405 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1406 return BAD_VALUE;
1407 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001408 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001409 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001410 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001411 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001412 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1413 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1414 if (rawOpaqueBufferSize <= 0) {
1415 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1416 return BAD_VALUE;
1417 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001418 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001419 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001420 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001421 } else if (isShared) {
1422 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1423 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001424 mTimestampOffset, physicalCameraId, streamSetId,
1425 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001426 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001427 newStream = new Camera3OutputStream(mNextStreamId,
1428 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001429 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001431 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001432 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001433 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001434 }
Emilian Peev40ead602017-09-26 15:46:36 +01001435
1436 size_t consumerCount = consumers.size();
1437 for (size_t i = 0; i < consumerCount; i++) {
1438 int id = newStream->getSurfaceId(consumers[i]);
1439 if (id < 0) {
1440 SET_ERR_L("Invalid surface id");
1441 return BAD_VALUE;
1442 }
1443 if (surfaceIds != nullptr) {
1444 surfaceIds->push_back(id);
1445 }
1446 }
1447
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001448 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001449
Emilian Peev08dd2452017-04-06 16:55:14 +01001450 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001451
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001452 res = mOutputStreams.add(mNextStreamId, newStream);
1453 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001454 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001455 return res;
1456 }
1457
1458 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001459 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001460
1461 // Continue captures if active at start
1462 if (wasActive) {
1463 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001464 // Reuse current operating mode and session parameters for new stream config
1465 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001467 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1468 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001469 return res;
1470 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001471 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001472 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001473 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001475}
1476
Emilian Peev710c1422017-08-30 11:19:38 +01001477status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001478 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001479 if (nullptr == streamInfo) {
1480 return BAD_VALUE;
1481 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001482 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001483 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001484
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 switch (mStatus) {
1486 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001487 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001488 return INVALID_OPERATION;
1489 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001490 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001491 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001492 case STATUS_UNCONFIGURED:
1493 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 case STATUS_ACTIVE:
1495 // OK
1496 break;
1497 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001498 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001499 return INVALID_OPERATION;
1500 }
1501
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001502 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1503 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001504 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001505 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506 }
1507
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001508 streamInfo->width = stream->getWidth();
1509 streamInfo->height = stream->getHeight();
1510 streamInfo->format = stream->getFormat();
1511 streamInfo->dataSpace = stream->getDataSpace();
1512 streamInfo->formatOverridden = stream->isFormatOverridden();
1513 streamInfo->originalFormat = stream->getOriginalFormat();
1514 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1515 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001516 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001517}
1518
1519status_t Camera3Device::setStreamTransform(int id,
1520 int transform) {
1521 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001522 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001524
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001525 switch (mStatus) {
1526 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001527 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 return INVALID_OPERATION;
1529 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001530 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001531 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001532 case STATUS_UNCONFIGURED:
1533 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 case STATUS_ACTIVE:
1535 // OK
1536 break;
1537 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001538 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 return INVALID_OPERATION;
1540 }
1541
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001542 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1543 if (stream == nullptr) {
1544 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 return BAD_VALUE;
1546 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001547 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001548}
1549
1550status_t Camera3Device::deleteStream(int id) {
1551 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 Mutex::Autolock l(mLock);
1554 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001555
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001556 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001557
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 // CameraDevice semantics require device to already be idle before
1559 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001560 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001561 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001562 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001563 }
1564
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001565 if (mStatus == STATUS_ERROR) {
1566 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1567 __FUNCTION__, mId.string());
1568 return -EBUSY;
1569 }
1570
Igor Murashkin2fba5842013-04-22 14:03:54 -07001571 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001572 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001573 if (mInputStream != NULL && id == mInputStream->getId()) {
1574 deletedStream = mInputStream;
1575 mInputStream.clear();
1576 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001577 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001578 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579 return BAD_VALUE;
1580 }
Zhijun He5f446352014-01-22 09:49:33 -08001581 }
1582
1583 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001584 if (stream != nullptr) {
1585 deletedStream = stream;
1586 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001587 }
1588
1589 // Free up the stream endpoint so that it can be used by some other stream
1590 res = deletedStream->disconnect();
1591 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001592 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593 // fall through since we want to still list the stream as deleted.
1594 }
1595 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001596 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001597
1598 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001599}
1600
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001601status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001602 ATRACE_CALL();
1603 ALOGV("%s: E", __FUNCTION__);
1604
1605 Mutex::Autolock il(mInterfaceLock);
1606 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001607
Emilian Peev811d2952018-05-25 11:08:40 +01001608 // In case the client doesn't include any session parameter, try a
1609 // speculative configuration using the values from the last cached
1610 // default request.
1611 if (sessionParams.isEmpty() &&
1612 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1613 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1614 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1615 mLastTemplateId);
1616 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1617 operatingMode);
1618 }
1619
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001620 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1621}
1622
1623status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1624 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001625 //Filter out any incoming session parameters
1626 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001627 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1628 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001629 CameraMetadata filteredParams(availableSessionKeys.count);
1630 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1631 filteredParams.getAndLock());
1632 set_camera_metadata_vendor_id(meta, mVendorTagId);
1633 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001634 if (availableSessionKeys.count > 0) {
1635 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1636 camera_metadata_ro_entry entry = params.find(
1637 availableSessionKeys.data.i32[i]);
1638 if (entry.count > 0) {
1639 filteredParams.update(entry);
1640 }
1641 }
1642 }
1643
1644 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001645}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001646
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001647status_t Camera3Device::getInputBufferProducer(
1648 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001649 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001650 Mutex::Autolock il(mInterfaceLock);
1651 Mutex::Autolock l(mLock);
1652
1653 if (producer == NULL) {
1654 return BAD_VALUE;
1655 } else if (mInputStream == NULL) {
1656 return INVALID_OPERATION;
1657 }
1658
1659 return mInputStream->getInputBufferProducer(producer);
1660}
1661
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001662status_t Camera3Device::createDefaultRequest(int templateId,
1663 CameraMetadata *request) {
1664 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001665 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001666
1667 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1668 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001669 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001670 return BAD_VALUE;
1671 }
1672
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001673 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001674
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001675 {
1676 Mutex::Autolock l(mLock);
1677 switch (mStatus) {
1678 case STATUS_ERROR:
1679 CLOGE("Device has encountered a serious error");
1680 return INVALID_OPERATION;
1681 case STATUS_UNINITIALIZED:
1682 CLOGE("Device is not initialized!");
1683 return INVALID_OPERATION;
1684 case STATUS_UNCONFIGURED:
1685 case STATUS_CONFIGURED:
1686 case STATUS_ACTIVE:
1687 // OK
1688 break;
1689 default:
1690 SET_ERR_L("Unexpected status: %d", mStatus);
1691 return INVALID_OPERATION;
1692 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001693
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001694 if (!mRequestTemplateCache[templateId].isEmpty()) {
1695 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001696 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001697 return OK;
1698 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001699 }
1700
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001701 camera_metadata_t *rawRequest;
1702 status_t res = mInterface->constructDefaultRequestSettings(
1703 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001704
1705 {
1706 Mutex::Autolock l(mLock);
1707 if (res == BAD_VALUE) {
1708 ALOGI("%s: template %d is not supported on this camera device",
1709 __FUNCTION__, templateId);
1710 return res;
1711 } else if (res != OK) {
1712 CLOGE("Unable to construct request template %d: %s (%d)",
1713 templateId, strerror(-res), res);
1714 return res;
1715 }
1716
1717 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1718 mRequestTemplateCache[templateId].acquire(rawRequest);
1719
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001720 // Override the template request with zoomRatioMapper
1721 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1722 &mRequestTemplateCache[templateId]);
1723 if (res != OK) {
1724 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1725 templateId, strerror(-res), res);
1726 return res;
1727 }
1728
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001729 // Fill in JPEG_QUALITY if not available
1730 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1731 static const uint8_t kDefaultJpegQuality = 95;
1732 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1733 &kDefaultJpegQuality, 1);
1734 }
1735
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001736 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001737 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001738 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001739 return OK;
1740}
1741
1742status_t Camera3Device::waitUntilDrained() {
1743 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001744 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001745 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001746 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001747
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001748 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001749}
1750
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001751status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001752 switch (mStatus) {
1753 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001754 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001755 ALOGV("%s: Already idle", __FUNCTION__);
1756 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001757 case STATUS_CONFIGURED:
1758 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001759 case STATUS_ERROR:
1760 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001761 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001762 break;
1763 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001764 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001765 return INVALID_OPERATION;
1766 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001767 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1768 maxExpectedDuration);
1769 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001770 if (res != OK) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07001771 mStatusTracker->dumpActiveComponents();
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001772 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1773 res);
1774 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001775 return res;
1776}
1777
Ruben Brunk183f0562015-08-12 12:55:02 -07001778
1779void Camera3Device::internalUpdateStatusLocked(Status status) {
1780 mStatus = status;
1781 mRecentStatusUpdates.add(mStatus);
1782 mStatusChanged.broadcast();
1783}
1784
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001785// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001786status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001787 if (mRequestThread.get() != nullptr) {
1788 mRequestThread->setPaused(true);
1789 } else {
1790 return NO_INIT;
1791 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001792
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001793 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1794 maxExpectedDuration);
1795 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001796 if (res != OK) {
1797 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001798 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001799 }
1800
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001801 return res;
1802}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001803
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001804// Resume after internalPauseAndWaitLocked
1805status_t Camera3Device::internalResumeLocked() {
1806 status_t res;
1807
1808 mRequestThread->setPaused(false);
1809
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001810 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1811 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001812 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1813 if (res != OK) {
1814 SET_ERR_L("Can't transition to active in %f seconds!",
1815 kActiveTimeout/1e9);
1816 }
1817 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001818 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001819}
1820
Ruben Brunk183f0562015-08-12 12:55:02 -07001821status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001822 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001823
1824 size_t startIndex = 0;
1825 if (mStatusWaiters == 0) {
1826 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1827 // this status list
1828 mRecentStatusUpdates.clear();
1829 } else {
1830 // If other threads are waiting on updates to this status list, set the position of the
1831 // first element that this list will check rather than clearing the list.
1832 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001833 }
1834
Ruben Brunk183f0562015-08-12 12:55:02 -07001835 mStatusWaiters++;
1836
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001837 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001838 if (!active && mUseHalBufManager) {
1839 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001840 if (mStatus == STATUS_ACTIVE) {
1841 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001842 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001843 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001844 mRequestBufferSM.onWaitUntilIdle();
1845 }
1846
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001847 bool stateSeen = false;
1848 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001849 if (active == (mStatus == STATUS_ACTIVE)) {
1850 // Desired state is current
1851 break;
1852 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001853
1854 res = mStatusChanged.waitRelative(mLock, timeout);
1855 if (res != OK) break;
1856
Ruben Brunk183f0562015-08-12 12:55:02 -07001857 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1858 // transitions.
1859 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1860 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1861 __FUNCTION__);
1862
1863 // Encountered desired state since we began waiting
1864 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001865 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1866 stateSeen = true;
1867 break;
1868 }
1869 }
1870 } while (!stateSeen);
1871
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07001872 if (signalPipelineDrain) {
1873 mRequestThread->resetPipelineDrain();
1874 }
1875
Ruben Brunk183f0562015-08-12 12:55:02 -07001876 mStatusWaiters--;
1877
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001878 return res;
1879}
1880
1881
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001882status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001883 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001884 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001885
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001886 if (listener != NULL && mListener != NULL) {
1887 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1888 }
1889 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001890 mRequestThread->setNotificationListener(listener);
1891 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001892
1893 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001894}
1895
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001896bool Camera3Device::willNotify3A() {
1897 return false;
1898}
1899
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001900status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001901 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001902 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001903
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001904 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001905 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1906 if (st == std::cv_status::timeout) {
1907 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001908 }
1909 }
1910 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001911}
1912
Jianing Weicb0652e2014-03-12 18:29:36 -07001913status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001914 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001915 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001916
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001917 if (mResultQueue.empty()) {
1918 return NOT_ENOUGH_DATA;
1919 }
1920
Jianing Weicb0652e2014-03-12 18:29:36 -07001921 if (frame == NULL) {
1922 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1923 return BAD_VALUE;
1924 }
1925
1926 CaptureResult &result = *(mResultQueue.begin());
1927 frame->mResultExtras = result.mResultExtras;
1928 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001929 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001930 mResultQueue.erase(mResultQueue.begin());
1931
1932 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001933}
1934
1935status_t Camera3Device::triggerAutofocus(uint32_t id) {
1936 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001937 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001938
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001939 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1940 // Mix-in this trigger into the next request and only the next request.
1941 RequestTrigger trigger[] = {
1942 {
1943 ANDROID_CONTROL_AF_TRIGGER,
1944 ANDROID_CONTROL_AF_TRIGGER_START
1945 },
1946 {
1947 ANDROID_CONTROL_AF_TRIGGER_ID,
1948 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001949 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001950 };
1951
1952 return mRequestThread->queueTrigger(trigger,
1953 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001954}
1955
1956status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1957 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001958 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001959
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001960 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1961 // Mix-in this trigger into the next request and only the next request.
1962 RequestTrigger trigger[] = {
1963 {
1964 ANDROID_CONTROL_AF_TRIGGER,
1965 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1966 },
1967 {
1968 ANDROID_CONTROL_AF_TRIGGER_ID,
1969 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001970 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001971 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001972
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001973 return mRequestThread->queueTrigger(trigger,
1974 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001975}
1976
1977status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1978 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001979 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001980
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001981 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1982 // Mix-in this trigger into the next request and only the next request.
1983 RequestTrigger trigger[] = {
1984 {
1985 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1986 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1987 },
1988 {
1989 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1990 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001991 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001992 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001993
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001994 return mRequestThread->queueTrigger(trigger,
1995 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001996}
1997
Jianing Weicb0652e2014-03-12 18:29:36 -07001998status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001999 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002000 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002001 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002002
Zhijun He7ef20392014-04-21 16:04:17 -07002003 {
2004 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002005
2006 // b/116514106 "disconnect()" can get called twice for the same device. The
2007 // camera device will not be initialized during the second run.
2008 if (mStatus == STATUS_UNINITIALIZED) {
2009 return OK;
2010 }
2011
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002012 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002013 }
2014
Emilian Peev08dd2452017-04-06 16:55:14 +01002015 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002016}
2017
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002018status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002019 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2020}
2021
2022status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002023 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002024 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002025 Mutex::Autolock il(mInterfaceLock);
2026 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002027
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002028 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2029 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002030 CLOGE("Stream %d does not exist", streamId);
2031 return BAD_VALUE;
2032 }
2033
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002034 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002035 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002036 return BAD_VALUE;
2037 }
2038
2039 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002040 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002041 return BAD_VALUE;
2042 }
2043
Ruben Brunkc78ac262015-08-13 17:58:46 -07002044 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002045}
2046
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002047status_t Camera3Device::tearDown(int streamId) {
2048 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002049 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002050 Mutex::Autolock il(mInterfaceLock);
2051 Mutex::Autolock l(mLock);
2052
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002053 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2054 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002055 CLOGE("Stream %d does not exist", streamId);
2056 return BAD_VALUE;
2057 }
2058
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002059 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2060 CLOGE("Stream %d is a target of a in-progress request", streamId);
2061 return BAD_VALUE;
2062 }
2063
2064 return stream->tearDown();
2065}
2066
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002067status_t Camera3Device::addBufferListenerForStream(int streamId,
2068 wp<Camera3StreamBufferListener> listener) {
2069 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002070 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002071 Mutex::Autolock il(mInterfaceLock);
2072 Mutex::Autolock l(mLock);
2073
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002074 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2075 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002076 CLOGE("Stream %d does not exist", streamId);
2077 return BAD_VALUE;
2078 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002079 stream->addBufferListener(listener);
2080
2081 return OK;
2082}
2083
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002084/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002085 * Methods called by subclasses
2086 */
2087
2088void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002089 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002090 {
2091 // Need mLock to safely update state and synchronize to current
2092 // state of methods in flight.
2093 Mutex::Autolock l(mLock);
2094 // We can get various system-idle notices from the status tracker
2095 // while starting up. Only care about them if we've actually sent
2096 // in some requests recently.
2097 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2098 return;
2099 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002100 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2101 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002102 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002103
2104 // Skip notifying listener if we're doing some user-transparent
2105 // state changes
2106 if (mPauseStateNotify) return;
2107 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002108
2109 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002110 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002111 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002112 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002113 }
2114 if (idle && listener != NULL) {
2115 listener->notifyIdle();
2116 }
2117}
2118
Shuzhen Wang758c2152017-01-10 18:26:18 -08002119status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002120 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002121 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002122 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2123 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002124
2125 if (surfaceIds == nullptr) {
2126 return BAD_VALUE;
2127 }
2128
Zhijun He5d677d12016-05-29 16:52:39 -07002129 Mutex::Autolock il(mInterfaceLock);
2130 Mutex::Autolock l(mLock);
2131
Shuzhen Wang758c2152017-01-10 18:26:18 -08002132 if (consumers.size() == 0) {
2133 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002134 return BAD_VALUE;
2135 }
2136
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002137 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2138 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002139 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002140 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002141 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002142
2143 // isConsumerConfigurationDeferred will be off after setConsumers
2144 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002145 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002146 if (res != OK) {
2147 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2148 return res;
2149 }
2150
Emilian Peev40ead602017-09-26 15:46:36 +01002151 for (auto &consumer : consumers) {
2152 int id = stream->getSurfaceId(consumer);
2153 if (id < 0) {
2154 CLOGE("Invalid surface id!");
2155 return BAD_VALUE;
2156 }
2157 surfaceIds->push_back(id);
2158 }
2159
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002160 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002161 if (!stream->isConfiguring()) {
2162 CLOGE("Stream %d was already fully configured.", streamId);
2163 return INVALID_OPERATION;
2164 }
Zhijun He5d677d12016-05-29 16:52:39 -07002165
Shuzhen Wang0129d522016-10-30 22:43:41 -07002166 res = stream->finishConfiguration();
2167 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002168 // If finishConfiguration fails due to abandoned surface, do not set
2169 // device to error state.
2170 bool isSurfaceAbandoned =
2171 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2172 if (!isSurfaceAbandoned) {
2173 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2174 stream->getId(), strerror(-res), res);
2175 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002176 return res;
2177 }
Zhijun He5d677d12016-05-29 16:52:39 -07002178 }
2179
2180 return OK;
2181}
2182
Emilian Peev40ead602017-09-26 15:46:36 +01002183status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2184 const std::vector<OutputStreamInfo> &outputInfo,
2185 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2186 Mutex::Autolock il(mInterfaceLock);
2187 Mutex::Autolock l(mLock);
2188
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002189 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2190 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002191 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002192 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002193 }
2194
2195 for (const auto &it : removedSurfaceIds) {
2196 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2197 CLOGE("Shared surface still part of a pending request!");
2198 return -EBUSY;
2199 }
2200 }
2201
Emilian Peev40ead602017-09-26 15:46:36 +01002202 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2203 if (res != OK) {
2204 CLOGE("Stream %d failed to update stream (error %d %s) ",
2205 streamId, res, strerror(-res));
2206 if (res == UNKNOWN_ERROR) {
2207 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2208 __FUNCTION__);
2209 }
2210 return res;
2211 }
2212
2213 return res;
2214}
2215
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002216status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2217 Mutex::Autolock il(mInterfaceLock);
2218 Mutex::Autolock l(mLock);
2219
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002220 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2221 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002222 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2223 return BAD_VALUE;
2224 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002225 return stream->dropBuffers(dropping);
2226}
2227
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002228/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002229 * Camera3Device private methods
2230 */
2231
2232sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002233 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002234 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002235
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002236 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002237 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002238
2239 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002240 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002241 if (inputStreams.count > 0) {
2242 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002243 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002244 CLOGE("Request references unknown input stream %d",
2245 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002246 return NULL;
2247 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002248
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002249 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002250 SET_ERR_L("%s: input stream %d is not configured!",
2251 __FUNCTION__, mInputStream->getId());
2252 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002253 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002254 // Check if stream prepare is blocking requests.
2255 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002256 CLOGE("Request references an input stream that's being prepared!");
2257 return NULL;
2258 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002259
2260 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002261 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002262 }
2263
2264 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002265 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002266 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002267 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002268 return NULL;
2269 }
2270
2271 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002272 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2273 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002274 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002275 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002276 return NULL;
2277 }
Zhijun He5d677d12016-05-29 16:52:39 -07002278 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002279 auto iter = surfaceMap.find(streams.data.i32[i]);
2280 if (iter != surfaceMap.end()) {
2281 const std::vector<size_t>& surfaces = iter->second;
2282 for (const auto& surface : surfaces) {
2283 if (stream->isConsumerConfigurationDeferred(surface)) {
2284 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2285 "due to deferred consumer", stream->getId(), surface);
2286 return NULL;
2287 }
2288 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002289 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002290 }
2291
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002292 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002293 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2294 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002295 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002296 // Check if stream prepare is blocking requests.
2297 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002298 CLOGE("Request references an output stream that's being prepared!");
2299 return NULL;
2300 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002301
2302 newRequest->mOutputStreams.push(stream);
2303 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002304 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002305 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002306
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002307 auto rotateAndCropEntry =
2308 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2309 if (rotateAndCropEntry.count > 0 &&
2310 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2311 newRequest->mRotateAndCropAuto = true;
2312 } else {
2313 newRequest->mRotateAndCropAuto = false;
2314 }
2315
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002316 auto zoomRatioEntry =
2317 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2318 if (zoomRatioEntry.count > 0 &&
2319 zoomRatioEntry.data.f[0] == 1.0f) {
2320 newRequest->mZoomRatioIs1x = true;
2321 } else {
2322 newRequest->mZoomRatioIs1x = false;
2323 }
2324
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002325 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002326}
2327
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002328void Camera3Device::cancelStreamsConfigurationLocked() {
2329 int res = OK;
2330 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2331 res = mInputStream->cancelConfiguration();
2332 if (res != OK) {
2333 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2334 mInputStream->getId(), strerror(-res), res);
2335 }
2336 }
2337
2338 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002339 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002340 if (outputStream->isConfiguring()) {
2341 res = outputStream->cancelConfiguration();
2342 if (res != OK) {
2343 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2344 outputStream->getId(), strerror(-res), res);
2345 }
2346 }
2347 }
2348
2349 // Return state to that at start of call, so that future configures
2350 // properly clean things up
2351 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2352 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002353
2354 res = mPreparerThread->resume();
2355 if (res != OK) {
2356 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2357 }
2358}
2359
Emilian Peev0d0191e2020-04-21 17:01:18 -07002360bool Camera3Device::checkAbandonedStreamsLocked() {
2361 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2362 return true;
2363 }
2364
2365 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2366 auto stream = mOutputStreams[i];
2367 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2368 return true;
2369 }
2370 }
2371
2372 return false;
2373}
2374
Emilian Peev3bead5f2020-05-28 17:29:08 -07002375bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002376 ATRACE_CALL();
2377 bool ret = false;
2378
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002379 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002380 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2381
2382 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002383 if (checkAbandonedStreamsLocked()) {
2384 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2385 __FUNCTION__);
2386 return true;
2387 }
2388
Emilian Peev3bead5f2020-05-28 17:29:08 -07002389 status_t rc = NO_ERROR;
2390 bool markClientActive = false;
2391 if (mStatus == STATUS_ACTIVE) {
2392 markClientActive = true;
2393 mPauseStateNotify = true;
2394 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2395
2396 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2397 }
2398
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002399 if (rc == NO_ERROR) {
2400 mNeedConfig = true;
2401 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2402 if (rc == NO_ERROR) {
2403 ret = true;
2404 mPauseStateNotify = false;
2405 //Moving to active state while holding 'mLock' is important.
2406 //There could be pending calls to 'create-/deleteStream' which
2407 //will trigger another stream configuration while the already
2408 //present streams end up with outstanding buffers that will
2409 //not get drained.
2410 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002411 } else if (rc == DEAD_OBJECT) {
2412 // DEAD_OBJECT can be returned if either the consumer surface is
2413 // abandoned, or the HAL has died.
2414 // - If the HAL has died, configureStreamsLocked call will set
2415 // device to error state,
2416 // - If surface is abandoned, we should not set device to error
2417 // state.
2418 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002419 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002420 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002421 }
2422 } else {
2423 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2424 }
2425
Emilian Peev3bead5f2020-05-28 17:29:08 -07002426 if (markClientActive) {
2427 mStatusTracker->markComponentActive(clientStatusId);
2428 }
2429
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002430 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002431}
2432
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002433status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002434 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002435 ATRACE_CALL();
2436 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002437
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002438 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002439 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002440 return INVALID_OPERATION;
2441 }
2442
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002443 if (operatingMode < 0) {
2444 CLOGE("Invalid operating mode: %d", operatingMode);
2445 return BAD_VALUE;
2446 }
2447
2448 bool isConstrainedHighSpeed =
2449 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2450 operatingMode;
2451
2452 if (mOperatingMode != operatingMode) {
2453 mNeedConfig = true;
2454 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2455 mOperatingMode = operatingMode;
2456 }
2457
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002458 // In case called from configureStreams, abort queued input buffers not belonging to
2459 // any pending requests.
2460 if (mInputStream != NULL && notifyRequestThread) {
2461 while (true) {
2462 camera3_stream_buffer_t inputBuffer;
2463 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2464 /*respectHalLimit*/ false);
2465 if (res != OK) {
2466 // Exhausted acquiring all input buffers.
2467 break;
2468 }
2469
2470 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2471 res = mInputStream->returnInputBuffer(inputBuffer);
2472 if (res != OK) {
2473 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2474 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2475 }
2476 }
2477 }
2478
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002479 if (!mNeedConfig) {
2480 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2481 return OK;
2482 }
2483
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002484 // Workaround for device HALv3.2 or older spec bug - zero streams requires
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002485 // adding a fake stream instead.
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002486 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2487 if (mOutputStreams.size() == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002488 addFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002489 } else {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002490 tryRemoveFakeStreamLocked();
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002491 }
2492
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002493 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002494 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002495
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002496 mPreparerThread->pause();
2497
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002498 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002499 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002500 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2501
2502 Vector<camera3_stream_t*> streams;
2503 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002504 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002505
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002506
2507 if (mInputStream != NULL) {
2508 camera3_stream_t *inputStream;
2509 inputStream = mInputStream->startConfiguration();
2510 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002511 CLOGE("Can't start input stream configuration");
2512 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002513 return INVALID_OPERATION;
2514 }
2515 streams.add(inputStream);
2516 }
2517
2518 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002519
2520 // Don't configure bidi streams twice, nor add them twice to the list
2521 if (mOutputStreams[i].get() ==
2522 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2523
2524 config.num_streams--;
2525 continue;
2526 }
2527
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002528 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002529 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002530 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002531 CLOGE("Can't start output stream configuration");
2532 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002533 return INVALID_OPERATION;
2534 }
2535 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002536
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002537 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002538 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2539 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002540 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2541 bufferSizes[k] = static_cast<uint32_t>(
2542 getJpegBufferSize(outputStream->width, outputStream->height));
2543 } else if (outputStream->data_space ==
2544 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2545 bufferSizes[k] = outputStream->width * outputStream->height;
2546 } else {
2547 ALOGW("%s: Blob dataSpace %d not supported",
2548 __FUNCTION__, outputStream->data_space);
2549 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002550 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002551 }
2552
2553 config.streams = streams.editArray();
2554
2555 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002556 // max_buffers, usage, and priv fields, as well as data_space and format
2557 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002558
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002559 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002560 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002561 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002562
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002563 if (res == BAD_VALUE) {
2564 // HAL rejected this set of streams as unsupported, clean up config
2565 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002566 CLOGE("Set of requested inputs/outputs not supported by HAL");
2567 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002568 return BAD_VALUE;
2569 } else if (res != OK) {
2570 // Some other kind of error from configure_streams - this is not
2571 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002572 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2573 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002574 return res;
2575 }
2576
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002577 // Finish all stream configuration immediately.
2578 // TODO: Try to relax this later back to lazy completion, which should be
2579 // faster
2580
Igor Murashkin073f8572013-05-02 14:59:28 -07002581 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002582 bool streamReConfigured = false;
2583 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002584 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002585 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002586 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002587 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002588 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2589 return DEAD_OBJECT;
2590 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002591 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002592 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002593 if (streamReConfigured) {
2594 mInterface->onStreamReConfigured(mInputStream->getId());
2595 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002596 }
2597
2598 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002599 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002600 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002601 bool streamReConfigured = false;
2602 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002603 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002604 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002605 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002606 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002607 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2608 return DEAD_OBJECT;
2609 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002610 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002611 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002612 if (streamReConfigured) {
2613 mInterface->onStreamReConfigured(outputStream->getId());
2614 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002615 }
2616 }
2617
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002618 // Request thread needs to know to avoid using repeat-last-settings protocol
2619 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002620 if (notifyRequestThread) {
2621 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2622 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002623
Zhijun He90f7c372016-08-16 16:19:43 -07002624 char value[PROPERTY_VALUE_MAX];
2625 property_get("camera.fifo.disable", value, "0");
2626 int32_t disableFifo = atoi(value);
2627 if (disableFifo != 1) {
2628 // Boost priority of request thread to SCHED_FIFO.
2629 pid_t requestThreadTid = mRequestThread->getTid();
2630 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002631 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002632 if (res != OK) {
2633 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2634 strerror(-res), res);
2635 } else {
2636 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2637 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002638 }
2639
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002640 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002641 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2642 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2643 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2644 sessionParams.unlock(newSessionParams);
2645 mSessionParams.unlock(currentSessionParams);
2646 if (updateSessionParams) {
2647 mSessionParams = sessionParams;
2648 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002649
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002650 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002651
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002652 internalUpdateStatusLocked((mFakeStreamId == NO_STREAM) ?
Ruben Brunk183f0562015-08-12 12:55:02 -07002653 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002654
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002655 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002656
Zhijun He0a210512014-07-24 13:45:15 -07002657 // tear down the deleted streams after configure streams.
2658 mDeletedStreams.clear();
2659
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002660 auto rc = mPreparerThread->resume();
2661 if (rc != OK) {
2662 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2663 return rc;
2664 }
2665
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002666 if (mFakeStreamId == NO_STREAM) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002667 mRequestBufferSM.onStreamsConfigured();
2668 }
2669
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002670 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002671}
2672
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002673status_t Camera3Device::addFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002674 ATRACE_CALL();
2675 status_t res;
2676
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002677 if (mFakeStreamId != NO_STREAM) {
2678 // Should never be adding a second fake stream when one is already
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002679 // active
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002680 SET_ERR_L("%s: Camera %s: A fake stream already exists!",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002681 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002682 return INVALID_OPERATION;
2683 }
2684
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002685 ALOGV("%s: Camera %s: Adding a fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002686
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002687 sp<Camera3OutputStreamInterface> fakeStream =
2688 new Camera3FakeStream(mNextStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002689
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002690 res = mOutputStreams.add(mNextStreamId, fakeStream);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002691 if (res < 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002692 SET_ERR_L("Can't add fake stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002693 return res;
2694 }
2695
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002696 mFakeStreamId = mNextStreamId;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002697 mNextStreamId++;
2698
2699 return OK;
2700}
2701
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002702status_t Camera3Device::tryRemoveFakeStreamLocked() {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002703 ATRACE_CALL();
2704 status_t res;
2705
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002706 if (mFakeStreamId == NO_STREAM) return OK;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002707 if (mOutputStreams.size() == 1) return OK;
2708
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002709 ALOGV("%s: Camera %s: Removing the fake stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002710
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002711 // Ok, have a fake stream and there's at least one other output stream,
2712 // so remove the fake
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002713
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002714 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mFakeStreamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002715 if (deletedStream == nullptr) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002716 SET_ERR_L("Fake stream %d does not appear to exist", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002717 return INVALID_OPERATION;
2718 }
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002719 mOutputStreams.remove(mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002720
2721 // Free up the stream endpoint so that it can be used by some other stream
2722 res = deletedStream->disconnect();
2723 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002724 SET_ERR_L("Can't disconnect deleted fake stream %d", mFakeStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002725 // fall through since we want to still list the stream as deleted.
2726 }
2727 mDeletedStreams.add(deletedStream);
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002728 mFakeStreamId = NO_STREAM;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002729
2730 return res;
2731}
2732
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002733void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002734 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002735 Mutex::Autolock l(mLock);
2736 va_list args;
2737 va_start(args, fmt);
2738
2739 setErrorStateLockedV(fmt, args);
2740
2741 va_end(args);
2742}
2743
2744void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002745 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002746 Mutex::Autolock l(mLock);
2747 setErrorStateLockedV(fmt, args);
2748}
2749
2750void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2751 va_list args;
2752 va_start(args, fmt);
2753
2754 setErrorStateLockedV(fmt, args);
2755
2756 va_end(args);
2757}
2758
2759void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002760 // Print out all error messages to log
2761 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002762 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002763
2764 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002765 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002766
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002767 mErrorCause = errorCause;
2768
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002769 if (mRequestThread != nullptr) {
2770 mRequestThread->setPaused(true);
2771 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002772 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002773
2774 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002775 sp<NotificationListener> listener = mListener.promote();
2776 if (listener != NULL) {
2777 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002778 CaptureResultExtras());
2779 }
2780
2781 // Save stack trace. View by dumping it later.
2782 CameraTraces::saveTrace();
2783 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002784}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002785
2786/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002787 * In-flight request management
2788 */
2789
Jianing Weicb0652e2014-03-12 18:29:36 -07002790status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002791 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002792 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002793 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002794 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08002795 const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002796 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002797 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002798
2799 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002800 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002801 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002802 rotateAndCropAuto, cameraIdsWithZoom, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002803 if (res < 0) return res;
2804
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002805 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002806 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2807 // avoid a deadlock during reprocess requests.
2808 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002809 if (mStatusTracker != nullptr) {
2810 mStatusTracker->markComponentActive(mInFlightStatusId);
2811 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002812 }
2813
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002814 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002815 return OK;
2816}
2817
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002818void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002819 // Indicate idle inFlightMap to the status tracker
2820 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002821 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002822 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2823 // avoid a deadlock during reprocess requests.
2824 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002825 if (mStatusTracker != nullptr) {
2826 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2827 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002828 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002829 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002830}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002831
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002832void Camera3Device::checkInflightMapLengthLocked() {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04002833 // Validation check - if we have too many in-flight frames with long total inflight duration,
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002834 // something has likely gone wrong. This might still be legit only if application send in
2835 // a long burst of long exposure requests.
2836 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2837 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2838 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2839 mInFlightMap.size(), mExpectedInflightDuration);
2840 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2841 kInFlightWarnLimitHighSpeed) {
2842 CLOGW("In-flight list too large for high speed configuration: %zu,"
2843 "total inflight duration %" PRIu64,
2844 mInFlightMap.size(), mExpectedInflightDuration);
2845 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002846 }
2847}
2848
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002849void Camera3Device::onInflightMapFlushedLocked() {
2850 mExpectedInflightDuration = 0;
2851}
2852
2853void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002854 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002855 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2856 mInFlightMap.removeItemsAt(idx, 1);
2857
2858 onInflightEntryRemovedLocked(duration);
2859}
2860
2861
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002862void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002863 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002864 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002865 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002866 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002867 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002868 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002869
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002870 FlushInflightReqStates states {
2871 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
2872 listener, *this, *mInterface, *this};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002873
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002874 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002875}
2876
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002877CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002878 ALOGV("%s", __FUNCTION__);
2879
Igor Murashkin1e479c02013-09-06 16:55:14 -07002880 CameraMetadata retVal;
2881
2882 if (mRequestThread != NULL) {
2883 retVal = mRequestThread->getLatestRequest();
2884 }
2885
Igor Murashkin1e479c02013-09-06 16:55:14 -07002886 return retVal;
2887}
2888
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002889void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002890 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2891 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2892
2893 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2894 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002895}
2896
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002897/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002898 * HalInterface inner class methods
2899 */
2900
Yifan Hongf79b5542017-04-11 14:44:25 -07002901Camera3Device::HalInterface::HalInterface(
2902 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002903 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002904 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002905 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002906 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08002907 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002908 mIsReconfigurationQuerySupported(true),
2909 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002910 // Check with hardware service manager if we can downcast these interfaces
2911 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002912 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
2913 if (castResult_3_6.isOk()) {
2914 mHidlSession_3_6 = castResult_3_6;
2915 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002916 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
2917 if (castResult_3_5.isOk()) {
2918 mHidlSession_3_5 = castResult_3_5;
2919 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002920 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
2921 if (castResult_3_4.isOk()) {
2922 mHidlSession_3_4 = castResult_3_4;
2923 }
2924 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
2925 if (castResult_3_3.isOk()) {
2926 mHidlSession_3_3 = castResult_3_3;
2927 }
2928}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002929
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002930Camera3Device::HalInterface::HalInterface() :
2931 mUseHalBufManager(false),
2932 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002933
2934Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002935 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002936 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002937 mUseHalBufManager(other.mUseHalBufManager),
2938 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002939
2940bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01002941 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002942}
2943
2944void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002945 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00002946 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00002947 mHidlSession_3_4.clear();
2948 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002949 mHidlSession.clear();
2950}
2951
2952status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2953 camera3_request_template_t templateId,
2954 /*out*/ camera_metadata_t **requestTemplate) {
2955 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
2956 if (!valid()) return INVALID_OPERATION;
2957 status_t res = OK;
2958
Emilian Peev31abd0a2017-05-11 18:37:46 +01002959 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002960
2961 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01002962 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002963 status = s;
2964 if (status == common::V1_0::Status::OK) {
2965 const camera_metadata *r =
2966 reinterpret_cast<const camera_metadata_t*>(request.data());
2967 size_t expectedSize = request.size();
2968 int ret = validate_camera_metadata_structure(r, &expectedSize);
2969 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
2970 *requestTemplate = clone_camera_metadata(r);
2971 if (*requestTemplate == nullptr) {
2972 ALOGE("%s: Unable to clone camera metadata received from HAL",
2973 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01002974 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002975 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002976 } else {
2977 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
2978 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01002979 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002980 }
2981 };
2982 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08002983 RequestTemplate id;
2984 switch (templateId) {
2985 case CAMERA3_TEMPLATE_PREVIEW:
2986 id = RequestTemplate::PREVIEW;
2987 break;
2988 case CAMERA3_TEMPLATE_STILL_CAPTURE:
2989 id = RequestTemplate::STILL_CAPTURE;
2990 break;
2991 case CAMERA3_TEMPLATE_VIDEO_RECORD:
2992 id = RequestTemplate::VIDEO_RECORD;
2993 break;
2994 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
2995 id = RequestTemplate::VIDEO_SNAPSHOT;
2996 break;
2997 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
2998 id = RequestTemplate::ZERO_SHUTTER_LAG;
2999 break;
3000 case CAMERA3_TEMPLATE_MANUAL:
3001 id = RequestTemplate::MANUAL;
3002 break;
3003 default:
3004 // Unknown template ID, or this HAL is too old to support it
3005 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003006 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003007 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003008
Emilian Peev31abd0a2017-05-11 18:37:46 +01003009 if (!err.isOk()) {
3010 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3011 res = DEAD_OBJECT;
3012 } else {
3013 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003014 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003015
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003016 return res;
3017}
3018
Emilian Peev4ec17882019-01-24 17:16:58 -08003019bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3020 CameraMetadata& newSessionParams) {
3021 // We do reconfiguration by default;
3022 bool ret = true;
3023 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3024 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3025 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3026 oldSessionParams.getAndLock());
3027 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3028 newSessionParams.getAndLock());
3029 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3030 get_camera_metadata_size(oldSessioMeta));
3031 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3032 get_camera_metadata_size(newSessioMeta));
3033 hardware::camera::common::V1_0::Status callStatus;
3034 bool required;
3035 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3036 bool requiredFlag) {
3037 callStatus = s;
3038 required = requiredFlag;
3039 };
3040 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3041 oldSessionParams.unlock(oldSessioMeta);
3042 newSessionParams.unlock(newSessioMeta);
3043 if (err.isOk()) {
3044 switch (callStatus) {
3045 case hardware::camera::common::V1_0::Status::OK:
3046 ret = required;
3047 break;
3048 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3049 mIsReconfigurationQuerySupported = false;
3050 ret = true;
3051 break;
3052 default:
3053 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3054 ret = true;
3055 }
3056 } else {
3057 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3058 ret = true;
3059 }
3060 }
3061
3062 return ret;
3063}
3064
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003065status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003066 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003067 ATRACE_NAME("CameraHal::configureStreams");
3068 if (!valid()) return INVALID_OPERATION;
3069 status_t res = OK;
3070
Emilian Peev31abd0a2017-05-11 18:37:46 +01003071 // Convert stream config to HIDL
3072 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003073 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3074 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3075 requestedConfiguration3_2.streams.resize(config->num_streams);
3076 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003077 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003078 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3079 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003080 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003081
Emilian Peev31abd0a2017-05-11 18:37:46 +01003082 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3083 cam3stream->setBufferFreedListener(this);
3084 int streamId = cam3stream->getId();
3085 StreamType streamType;
3086 switch (src->stream_type) {
3087 case CAMERA3_STREAM_OUTPUT:
3088 streamType = StreamType::OUTPUT;
3089 break;
3090 case CAMERA3_STREAM_INPUT:
3091 streamType = StreamType::INPUT;
3092 break;
3093 default:
3094 ALOGE("%s: Stream %d: Unsupported stream type %d",
3095 __FUNCTION__, streamId, config->streams[i]->stream_type);
3096 return BAD_VALUE;
3097 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003098 dst3_2.id = streamId;
3099 dst3_2.streamType = streamType;
3100 dst3_2.width = src->width;
3101 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003102 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003103 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003104 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3105 // to HAL are original, not the overriden ones.
3106 if (mHidlSession_3_5 != nullptr) {
3107 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3108 cam3stream->getOriginalFormat() : src->format);
3109 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3110 cam3stream->getOriginalDataSpace() : src->data_space);
3111 } else {
3112 dst3_2.format = mapToPixelFormat(src->format);
3113 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3114 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003115 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003116 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003117 if (src->physical_camera_id != nullptr) {
3118 dst3_4.physicalCameraId = src->physical_camera_id;
3119 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003120
3121 activeStreams.insert(streamId);
3122 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003123 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003124 }
3125 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003126 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003127
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003128 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003129 res = mapToStreamConfigurationMode(
3130 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003131 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003132 if (res != OK) {
3133 return res;
3134 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003135 requestedConfiguration3_2.operationMode = operationMode;
3136 requestedConfiguration3_4.operationMode = operationMode;
3137 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003138 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3139 get_camera_metadata_size(sessionParams));
3140
Emilian Peev31abd0a2017-05-11 18:37:46 +01003141 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003142 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003143 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003144 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003145 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003146
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003147 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003148 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3149 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003150 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003151 };
3152
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003153 auto configStream36Cb = [&status, &finalConfiguration3_6]
3154 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3155 finalConfiguration3_6 = halConfiguration;
3156 status = s;
3157 };
3158
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003159 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3160 (hardware::Return<void>& err) -> status_t {
3161 if (!err.isOk()) {
3162 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3163 return DEAD_OBJECT;
3164 }
3165 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3166 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3167 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3168 }
3169 return OK;
3170 };
3171
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003172 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3173 (hardware::Return<void>& err) -> status_t {
3174 if (!err.isOk()) {
3175 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3176 return DEAD_OBJECT;
3177 }
3178 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3179 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3180 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3181 }
3182 return OK;
3183 };
3184
Shuzhen Wang92653952019-05-07 15:11:43 -07003185 // See which version of HAL we have
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003186 if (mHidlSession_3_6 != nullptr) {
3187 ALOGV("%s: v3.6 device found", __FUNCTION__);
3188 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3189 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3190 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3191 auto err = mHidlSession_3_6->configureStreams_3_6(
3192 requestedConfiguration3_5, configStream36Cb);
3193 res = postprocConfigStream36(err);
3194 if (res != OK) {
3195 return res;
3196 }
3197 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003198 ALOGV("%s: v3.5 device found", __FUNCTION__);
3199 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3200 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3201 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3202 auto err = mHidlSession_3_5->configureStreams_3_5(
3203 requestedConfiguration3_5, configStream34Cb);
3204 res = postprocConfigStream34(err);
3205 if (res != OK) {
3206 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003207 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003208 } else if (mHidlSession_3_4 != nullptr) {
3209 // We do; use v3.4 for the call
3210 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003211 auto err = mHidlSession_3_4->configureStreams_3_4(
3212 requestedConfiguration3_4, configStream34Cb);
3213 res = postprocConfigStream34(err);
3214 if (res != OK) {
3215 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003216 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003217 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003218 // We do; use v3.3 for the call
3219 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003220 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003221 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003222 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003223 finalConfiguration = halConfiguration;
3224 status = s;
3225 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003226 if (!err.isOk()) {
3227 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3228 return DEAD_OBJECT;
3229 }
3230 } else {
3231 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3232 ALOGV("%s: v3.2 device found", __FUNCTION__);
3233 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003234 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003235 [&status, &finalConfiguration_3_2]
3236 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3237 finalConfiguration_3_2 = halConfiguration;
3238 status = s;
3239 });
3240 if (!err.isOk()) {
3241 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3242 return DEAD_OBJECT;
3243 }
3244 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3245 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3246 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3247 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003248 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003249 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003250 }
3251
3252 if (status != common::V1_0::Status::OK ) {
3253 return CameraProviderManager::mapToStatusT(status);
3254 }
3255
3256 // And convert output stream configuration from HIDL
3257
3258 for (size_t i = 0; i < config->num_streams; i++) {
3259 camera3_stream_t *dst = config->streams[i];
3260 int streamId = Camera3Stream::cast(dst)->getId();
3261
3262 // Start scan at i, with the assumption that the stream order matches
3263 size_t realIdx = i;
3264 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003265 size_t halStreamCount = finalConfiguration.streams.size();
3266 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003267 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003268 found = true;
3269 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003270 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003271 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003272 }
3273 if (!found) {
3274 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3275 __FUNCTION__, streamId);
3276 return INVALID_OPERATION;
3277 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003278 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003279 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003280
Emilian Peev710c1422017-08-30 11:19:38 +01003281 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003282 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3283 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3284
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003285 if (mHidlSession_3_6 != nullptr) {
3286 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3287 }
3288
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003289 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003290 dstStream->setFormatOverride(false);
3291 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003292 if (dst->format != overrideFormat) {
3293 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3294 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003295 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003296 if (dst->data_space != overrideDataSpace) {
3297 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3298 streamId, dst->format);
3299 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003300 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003301 bool needFormatOverride =
3302 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3303 bool needDataspaceOverride =
3304 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003305 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003306 dstStream->setFormatOverride(needFormatOverride);
3307 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003308 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003309 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003310 }
3311
Emilian Peev31abd0a2017-05-11 18:37:46 +01003312 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003313 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003314 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003315 __FUNCTION__, streamId);
3316 return INVALID_OPERATION;
3317 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003318 dstStream->setUsage(
3319 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003320 } else {
3321 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003322 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003323 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3324 __FUNCTION__, streamId);
3325 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003326 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003327 dstStream->setUsage(
3328 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003329 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003330 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003331 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003332
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003333 return res;
3334}
3335
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003336status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003337 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003338 /*out*/std::vector<native_handle_t*>* handlesCreated,
3339 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003340 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003341 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3342 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3343 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003344 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003345 }
3346
3347 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003348
3349 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003350
3351 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003352 if (request->input_buffer != nullptr) {
3353 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3354 buffer_handle_t buf = *(request->input_buffer->buffer);
3355 auto pair = getBufferId(buf, streamId);
3356 bool isNewBuffer = pair.first;
3357 uint64_t bufferId = pair.second;
3358 captureRequest->inputBuffer.streamId = streamId;
3359 captureRequest->inputBuffer.bufferId = bufferId;
3360 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3361 captureRequest->inputBuffer.status = BufferStatus::OK;
3362 native_handle_t *acquireFence = nullptr;
3363 if (request->input_buffer->acquire_fence != -1) {
3364 acquireFence = native_handle_create(1,0);
3365 acquireFence->data[0] = request->input_buffer->acquire_fence;
3366 handlesCreated->push_back(acquireFence);
3367 }
3368 captureRequest->inputBuffer.acquireFence = acquireFence;
3369 captureRequest->inputBuffer.releaseFence = nullptr;
3370
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003371 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003372 request->input_buffer->buffer);
3373 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003374 } else {
3375 captureRequest->inputBuffer.streamId = -1;
3376 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3377 }
3378
3379 captureRequest->outputBuffers.resize(request->num_output_buffers);
3380 for (size_t i = 0; i < request->num_output_buffers; i++) {
3381 const camera3_stream_buffer_t *src = request->output_buffers + i;
3382 StreamBuffer &dst = captureRequest->outputBuffers[i];
3383 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003384 if (src->buffer != nullptr) {
3385 buffer_handle_t buf = *(src->buffer);
3386 auto pair = getBufferId(buf, streamId);
3387 bool isNewBuffer = pair.first;
3388 dst.bufferId = pair.second;
3389 dst.buffer = isNewBuffer ? buf : nullptr;
3390 native_handle_t *acquireFence = nullptr;
3391 if (src->acquire_fence != -1) {
3392 acquireFence = native_handle_create(1,0);
3393 acquireFence->data[0] = src->acquire_fence;
3394 handlesCreated->push_back(acquireFence);
3395 }
3396 dst.acquireFence = acquireFence;
3397 } else if (mUseHalBufManager) {
3398 // HAL buffer management path
3399 dst.bufferId = BUFFER_ID_NO_BUFFER;
3400 dst.buffer = nullptr;
3401 dst.acquireFence = nullptr;
3402 } else {
3403 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3404 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003405 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003406 dst.streamId = streamId;
3407 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003408 dst.releaseFence = nullptr;
3409
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003410 // Output buffers are empty when using HAL buffer manager
3411 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003412 mBufferRecords.pushInflightBuffer(
3413 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003414 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003415 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003416 }
3417 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003418 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003419}
3420
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003421void Camera3Device::HalInterface::cleanupNativeHandles(
3422 std::vector<native_handle_t*> *handles, bool closeFd) {
3423 if (handles == nullptr) {
3424 return;
3425 }
3426 if (closeFd) {
3427 for (auto& handle : *handles) {
3428 native_handle_close(handle);
3429 }
3430 }
3431 for (auto& handle : *handles) {
3432 native_handle_delete(handle);
3433 }
3434 handles->clear();
3435 return;
3436}
3437
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003438status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3439 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3440 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3441 if (!valid()) return INVALID_OPERATION;
3442
Emilian Peevaebbe412018-01-15 13:53:24 +00003443 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3444 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3445 if (castResult_3_4.isOk()) {
3446 hidlSession_3_4 = castResult_3_4;
3447 }
3448
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003449 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003450 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003451 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003452 if (hidlSession_3_4 != nullptr) {
3453 captureRequests_3_4.resize(batchSize);
3454 } else {
3455 captureRequests.resize(batchSize);
3456 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003457 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003458 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003459
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003460 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003461 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003462 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003463 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003464 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003465 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003466 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3467 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003468 }
3469 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003470 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003471 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003472 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003473 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003474 }
3475
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003476 std::vector<device::V3_2::BufferCache> cachesToRemove;
3477 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003478 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003479 for (auto& pair : mFreedBuffers) {
3480 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003481 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003482 cachesToRemove.push_back({pair.first, pair.second});
3483 }
3484 }
3485 mFreedBuffers.clear();
3486 }
3487
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003488 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3489 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003490
3491 // Write metadata to FMQ.
3492 for (size_t i = 0; i < batchSize; i++) {
3493 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003494 device::V3_2::CaptureRequest* captureRequest;
3495 if (hidlSession_3_4 != nullptr) {
3496 captureRequest = &captureRequests_3_4[i].v3_2;
3497 } else {
3498 captureRequest = &captureRequests[i];
3499 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003500
3501 if (request->settings != nullptr) {
3502 size_t settingsSize = get_camera_metadata_size(request->settings);
3503 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3504 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3505 captureRequest->settings.resize(0);
3506 captureRequest->fmqSettingsSize = settingsSize;
3507 } else {
3508 if (mRequestMetadataQueue != nullptr) {
3509 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3510 }
3511 captureRequest->settings.setToExternal(
3512 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3513 get_camera_metadata_size(request->settings));
3514 captureRequest->fmqSettingsSize = 0u;
3515 }
3516 } else {
3517 // A null request settings maps to a size-0 CameraMetadata
3518 captureRequest->settings.resize(0);
3519 captureRequest->fmqSettingsSize = 0u;
3520 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003521
3522 if (hidlSession_3_4 != nullptr) {
3523 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3524 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003525 if (request->physcam_settings != nullptr) {
3526 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3527 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3528 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3529 settingsSize)) {
3530 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3531 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3532 settingsSize;
3533 } else {
3534 if (mRequestMetadataQueue != nullptr) {
3535 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3536 }
3537 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3538 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3539 request->physcam_settings[j])),
3540 get_camera_metadata_size(request->physcam_settings[j]));
3541 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003542 }
Emilian Peev00420d22018-02-05 21:33:13 +00003543 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003544 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003545 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003546 }
3547 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3548 request->physcam_id[j];
3549 }
3550 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003551 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003552
3553 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003554 auto resultCallback =
3555 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3556 status = s;
3557 *numRequestProcessed = n;
3558 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003559 if (hidlSession_3_4 != nullptr) {
3560 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003561 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003562 } else {
3563 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003564 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003565 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003566 if (!err.isOk()) {
3567 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003568 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003569 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003570
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003571 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3572 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3573 __FUNCTION__, *numRequestProcessed, batchSize);
3574 status = common::V1_0::Status::INTERNAL_ERROR;
3575 }
3576
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003577 res = CameraProviderManager::mapToStatusT(status);
3578 if (res == OK) {
3579 if (mHidlSession->isRemote()) {
3580 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3581 // sent to camera HAL processes)
3582 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3583 } else {
3584 // In passthrough mode the FDs are now owned by HAL
3585 cleanupNativeHandles(&handlesCreated);
3586 }
3587 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003588 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003589 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003590 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003591 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003592}
3593
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003594status_t Camera3Device::HalInterface::flush() {
3595 ATRACE_NAME("CameraHal::flush");
3596 if (!valid()) return INVALID_OPERATION;
3597 status_t res = OK;
3598
Emilian Peev31abd0a2017-05-11 18:37:46 +01003599 auto err = mHidlSession->flush();
3600 if (!err.isOk()) {
3601 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3602 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003603 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003604 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003605 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003606
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003607 return res;
3608}
3609
Emilian Peev31abd0a2017-05-11 18:37:46 +01003610status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003611 ATRACE_NAME("CameraHal::dump");
3612 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003613
Emilian Peev31abd0a2017-05-11 18:37:46 +01003614 // Handled by CameraProviderManager::dump
3615
3616 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003617}
3618
3619status_t Camera3Device::HalInterface::close() {
3620 ATRACE_NAME("CameraHal::close()");
3621 if (!valid()) return INVALID_OPERATION;
3622 status_t res = OK;
3623
Emilian Peev31abd0a2017-05-11 18:37:46 +01003624 auto err = mHidlSession->close();
3625 // Interface will be dead shortly anyway, so don't log errors
3626 if (!err.isOk()) {
3627 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003628 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003629
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003630 return res;
3631}
3632
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003633void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3634 ATRACE_NAME("CameraHal::signalPipelineDrain");
3635 if (!valid() || mHidlSession_3_5 == nullptr) {
3636 ALOGE("%s called on invalid camera!", __FUNCTION__);
3637 return;
3638 }
3639
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003640 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003641 if (!err.isOk()) {
3642 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3643 return;
3644 }
3645}
3646
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003647status_t Camera3Device::HalInterface::switchToOffline(
3648 const std::vector<int32_t>& streamsToKeep,
3649 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003650 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3651 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003652 ATRACE_NAME("CameraHal::switchToOffline");
3653 if (!valid() || mHidlSession_3_6 == nullptr) {
3654 ALOGE("%s called on invalid camera!", __FUNCTION__);
3655 return INVALID_OPERATION;
3656 }
3657
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003658 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3659 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003660 return INVALID_OPERATION;
3661 }
3662
3663 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003664 auto resultCallback =
3665 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3666 status = s;
3667 *offlineSessionInfo = info;
3668 *offlineSession = session;
3669 };
3670 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3671
3672 if (!err.isOk()) {
3673 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3674 return DEAD_OBJECT;
3675 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003676
3677 status_t ret = CameraProviderManager::mapToStatusT(status);
3678 if (ret != OK) {
3679 return ret;
3680 }
3681
3682 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3683 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3684 // returns from switchToOffline.
3685
3686
3687 // Validate buffer caches
3688 std::vector<int32_t> streams;
3689 streams.reserve(offlineSessionInfo->offlineStreams.size());
3690 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3691 int32_t id = offlineStream.id;
3692 streams.push_back(id);
3693 // Verify buffer caches
3694 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3695 offlineStream.circulatingBufferIds.end());
3696 if (!verifyBufferIds(id, bufIds)) {
3697 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3698 return UNKNOWN_ERROR;
3699 }
3700 }
3701
3702 // Move buffer records
3703 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3704 bufferRecords->takeInflightBufferMap(mBufferRecords);
3705 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3706 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003707}
3708
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003709void Camera3Device::HalInterface::getInflightBufferKeys(
3710 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003711 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003712 return;
3713}
3714
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003715void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3716 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003717 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003718 return;
3719}
3720
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003721bool Camera3Device::HalInterface::verifyBufferIds(
3722 int32_t streamId, std::vector<uint64_t>& bufIds) {
3723 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003724}
3725
3726status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003727 int32_t frameNumber, int32_t streamId,
3728 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003729 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003730}
3731
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003732status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003733 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003734 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003735}
3736
3737// Find and pop a buffer_handle_t based on bufferId
3738status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003739 uint64_t bufferId,
3740 /*out*/ buffer_handle_t** buffer,
3741 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003742 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003743}
3744
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003745std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3746 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003747 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003748}
3749
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003750void Camera3Device::HalInterface::onBufferFreed(
3751 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003752 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3753 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3754 if (bufferId != BUFFER_ID_NO_BUFFER) {
3755 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003756 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003757}
3758
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003759void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003760 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3761 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3762 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003763 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3764 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003765}
3766
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003767/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003768 * RequestThread inner class methods
3769 */
3770
3771Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003772 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003773 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3774 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003775 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003776 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003777 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003778 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003779 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003780 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003781 mReconfigured(false),
3782 mDoPause(false),
3783 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003784 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003785 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003786 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003787 mCurrentAfTriggerId(0),
3788 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003789 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003790 mRepeatingLastFrameNumber(
3791 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003792 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003793 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003794 mRequestLatency(kRequestLatencyBinSize),
3795 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003796 mLatestSessionParams(sessionParamKeys.size()),
3797 mUseHalBufManager(useHalBufManager) {
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07003798 mStatusId = statusTracker->addComponent("RequestThread");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003799}
3800
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003801Camera3Device::RequestThread::~RequestThread() {}
3802
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003803void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003804 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003805 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003806 Mutex::Autolock l(mRequestLock);
3807 mListener = listener;
3808}
3809
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003810void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3811 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003812 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003813 Mutex::Autolock l(mRequestLock);
3814 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003815 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003816 // Prepare video stream for high speed recording.
3817 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003818 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003819}
3820
Jianing Wei90e59c92014-03-12 18:29:36 -07003821status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003822 List<sp<CaptureRequest> > &requests,
3823 /*out*/
3824 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003825 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003826 Mutex::Autolock l(mRequestLock);
3827 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3828 ++it) {
3829 mRequestQueue.push_back(*it);
3830 }
3831
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003832 if (lastFrameNumber != NULL) {
3833 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3834 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3835 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3836 *lastFrameNumber);
3837 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003838
Jianing Wei90e59c92014-03-12 18:29:36 -07003839 unpauseForNewRequests();
3840
3841 return OK;
3842}
3843
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003844
3845status_t Camera3Device::RequestThread::queueTrigger(
3846 RequestTrigger trigger[],
3847 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003848 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003849 Mutex::Autolock l(mTriggerMutex);
3850 status_t ret;
3851
3852 for (size_t i = 0; i < count; ++i) {
3853 ret = queueTriggerLocked(trigger[i]);
3854
3855 if (ret != OK) {
3856 return ret;
3857 }
3858 }
3859
3860 return OK;
3861}
3862
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003863const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3864 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003865 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003866 if (d != nullptr) return d->mId;
3867 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003868}
3869
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003870status_t Camera3Device::RequestThread::queueTriggerLocked(
3871 RequestTrigger trigger) {
3872
3873 uint32_t tag = trigger.metadataTag;
3874 ssize_t index = mTriggerMap.indexOfKey(tag);
3875
3876 switch (trigger.getTagType()) {
3877 case TYPE_BYTE:
3878 // fall-through
3879 case TYPE_INT32:
3880 break;
3881 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003882 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3883 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003884 return INVALID_OPERATION;
3885 }
3886
3887 /**
3888 * Collect only the latest trigger, since we only have 1 field
3889 * in the request settings per trigger tag, and can't send more than 1
3890 * trigger per request.
3891 */
3892 if (index != NAME_NOT_FOUND) {
3893 mTriggerMap.editValueAt(index) = trigger;
3894 } else {
3895 mTriggerMap.add(tag, trigger);
3896 }
3897
3898 return OK;
3899}
3900
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003901status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003902 const RequestList &requests,
3903 /*out*/
3904 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003905 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003906 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003907 if (lastFrameNumber != NULL) {
3908 *lastFrameNumber = mRepeatingLastFrameNumber;
3909 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003910 mRepeatingRequests.clear();
3911 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3912 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003913
3914 unpauseForNewRequests();
3915
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003916 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003917 return OK;
3918}
3919
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003920bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003921 if (mRepeatingRequests.empty()) {
3922 return false;
3923 }
3924 int32_t requestId = requestIn->mResultExtras.requestId;
3925 const RequestList &repeatRequests = mRepeatingRequests;
3926 // All repeating requests are guaranteed to have same id so only check first quest
3927 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3928 return (firstRequest->mResultExtras.requestId == requestId);
3929}
3930
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003931status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003932 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003933 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003934 return clearRepeatingRequestsLocked(lastFrameNumber);
3935
3936}
3937
3938status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003939 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003940 if (lastFrameNumber != NULL) {
3941 *lastFrameNumber = mRepeatingLastFrameNumber;
3942 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003943 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003944 return OK;
3945}
3946
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003947status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003948 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003949 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003950 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003951 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003952
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003953 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003954
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003955 // Send errors for all requests pending in the request queue, including
3956 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003957 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003958 if (listener != NULL) {
3959 for (RequestList::iterator it = mRequestQueue.begin();
3960 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003961 // Abort the input buffers for reprocess requests.
3962 if ((*it)->mInputStream != NULL) {
3963 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003964 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3965 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003966 if (res != OK) {
3967 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3968 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3969 } else {
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07003970 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003971 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3972 if (res != OK) {
3973 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3974 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3975 }
3976 }
3977 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003978 // Set the frame number this request would have had, if it
3979 // had been submitted; this frame number will not be reused.
3980 // The requestId and burstId fields were set when the request was
3981 // submitted originally (in convertMetadataListToRequestListLocked)
3982 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003983 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003984 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003985 }
3986 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003987 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003988
3989 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003990 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003991 if (lastFrameNumber != NULL) {
3992 *lastFrameNumber = mRepeatingLastFrameNumber;
3993 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003994 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003995 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003996 return OK;
3997}
3998
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003999status_t Camera3Device::RequestThread::flush() {
4000 ATRACE_CALL();
4001 Mutex::Autolock l(mFlushLock);
4002
Emilian Peev08dd2452017-04-06 16:55:14 +01004003 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004004}
4005
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004006void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004007 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004008 Mutex::Autolock l(mPauseLock);
4009 mDoPause = paused;
4010 mDoPauseSignal.signal();
4011}
4012
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004013status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4014 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004015 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004016 Mutex::Autolock l(mLatestRequestMutex);
4017 status_t res;
4018 while (mLatestRequestId != requestId) {
4019 nsecs_t startTime = systemTime();
4020
4021 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4022 if (res != OK) return res;
4023
4024 timeout -= (systemTime() - startTime);
4025 }
4026
4027 return OK;
4028}
4029
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004030void Camera3Device::RequestThread::requestExit() {
4031 // Call parent to set up shutdown
4032 Thread::requestExit();
4033 // The exit from any possible waits
4034 mDoPauseSignal.signal();
4035 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004036
4037 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4038 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004039}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004040
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004041void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004042 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004043 bool surfaceAbandoned = false;
4044 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004045 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004046 {
4047 Mutex::Autolock l(mRequestLock);
4048 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4049 // repeating requests.
4050 for (const auto& request : mRepeatingRequests) {
4051 for (const auto& s : request->mOutputStreams) {
4052 if (s->isAbandoned()) {
4053 surfaceAbandoned = true;
4054 clearRepeatingRequestsLocked(&lastFrameNumber);
4055 break;
4056 }
4057 }
4058 if (surfaceAbandoned) {
4059 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004060 }
4061 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004062 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004063 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004064
4065 if (listener != NULL && surfaceAbandoned) {
4066 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004067 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004068}
4069
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004070bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004071 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004072 status_t res;
4073 size_t batchSize = mNextRequests.size();
4074 std::vector<camera3_capture_request_t*> requests(batchSize);
4075 uint32_t numRequestProcessed = 0;
4076 for (size_t i = 0; i < batchSize; i++) {
4077 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004078 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004079 }
4080
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004081 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4082
4083 bool triggerRemoveFailed = false;
4084 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4085 for (size_t i = 0; i < numRequestProcessed; i++) {
4086 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4087 nextRequest.submitted = true;
4088
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004089 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004090
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004091 if (!triggerRemoveFailed) {
4092 // Remove any previously queued triggers (after unlock)
4093 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4094 if (removeTriggerRes != OK) {
4095 triggerRemoveFailed = true;
4096 triggerFailedRequest = nextRequest;
4097 }
4098 }
4099 }
4100
4101 if (triggerRemoveFailed) {
4102 SET_ERR("RequestThread: Unable to remove triggers "
4103 "(capture request %d, HAL device: %s (%d)",
4104 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4105 cleanUpFailedRequests(/*sendRequestError*/ false);
4106 return false;
4107 }
4108
4109 if (res != OK) {
4110 // Should only get a failure here for malformed requests or device-level
4111 // errors, so consider all errors fatal. Bad metadata failures should
4112 // come through notify.
4113 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4114 mNextRequests[numRequestProcessed].halRequest.frame_number,
4115 strerror(-res), res);
4116 cleanUpFailedRequests(/*sendRequestError*/ false);
4117 return false;
4118 }
4119 return true;
4120}
4121
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004122nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4123 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4124 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4125 find_camera_metadata_ro_entry(request,
4126 ANDROID_CONTROL_AE_MODE,
4127 &e);
4128 if (e.count == 0) return maxExpectedDuration;
4129
4130 switch (e.data.u8[0]) {
4131 case ANDROID_CONTROL_AE_MODE_OFF:
4132 find_camera_metadata_ro_entry(request,
4133 ANDROID_SENSOR_EXPOSURE_TIME,
4134 &e);
4135 if (e.count > 0) {
4136 maxExpectedDuration = e.data.i64[0];
4137 }
4138 find_camera_metadata_ro_entry(request,
4139 ANDROID_SENSOR_FRAME_DURATION,
4140 &e);
4141 if (e.count > 0) {
4142 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4143 }
4144 break;
4145 default:
4146 find_camera_metadata_ro_entry(request,
4147 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4148 &e);
4149 if (e.count > 1) {
4150 maxExpectedDuration = 1e9 / e.data.u8[0];
4151 }
4152 break;
4153 }
4154
4155 return maxExpectedDuration;
4156}
4157
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004158bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4159 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4160 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4161 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4162 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4163 return true;
4164 }
4165
4166 return false;
4167}
4168
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004169void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4170 // Update the latest request sent to HAL
4171 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4172 Mutex::Autolock al(mLatestRequestMutex);
4173
4174 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4175 mLatestRequest.acquire(cloned);
4176
4177 mLatestPhysicalRequest.clear();
4178 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
4179 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
4180 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
4181 CameraMetadata(cloned));
4182 }
4183
4184 sp<Camera3Device> parent = mParent.promote();
4185 if (parent != NULL) {
4186 parent->monitorMetadata(TagMonitor::REQUEST,
4187 nextRequest.halRequest.frame_number,
4188 0, mLatestRequest, mLatestPhysicalRequest);
4189 }
4190 }
4191
4192 if (nextRequest.halRequest.settings != NULL) {
4193 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4194 nextRequest.halRequest.settings);
4195 }
4196
4197 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4198}
4199
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004200bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4201 ATRACE_CALL();
4202 bool updatesDetected = false;
4203
Emilian Peev4ec17882019-01-24 17:16:58 -08004204 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004205 for (auto tag : mSessionParamKeys) {
4206 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004207 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004208
4209 if (entry.count > 0) {
4210 bool isDifferent = false;
4211 if (lastEntry.count > 0) {
4212 // Have a last value, compare to see if changed
4213 if (lastEntry.type == entry.type &&
4214 lastEntry.count == entry.count) {
4215 // Same type and count, compare values
4216 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4217 size_t entryBytes = bytesPerValue * lastEntry.count;
4218 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4219 if (cmp != 0) {
4220 isDifferent = true;
4221 }
4222 } else {
4223 // Count or type has changed
4224 isDifferent = true;
4225 }
4226 } else {
4227 // No last entry, so always consider to be different
4228 isDifferent = true;
4229 }
4230
4231 if (isDifferent) {
4232 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004233 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4234 updatesDetected = true;
4235 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004236 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004237 }
4238 } else if (lastEntry.count > 0) {
4239 // Value has been removed
4240 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004241 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004242 updatesDetected = true;
4243 }
4244 }
4245
Emilian Peev4ec17882019-01-24 17:16:58 -08004246 bool reconfigureRequired;
4247 if (updatesDetected) {
4248 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4249 updatedParams);
4250 mLatestSessionParams = updatedParams;
4251 } else {
4252 reconfigureRequired = false;
4253 }
4254
4255 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004256}
4257
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004258bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004259 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004260 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004261 // Any function called from threadLoop() must not hold mInterfaceLock since
4262 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4263 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004264
4265 // Handle paused state.
4266 if (waitIfPaused()) {
4267 return true;
4268 }
4269
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004270 // Wait for the next batch of requests.
4271 waitForNextRequestBatch();
4272 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004273 return true;
4274 }
4275
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004276 // Get the latest request ID, if any
4277 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004278 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004279 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004280 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004281 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004282 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004283 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4284 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004285 }
4286
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004287 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4288 // or a single request from streaming or burst. In either case the first element
4289 // should contain the latest camera settings that we need to check for any session
4290 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004291 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004292 res = OK;
4293
4294 //Input stream buffers are already acquired at this point so an input stream
4295 //will not be able to move to idle state unless we force it.
4296 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4297 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4298 if (res != OK) {
4299 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4300 cleanUpFailedRequests(/*sendRequestError*/ false);
4301 return false;
4302 }
4303 }
4304
4305 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004306 sp<Camera3Device> parent = mParent.promote();
4307 if (parent != nullptr) {
4308 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004309 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004310 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004311
4312 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4313 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4314 if (res != OK) {
4315 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4316 cleanUpFailedRequests(/*sendRequestError*/ false);
4317 return false;
4318 }
4319 }
4320 }
4321 }
4322
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004323 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004324 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004325 if (res == TIMED_OUT) {
4326 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004327 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004328 // Check if any stream is abandoned.
4329 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004330 return true;
4331 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004332 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004333 return false;
4334 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004335
Zhijun Hecc27e112013-10-03 16:12:43 -07004336 // Inform waitUntilRequestProcessed thread of a new request ID
4337 {
4338 Mutex::Autolock al(mLatestRequestMutex);
4339
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004340 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004341 mLatestRequestSignal.signal();
4342 }
4343
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004344 // Submit a batch of requests to HAL.
4345 // Use flush lock only when submitting multilple requests in a batch.
4346 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4347 // which may take a long time to finish so synchronizing flush() and
4348 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4349 // For now, only synchronize for high speed recording and we should figure something out for
4350 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004351 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004352
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004353 if (useFlushLock) {
4354 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004355 }
4356
Zhijun Hef0645c12016-08-02 00:58:11 -07004357 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004358 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004359
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004360 sp<Camera3Device> parent = mParent.promote();
4361 if (parent != nullptr) {
4362 parent->mRequestBufferSM.onSubmittingRequest();
4363 }
4364
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004365 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004366 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004367 submitRequestSuccess = sendRequestsBatch();
4368
Shuzhen Wang686f6442017-06-20 16:16:04 -07004369 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4370 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004371
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004372 if (useFlushLock) {
4373 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004374 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004375
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004376 // Unset as current request
4377 {
4378 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004379 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004380 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004381 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004382
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004383 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004384}
4385
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004386status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004387 ATRACE_CALL();
4388
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004389 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004390 for (size_t i = 0; i < mNextRequests.size(); i++) {
4391 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004392 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4393 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4394 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4395
4396 // Prepare a request to HAL
4397 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4398
4399 // Insert any queued triggers (before metadata is locked)
4400 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004401 if (res < 0) {
4402 SET_ERR("RequestThread: Unable to insert triggers "
4403 "(capture request %d, HAL device: %s (%d)",
4404 halRequest->frame_number, strerror(-res), res);
4405 return INVALID_OPERATION;
4406 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004407
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004408 int triggerCount = res;
4409 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4410 mPrevTriggers = triggerCount;
4411
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004412 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
4413
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004414 // If the request is the same as last, or we had triggers last time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004415 bool newRequest =
4416 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004417 // Request settings are all the same within one batch, so only treat the first
4418 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004419 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004420 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004421 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004422 /**
4423 * HAL workaround:
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004424 * Insert a fake trigger ID if a trigger is set but no trigger ID is
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004425 */
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004426 res = addFakeTriggerIds(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004427 if (res != OK) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04004428 SET_ERR("RequestThread: Unable to insert fake trigger IDs "
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004429 "(capture request %d, HAL device: %s (%d)",
4430 halRequest->frame_number, strerror(-res), res);
4431 return INVALID_OPERATION;
4432 }
4433
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004434 {
4435 // Correct metadata regions for distortion correction if enabled
4436 sp<Camera3Device> parent = mParent.promote();
4437 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004438 List<PhysicalCameraSettings>::iterator it;
4439 for (it = captureRequest->mSettingsList.begin();
4440 it != captureRequest->mSettingsList.end(); it++) {
4441 if (parent->mDistortionMappers.find(it->cameraId) ==
4442 parent->mDistortionMappers.end()) {
4443 continue;
4444 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004445
4446 if (!captureRequest->mDistortionCorrectionUpdated) {
4447 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4448 &(it->metadata));
4449 if (res != OK) {
4450 SET_ERR("RequestThread: Unable to correct capture requests "
4451 "for lens distortion for request %d: %s (%d)",
4452 halRequest->frame_number, strerror(-res), res);
4453 return INVALID_OPERATION;
4454 }
4455 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004456 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004457 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004458
4459 for (it = captureRequest->mSettingsList.begin();
4460 it != captureRequest->mSettingsList.end(); it++) {
4461 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4462 parent->mZoomRatioMappers.end()) {
4463 continue;
4464 }
4465
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004466 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004467 cameraIdsWithZoom.insert(it->cameraId);
4468 }
4469
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004470 if (!captureRequest->mZoomRatioUpdated) {
4471 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4472 &(it->metadata));
4473 if (res != OK) {
4474 SET_ERR("RequestThread: Unable to correct capture requests "
4475 "for zoom ratio for request %d: %s (%d)",
4476 halRequest->frame_number, strerror(-res), res);
4477 return INVALID_OPERATION;
4478 }
4479 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004480 }
4481 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004482 if (captureRequest->mRotateAndCropAuto &&
4483 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004484 for (it = captureRequest->mSettingsList.begin();
4485 it != captureRequest->mSettingsList.end(); it++) {
4486 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4487 if (mapper != parent->mRotateAndCropMappers.end()) {
4488 res = mapper->second.updateCaptureRequest(&(it->metadata));
4489 if (res != OK) {
4490 SET_ERR("RequestThread: Unable to correct capture requests "
4491 "for rotate-and-crop for request %d: %s (%d)",
4492 halRequest->frame_number, strerror(-res), res);
4493 return INVALID_OPERATION;
4494 }
4495 }
4496 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004497 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004498 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004499 }
4500 }
4501
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004502 /**
4503 * The request should be presorted so accesses in HAL
4504 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4505 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004506 captureRequest->mSettingsList.begin()->metadata.sort();
4507 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004508 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004509 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004510 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4511
4512 IF_ALOGV() {
4513 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4514 find_camera_metadata_ro_entry(
4515 halRequest->settings,
4516 ANDROID_CONTROL_AF_TRIGGER,
4517 &e
4518 );
4519 if (e.count > 0) {
4520 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4521 __FUNCTION__,
4522 halRequest->frame_number,
4523 e.data.u8[0]);
4524 }
4525 }
4526 } else {
4527 // leave request.settings NULL to indicate 'reuse latest given'
4528 ALOGVV("%s: Request settings are REUSED",
4529 __FUNCTION__);
4530 }
4531
Emilian Peevaebbe412018-01-15 13:53:24 +00004532 if (captureRequest->mSettingsList.size() > 1) {
4533 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4534 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004535 if (newRequest) {
4536 halRequest->physcam_settings =
4537 new const camera_metadata* [halRequest->num_physcam_settings];
4538 } else {
4539 halRequest->physcam_settings = nullptr;
4540 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004541 auto it = ++captureRequest->mSettingsList.begin();
4542 size_t i = 0;
4543 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4544 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004545 if (newRequest) {
4546 it->metadata.sort();
4547 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4548 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004549 }
4550 }
4551
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004552 uint32_t totalNumBuffers = 0;
4553
4554 // Fill in buffers
4555 if (captureRequest->mInputStream != NULL) {
4556 halRequest->input_buffer = &captureRequest->mInputBuffer;
4557 totalNumBuffers += 1;
4558 } else {
4559 halRequest->input_buffer = NULL;
4560 }
4561
4562 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4563 captureRequest->mOutputStreams.size());
4564 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004565 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004566
4567 sp<Camera3Device> parent = mParent.promote();
4568 if (parent == NULL) {
4569 // Should not happen, and nowhere to send errors to, so just log it
4570 CLOGE("RequestThread: Parent is gone");
4571 return INVALID_OPERATION;
4572 }
4573 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4574
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004575 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004576 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004577 sp<Camera3OutputStreamInterface> outputStream =
4578 captureRequest->mOutputStreams.editItemAt(j);
4579 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004580
4581 // Prepare video buffers for high speed recording on the first video request.
4582 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4583 // Only try to prepare video stream on the first video request.
4584 mPrepareVideoStream = false;
4585
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004586 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4587 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004588 while (res == NOT_ENOUGH_DATA) {
4589 res = outputStream->prepareNextBuffer();
4590 }
4591 if (res != OK) {
4592 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4593 __FUNCTION__, strerror(-res), res);
4594 outputStream->cancelPrepare();
4595 }
4596 }
4597
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004598 std::vector<size_t> uniqueSurfaceIds;
4599 res = outputStream->getUniqueSurfaceIds(
4600 captureRequest->mOutputSurfaces[streamId],
4601 &uniqueSurfaceIds);
4602 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4603 if (res != OK && res != INVALID_OPERATION) {
4604 ALOGE("%s: failed to query stream %d unique surface IDs",
4605 __FUNCTION__, streamId);
4606 return res;
4607 }
4608 if (res == OK) {
4609 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4610 }
4611
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004612 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004613 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004614 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004615 return TIMED_OUT;
4616 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004617 // HAL will request buffer through requestStreamBuffer API
4618 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
4619 buffer.stream = outputStream->asHalStream();
4620 buffer.buffer = nullptr;
4621 buffer.status = CAMERA3_BUFFER_STATUS_OK;
4622 buffer.acquire_fence = -1;
4623 buffer.release_fence = -1;
4624 } else {
4625 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4626 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004627 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004628 if (res != OK) {
4629 // Can't get output buffer from gralloc queue - this could be due to
4630 // abandoned queue or other consumer misbehavior, so not a fatal
4631 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004632 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004633 " %s (%d)", strerror(-res), res);
4634
4635 return TIMED_OUT;
4636 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004637 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004638
4639 {
4640 sp<Camera3Device> parent = mParent.promote();
4641 if (parent != nullptr) {
4642 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4643 for (const auto& settings : captureRequest->mSettingsList) {
4644 if ((streamCameraId.isEmpty() &&
4645 parent->getId() == settings.cameraId.c_str()) ||
4646 streamCameraId == settings.cameraId.c_str()) {
4647 outputStream->fireBufferRequestForFrameNumber(
4648 captureRequest->mResultExtras.frameNumber,
4649 settings.metadata);
4650 }
4651 }
4652 }
4653 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004654
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004655 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4656
4657 if (!physicalCameraId.isEmpty()) {
4658 // Physical stream isn't supported for input request.
4659 if (halRequest->input_buffer) {
4660 CLOGE("Physical stream is not supported for input request");
4661 return INVALID_OPERATION;
4662 }
4663 requestedPhysicalCameras.insert(physicalCameraId);
4664 }
4665 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004666 }
4667 totalNumBuffers += halRequest->num_output_buffers;
4668
4669 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004670 // If this request list is for constrained high speed recording (not
4671 // preview), and the current request is not the last one in the batch,
4672 // do not send callback to the app.
4673 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004674 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004675 hasCallback = false;
4676 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004677 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004678 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01004679 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4680 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4681 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4682 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4683 isStillCapture = true;
4684 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4685 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004686
4687 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
4688 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4689 isZslCapture = true;
4690 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004691 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004692 res = parent->registerInFlight(halRequest->frame_number,
4693 totalNumBuffers, captureRequest->mResultExtras,
4694 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004695 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004696 calculateMaxExpectedDuration(halRequest->settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004697 requestedPhysicalCameras, isStillCapture, isZslCapture,
4698 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004699 (mUseHalBufManager) ? uniqueSurfaceIdMap :
4700 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004701 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4702 ", burstId = %" PRId32 ".",
4703 __FUNCTION__,
4704 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4705 captureRequest->mResultExtras.burstId);
4706 if (res != OK) {
4707 SET_ERR("RequestThread: Unable to register new in-flight request:"
4708 " %s (%d)", strerror(-res), res);
4709 return INVALID_OPERATION;
4710 }
4711 }
4712
4713 return OK;
4714}
4715
Igor Murashkin1e479c02013-09-06 16:55:14 -07004716CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004717 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004718 Mutex::Autolock al(mLatestRequestMutex);
4719
4720 ALOGV("RequestThread::%s", __FUNCTION__);
4721
4722 return mLatestRequest;
4723}
4724
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004725bool Camera3Device::RequestThread::isStreamPending(
4726 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004727 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004728 Mutex::Autolock l(mRequestLock);
4729
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004730 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004731 if (!nextRequest.submitted) {
4732 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4733 if (stream == s) return true;
4734 }
4735 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004736 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004737 }
4738
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004739 for (const auto& request : mRequestQueue) {
4740 for (const auto& s : request->mOutputStreams) {
4741 if (stream == s) return true;
4742 }
4743 if (stream == request->mInputStream) return true;
4744 }
4745
4746 for (const auto& request : mRepeatingRequests) {
4747 for (const auto& s : request->mOutputStreams) {
4748 if (stream == s) return true;
4749 }
4750 if (stream == request->mInputStream) return true;
4751 }
4752
4753 return false;
4754}
Jianing Weicb0652e2014-03-12 18:29:36 -07004755
Emilian Peev40ead602017-09-26 15:46:36 +01004756bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4757 ATRACE_CALL();
4758 Mutex::Autolock l(mRequestLock);
4759
4760 for (const auto& nextRequest : mNextRequests) {
4761 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4762 if (s.first == streamId) {
4763 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4764 if (it != s.second.end()) {
4765 return true;
4766 }
4767 }
4768 }
4769 }
4770
4771 for (const auto& request : mRequestQueue) {
4772 for (const auto& s : request->mOutputSurfaces) {
4773 if (s.first == streamId) {
4774 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4775 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004776 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004777 }
4778 }
4779 }
4780 }
4781
4782 for (const auto& request : mRepeatingRequests) {
4783 for (const auto& s : request->mOutputSurfaces) {
4784 if (s.first == streamId) {
4785 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4786 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004787 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004788 }
4789 }
4790 }
4791 }
4792
4793 return false;
4794}
4795
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004796void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4797 if (!mUseHalBufManager) {
4798 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4799 return;
4800 }
4801
4802 Mutex::Autolock pl(mPauseLock);
4803 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004804 mInterface->signalPipelineDrain(streamIds);
4805 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004806 }
4807 // If request thread is still busy, wait until paused then notify HAL
4808 mNotifyPipelineDrain = true;
4809 mStreamIdsToBeDrained = streamIds;
4810}
4811
Yin-Chia Yehe52b8fa2020-07-28 00:17:58 -07004812void Camera3Device::RequestThread::resetPipelineDrain() {
4813 Mutex::Autolock pl(mPauseLock);
4814 mNotifyPipelineDrain = false;
4815 mStreamIdsToBeDrained.clear();
4816}
4817
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004818void Camera3Device::RequestThread::clearPreviousRequest() {
4819 Mutex::Autolock l(mRequestLock);
4820 mPrevRequest.clear();
4821}
4822
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004823status_t Camera3Device::RequestThread::switchToOffline(
4824 const std::vector<int32_t>& streamsToKeep,
4825 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004826 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4827 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004828 Mutex::Autolock l(mRequestLock);
4829 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
4830
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004831 // Wait until request thread is fully stopped
4832 // TBD: check if request thread is being paused by other APIs (shouldn't be)
4833
4834 // We could also check for mRepeatingRequests.empty(), but the API interface
4835 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
4836 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004837 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4838 while (!queueEmpty) {
4839 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
4840 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004841 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004842 return res;
4843 } else if (res != OK) {
4844 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
4845 __FUNCTION__, strerror(-res), res);
4846 return res;
4847 }
4848 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4849 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004850
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004851 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004852 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004853}
4854
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004855status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4856 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4857 ATRACE_CALL();
4858 Mutex::Autolock l(mTriggerMutex);
4859 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4860 return BAD_VALUE;
4861 }
4862 mRotateAndCropOverride = rotateAndCropValue;
4863 return OK;
4864}
4865
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004866nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004867 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004868 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004869 return mExpectedInflightDuration > kMinInflightDuration ?
4870 mExpectedInflightDuration : kMinInflightDuration;
4871}
4872
Emilian Peevaebbe412018-01-15 13:53:24 +00004873void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4874 camera3_capture_request_t *halRequest) {
4875 if ((request == nullptr) || (halRequest == nullptr)) {
4876 ALOGE("%s: Invalid request!", __FUNCTION__);
4877 return;
4878 }
4879
4880 if (halRequest->num_physcam_settings > 0) {
4881 if (halRequest->physcam_id != nullptr) {
4882 delete [] halRequest->physcam_id;
4883 halRequest->physcam_id = nullptr;
4884 }
4885 if (halRequest->physcam_settings != nullptr) {
4886 auto it = ++(request->mSettingsList.begin());
4887 size_t i = 0;
4888 for (; it != request->mSettingsList.end(); it++, i++) {
4889 it->metadata.unlock(halRequest->physcam_settings[i]);
4890 }
4891 delete [] halRequest->physcam_settings;
4892 halRequest->physcam_settings = nullptr;
4893 }
4894 }
4895}
4896
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004897void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4898 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004899 return;
4900 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004901
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004902 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004903 // Skip the ones that have been submitted successfully.
4904 if (nextRequest.submitted) {
4905 continue;
4906 }
4907
4908 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4909 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4910 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4911
4912 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004913 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004914 }
4915
Emilian Peevaebbe412018-01-15 13:53:24 +00004916 cleanupPhysicalSettings(captureRequest, halRequest);
4917
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004918 if (captureRequest->mInputStream != NULL) {
4919 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4920 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4921 }
4922
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004923 // No output buffer can be returned when using HAL buffer manager
4924 if (!mUseHalBufManager) {
4925 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4926 //Buffers that failed processing could still have
4927 //valid acquire fence.
4928 int acquireFence = (*outputBuffers)[i].acquire_fence;
4929 if (0 <= acquireFence) {
4930 close(acquireFence);
4931 outputBuffers->editItemAt(i).acquire_fence = -1;
4932 }
4933 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4934 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
4935 /*timestampIncreasing*/true, std::vector<size_t> (),
4936 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004937 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004938 }
4939
4940 if (sendRequestError) {
4941 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004942 sp<NotificationListener> listener = mListener.promote();
4943 if (listener != NULL) {
4944 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004945 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004946 captureRequest->mResultExtras);
4947 }
4948 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004949
4950 // Remove yet-to-be submitted inflight request from inflightMap
4951 {
4952 sp<Camera3Device> parent = mParent.promote();
4953 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004954 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004955 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4956 if (idx >= 0) {
4957 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4958 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4959 parent->removeInFlightMapEntryLocked(idx);
4960 }
4961 }
4962 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004963 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004964
4965 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004966 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004967}
4968
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004969void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004970 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004971 // Optimized a bit for the simple steady-state case (single repeating
4972 // request), to avoid putting that request in the queue temporarily.
4973 Mutex::Autolock l(mRequestLock);
4974
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004975 assert(mNextRequests.empty());
4976
4977 NextRequest nextRequest;
4978 nextRequest.captureRequest = waitForNextRequestLocked();
4979 if (nextRequest.captureRequest == nullptr) {
4980 return;
4981 }
4982
4983 nextRequest.halRequest = camera3_capture_request_t();
4984 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004985 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004986
4987 // Wait for additional requests
4988 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4989
4990 for (size_t i = 1; i < batchSize; i++) {
4991 NextRequest additionalRequest;
4992 additionalRequest.captureRequest = waitForNextRequestLocked();
4993 if (additionalRequest.captureRequest == nullptr) {
4994 break;
4995 }
4996
4997 additionalRequest.halRequest = camera3_capture_request_t();
4998 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004999 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005000 }
5001
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005002 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005003 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005004 mNextRequests.size(), batchSize);
5005 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005006 }
5007
5008 return;
5009}
5010
5011sp<Camera3Device::CaptureRequest>
5012 Camera3Device::RequestThread::waitForNextRequestLocked() {
5013 status_t res;
5014 sp<CaptureRequest> nextRequest;
5015
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005016 while (mRequestQueue.empty()) {
5017 if (!mRepeatingRequests.empty()) {
5018 // Always atomically enqueue all requests in a repeating request
5019 // list. Guarantees a complete in-sequence set of captures to
5020 // application.
5021 const RequestList &requests = mRepeatingRequests;
5022 RequestList::const_iterator firstRequest =
5023 requests.begin();
5024 nextRequest = *firstRequest;
5025 mRequestQueue.insert(mRequestQueue.end(),
5026 ++firstRequest,
5027 requests.end());
5028 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005029
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005030 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005031
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005032 break;
5033 }
5034
5035 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5036
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005037 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5038 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005039 Mutex::Autolock pl(mPauseLock);
5040 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005041 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005042 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005043 if (mNotifyPipelineDrain) {
5044 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5045 mNotifyPipelineDrain = false;
5046 mStreamIdsToBeDrained.clear();
5047 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005048 // Let the tracker know
5049 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5050 if (statusTracker != 0) {
5051 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5052 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005053 sp<Camera3Device> parent = mParent.promote();
5054 if (parent != nullptr) {
5055 parent->mRequestBufferSM.onRequestThreadPaused();
5056 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005057 }
5058 // Stop waiting for now and let thread management happen
5059 return NULL;
5060 }
5061 }
5062
5063 if (nextRequest == NULL) {
5064 // Don't have a repeating request already in hand, so queue
5065 // must have an entry now.
5066 RequestList::iterator firstRequest =
5067 mRequestQueue.begin();
5068 nextRequest = *firstRequest;
5069 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005070 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5071 sp<NotificationListener> listener = mListener.promote();
5072 if (listener != NULL) {
5073 listener->notifyRequestQueueEmpty();
5074 }
5075 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005076 }
5077
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005078 // In case we've been unpaused by setPaused clearing mDoPause, need to
5079 // update internal pause state (capture/setRepeatingRequest unpause
5080 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005081 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005082 if (mPaused) {
5083 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5084 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5085 if (statusTracker != 0) {
5086 statusTracker->markComponentActive(mStatusId);
5087 }
5088 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005089 mPaused = false;
5090
5091 // Check if we've reconfigured since last time, and reset the preview
5092 // request if so. Can't use 'NULL request == repeat' across configure calls.
5093 if (mReconfigured) {
5094 mPrevRequest.clear();
5095 mReconfigured = false;
5096 }
5097
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005098 if (nextRequest != NULL) {
5099 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005100 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5101 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005102
5103 // Since RequestThread::clear() removes buffers from the input stream,
5104 // get the right buffer here before unlocking mRequestLock
5105 if (nextRequest->mInputStream != NULL) {
5106 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5107 if (res != OK) {
5108 // Can't get input buffer from gralloc queue - this could be due to
5109 // disconnected queue or other producer misbehavior, so not a fatal
5110 // error
5111 ALOGE("%s: Can't get input buffer, skipping request:"
5112 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005113
5114 sp<NotificationListener> listener = mListener.promote();
5115 if (listener != NULL) {
5116 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005117 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005118 nextRequest->mResultExtras);
5119 }
5120 return NULL;
5121 }
5122 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005123 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005124
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005125 return nextRequest;
5126}
5127
5128bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005129 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005130 status_t res;
5131 Mutex::Autolock l(mPauseLock);
5132 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005133 if (mPaused == false) {
5134 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005135 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005136 if (mNotifyPipelineDrain) {
5137 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5138 mNotifyPipelineDrain = false;
5139 mStreamIdsToBeDrained.clear();
5140 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005141 // Let the tracker know
5142 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5143 if (statusTracker != 0) {
5144 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5145 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005146 sp<Camera3Device> parent = mParent.promote();
5147 if (parent != nullptr) {
5148 parent->mRequestBufferSM.onRequestThreadPaused();
5149 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005150 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005151
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005152 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005153 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005154 return true;
5155 }
5156 }
5157 // We don't set mPaused to false here, because waitForNextRequest needs
5158 // to further manage the paused state in case of starvation.
5159 return false;
5160}
5161
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005162void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005163 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005164 // With work to do, mark thread as unpaused.
5165 // If paused by request (setPaused), don't resume, to avoid
5166 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005167 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005168 Mutex::Autolock p(mPauseLock);
5169 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005170 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5171 if (mPaused) {
5172 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5173 if (statusTracker != 0) {
5174 statusTracker->markComponentActive(mStatusId);
5175 }
5176 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005177 mPaused = false;
5178 }
5179}
5180
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005181void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5182 sp<Camera3Device> parent = mParent.promote();
5183 if (parent != NULL) {
5184 va_list args;
5185 va_start(args, fmt);
5186
5187 parent->setErrorStateV(fmt, args);
5188
5189 va_end(args);
5190 }
5191}
5192
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005193status_t Camera3Device::RequestThread::insertTriggers(
5194 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005195 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005196 Mutex::Autolock al(mTriggerMutex);
5197
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005198 sp<Camera3Device> parent = mParent.promote();
5199 if (parent == NULL) {
5200 CLOGE("RequestThread: Parent is gone");
5201 return DEAD_OBJECT;
5202 }
5203
Emilian Peevaebbe412018-01-15 13:53:24 +00005204 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005205 size_t count = mTriggerMap.size();
5206
5207 for (size_t i = 0; i < count; ++i) {
5208 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005209 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005210
5211 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5212 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5213 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005214 if (isAeTrigger) {
5215 request->mResultExtras.precaptureTriggerId = triggerId;
5216 mCurrentPreCaptureTriggerId = triggerId;
5217 } else {
5218 request->mResultExtras.afTriggerId = triggerId;
5219 mCurrentAfTriggerId = triggerId;
5220 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005221 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005222 }
5223
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005224 camera_metadata_entry entry = metadata.find(tag);
5225
5226 if (entry.count > 0) {
5227 /**
5228 * Already has an entry for this trigger in the request.
5229 * Rewrite it with our requested trigger value.
5230 */
5231 RequestTrigger oldTrigger = trigger;
5232
5233 oldTrigger.entryValue = entry.data.u8[0];
5234
5235 mTriggerReplacedMap.add(tag, oldTrigger);
5236 } else {
5237 /**
5238 * More typical, no trigger entry, so we just add it
5239 */
5240 mTriggerRemovedMap.add(tag, trigger);
5241 }
5242
5243 status_t res;
5244
5245 switch (trigger.getTagType()) {
5246 case TYPE_BYTE: {
5247 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5248 res = metadata.update(tag,
5249 &entryValue,
5250 /*count*/1);
5251 break;
5252 }
5253 case TYPE_INT32:
5254 res = metadata.update(tag,
5255 &trigger.entryValue,
5256 /*count*/1);
5257 break;
5258 default:
5259 ALOGE("%s: Type not supported: 0x%x",
5260 __FUNCTION__,
5261 trigger.getTagType());
5262 return INVALID_OPERATION;
5263 }
5264
5265 if (res != OK) {
5266 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5267 ", value %d", __FUNCTION__, trigger.getTagName(),
5268 trigger.entryValue);
5269 return res;
5270 }
5271
5272 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5273 trigger.getTagName(),
5274 trigger.entryValue);
5275 }
5276
5277 mTriggerMap.clear();
5278
5279 return count;
5280}
5281
5282status_t Camera3Device::RequestThread::removeTriggers(
5283 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005284 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005285 Mutex::Autolock al(mTriggerMutex);
5286
Emilian Peevaebbe412018-01-15 13:53:24 +00005287 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005288
5289 /**
5290 * Replace all old entries with their old values.
5291 */
5292 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5293 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5294
5295 status_t res;
5296
5297 uint32_t tag = trigger.metadataTag;
5298 switch (trigger.getTagType()) {
5299 case TYPE_BYTE: {
5300 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5301 res = metadata.update(tag,
5302 &entryValue,
5303 /*count*/1);
5304 break;
5305 }
5306 case TYPE_INT32:
5307 res = metadata.update(tag,
5308 &trigger.entryValue,
5309 /*count*/1);
5310 break;
5311 default:
5312 ALOGE("%s: Type not supported: 0x%x",
5313 __FUNCTION__,
5314 trigger.getTagType());
5315 return INVALID_OPERATION;
5316 }
5317
5318 if (res != OK) {
5319 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5320 ", trigger value %d", __FUNCTION__,
5321 trigger.getTagName(), trigger.entryValue);
5322 return res;
5323 }
5324 }
5325 mTriggerReplacedMap.clear();
5326
5327 /**
5328 * Remove all new entries.
5329 */
5330 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5331 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5332 status_t res = metadata.erase(trigger.metadataTag);
5333
5334 if (res != OK) {
5335 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5336 ", trigger value %d", __FUNCTION__,
5337 trigger.getTagName(), trigger.entryValue);
5338 return res;
5339 }
5340 }
5341 mTriggerRemovedMap.clear();
5342
5343 return OK;
5344}
5345
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005346status_t Camera3Device::RequestThread::addFakeTriggerIds(
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005347 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005348 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005349 static const int32_t fakeTriggerId = 1;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005350 status_t res;
5351
Emilian Peevaebbe412018-01-15 13:53:24 +00005352 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005353
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005354 // If AF trigger is active, insert a fake AF trigger ID if none already
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005355 // exists
5356 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5357 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5358 if (afTrigger.count > 0 &&
5359 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5360 afId.count == 0) {
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005361 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005362 if (res != OK) return res;
5363 }
5364
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005365 // If AE precapture trigger is active, insert a fake precapture trigger ID
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005366 // if none already exists
5367 camera_metadata_entry pcTrigger =
5368 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5369 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5370 if (pcTrigger.count > 0 &&
5371 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5372 pcId.count == 0) {
5373 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
Ivan Lozanoc0ad82f2020-07-30 09:32:57 -04005374 &fakeTriggerId, 1);
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005375 if (res != OK) return res;
5376 }
5377
5378 return OK;
5379}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005380
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005381bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5382 const sp<CaptureRequest> &request) {
5383 ATRACE_CALL();
5384
5385 if (request->mRotateAndCropAuto) {
5386 Mutex::Autolock l(mTriggerMutex);
5387 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5388
5389 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5390 if (rotateAndCropEntry.count > 0) {
5391 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5392 return false;
5393 } else {
5394 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5395 return true;
5396 }
5397 } else {
5398 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5399 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5400 &rotateAndCrop_u8, 1);
5401 return true;
5402 }
5403 }
5404 return false;
5405}
5406
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005407/**
5408 * PreparerThread inner class methods
5409 */
5410
5411Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005412 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005413 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005414}
5415
5416Camera3Device::PreparerThread::~PreparerThread() {
5417 Thread::requestExitAndWait();
5418 if (mCurrentStream != nullptr) {
5419 mCurrentStream->cancelPrepare();
5420 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5421 mCurrentStream.clear();
5422 }
5423 clear();
5424}
5425
Ruben Brunkc78ac262015-08-13 17:58:46 -07005426status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005427 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005428 status_t res;
5429
5430 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005431 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005432
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005433 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005434 if (res == OK) {
5435 // No preparation needed, fire listener right off
5436 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005437 if (listener != NULL) {
5438 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005439 }
5440 return OK;
5441 } else if (res != NOT_ENOUGH_DATA) {
5442 return res;
5443 }
5444
5445 // Need to prepare, start up thread if necessary
5446 if (!mActive) {
5447 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5448 // isn't running
5449 Thread::requestExitAndWait();
5450 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5451 if (res != OK) {
5452 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005453 if (listener != NULL) {
5454 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005455 }
5456 return res;
5457 }
5458 mCancelNow = false;
5459 mActive = true;
5460 ALOGV("%s: Preparer stream started", __FUNCTION__);
5461 }
5462
5463 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005464 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005465 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5466
5467 return OK;
5468}
5469
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005470void Camera3Device::PreparerThread::pause() {
5471 ATRACE_CALL();
5472
5473 Mutex::Autolock l(mLock);
5474
5475 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5476 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5477 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5478 int currentMaxCount = mCurrentMaxCount;
5479 mPendingStreams.clear();
5480 mCancelNow = true;
5481 while (mActive) {
5482 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5483 if (res == TIMED_OUT) {
5484 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5485 return;
5486 } else if (res != OK) {
5487 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5488 return;
5489 }
5490 }
5491
5492 //Check whether the prepare thread was able to complete the current
5493 //stream. In case work is still pending emplace it along with the rest
5494 //of the streams in the pending list.
5495 if (currentStream != nullptr) {
5496 if (!mCurrentPrepareComplete) {
5497 pendingStreams.emplace(currentMaxCount, currentStream);
5498 }
5499 }
5500
5501 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5502 for (const auto& it : mPendingStreams) {
5503 it.second->cancelPrepare();
5504 }
5505}
5506
5507status_t Camera3Device::PreparerThread::resume() {
5508 ATRACE_CALL();
5509 status_t res;
5510
5511 Mutex::Autolock l(mLock);
5512 sp<NotificationListener> listener = mListener.promote();
5513
5514 if (mActive) {
5515 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5516 return NO_INIT;
5517 }
5518
5519 auto it = mPendingStreams.begin();
5520 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005521 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005522 if (res == OK) {
5523 if (listener != NULL) {
5524 listener->notifyPrepared(it->second->getId());
5525 }
5526 it = mPendingStreams.erase(it);
5527 } else if (res != NOT_ENOUGH_DATA) {
5528 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5529 res, strerror(-res));
5530 it = mPendingStreams.erase(it);
5531 } else {
5532 it++;
5533 }
5534 }
5535
5536 if (mPendingStreams.empty()) {
5537 return OK;
5538 }
5539
5540 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5541 if (res != OK) {
5542 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5543 __FUNCTION__, res, strerror(-res));
5544 return res;
5545 }
5546 mCancelNow = false;
5547 mActive = true;
5548 ALOGV("%s: Preparer stream started", __FUNCTION__);
5549
5550 return OK;
5551}
5552
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005553status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005554 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005555 Mutex::Autolock l(mLock);
5556
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005557 for (const auto& it : mPendingStreams) {
5558 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005559 }
5560 mPendingStreams.clear();
5561 mCancelNow = true;
5562
5563 return OK;
5564}
5565
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005566void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005567 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005568 Mutex::Autolock l(mLock);
5569 mListener = listener;
5570}
5571
5572bool Camera3Device::PreparerThread::threadLoop() {
5573 status_t res;
5574 {
5575 Mutex::Autolock l(mLock);
5576 if (mCurrentStream == nullptr) {
5577 // End thread if done with work
5578 if (mPendingStreams.empty()) {
5579 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5580 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5581 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5582 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005583 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005584 return false;
5585 }
5586
5587 // Get next stream to prepare
5588 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005589 mCurrentStream = it->second;
5590 mCurrentMaxCount = it->first;
5591 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005592 mPendingStreams.erase(it);
5593 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5594 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5595 } else if (mCancelNow) {
5596 mCurrentStream->cancelPrepare();
5597 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5598 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5599 mCurrentStream.clear();
5600 mCancelNow = false;
5601 return true;
5602 }
5603 }
5604
5605 res = mCurrentStream->prepareNextBuffer();
5606 if (res == NOT_ENOUGH_DATA) return true;
5607 if (res != OK) {
5608 // Something bad happened; try to recover by cancelling prepare and
5609 // signalling listener anyway
5610 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5611 mCurrentStream->getId(), res, strerror(-res));
5612 mCurrentStream->cancelPrepare();
5613 }
5614
5615 // This stream has finished, notify listener
5616 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005617 sp<NotificationListener> listener = mListener.promote();
5618 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005619 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5620 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005621 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005622 }
5623
5624 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5625 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005626 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005627
5628 return true;
5629}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005630
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005631status_t Camera3Device::RequestBufferStateMachine::initialize(
5632 sp<camera3::StatusTracker> statusTracker) {
5633 if (statusTracker == nullptr) {
5634 ALOGE("%s: statusTracker is null", __FUNCTION__);
5635 return BAD_VALUE;
5636 }
5637
5638 std::lock_guard<std::mutex> lock(mLock);
5639 mStatusTracker = statusTracker;
Yin-Chia Yeh87b3ec02019-06-03 10:44:39 -07005640 mRequestBufferStatusId = statusTracker->addComponent("BufferRequestSM");
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005641 return OK;
5642}
5643
5644bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5645 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005646 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005647 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005648 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005649 return true;
5650 }
5651 return false;
5652}
5653
5654void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5655 std::lock_guard<std::mutex> lock(mLock);
5656 if (!mRequestBufferOngoing) {
5657 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5658 return;
5659 }
5660 mRequestBufferOngoing = false;
5661 if (mStatus == RB_STATUS_PENDING_STOP) {
5662 checkSwitchToStopLocked();
5663 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005664 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005665}
5666
5667void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5668 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005669 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005670 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005671 return;
5672}
5673
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005674void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005675 std::lock_guard<std::mutex> lock(mLock);
5676 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005677 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5678 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005679 mInflightMapEmpty = false;
5680 if (mStatus == RB_STATUS_STOPPED) {
5681 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005682 }
5683 return;
5684}
5685
5686void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5687 std::lock_guard<std::mutex> lock(mLock);
5688 mRequestThreadPaused = true;
5689 if (mStatus == RB_STATUS_PENDING_STOP) {
5690 checkSwitchToStopLocked();
5691 }
5692 return;
5693}
5694
5695void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5696 std::lock_guard<std::mutex> lock(mLock);
5697 mInflightMapEmpty = true;
5698 if (mStatus == RB_STATUS_PENDING_STOP) {
5699 checkSwitchToStopLocked();
5700 }
5701 return;
5702}
5703
5704void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5705 std::lock_guard<std::mutex> lock(mLock);
5706 if (!checkSwitchToStopLocked()) {
5707 mStatus = RB_STATUS_PENDING_STOP;
5708 }
5709 return;
5710}
5711
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005712bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5713 std::lock_guard<std::mutex> lock(mLock);
5714 if (mRequestBufferOngoing) {
5715 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5716 __FUNCTION__);
5717 return false;
5718 }
5719 mSwitchedToOffline = true;
5720 mInflightMapEmpty = true;
5721 mRequestThreadPaused = true;
5722 mStatus = RB_STATUS_STOPPED;
5723 return true;
5724}
5725
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005726void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5727 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5728 if (statusTracker != nullptr) {
5729 if (active) {
5730 statusTracker->markComponentActive(mRequestBufferStatusId);
5731 } else {
5732 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5733 }
5734 }
5735}
5736
5737bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5738 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5739 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005740 return true;
5741 }
5742 return false;
5743}
5744
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005745bool Camera3Device::startRequestBuffer() {
5746 return mRequestBufferSM.startRequestBuffer();
5747}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005748
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005749void Camera3Device::endRequestBuffer() {
5750 mRequestBufferSM.endRequestBuffer();
5751}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005752
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005753nsecs_t Camera3Device::getWaitDuration() {
5754 return kBaseGetBufferWait + getExpectedInFlightDuration();
5755}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005756
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005757void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5758 mInterface->getInflightBufferKeys(out);
5759}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005760
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005761void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5762 mInterface->getInflightRequestBufferKeys(out);
5763}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005764
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005765std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5766 std::vector<sp<Camera3StreamInterface>> ret;
5767 bool hasInputStream = mInputStream != nullptr;
5768 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5769 if (hasInputStream) {
5770 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005771 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005772 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5773 ret.push_back(mOutputStreams[i]);
5774 }
5775 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5776 ret.push_back(mDeletedStreams[i]);
5777 }
5778 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005779}
5780
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005781status_t Camera3Device::switchToOffline(
5782 const std::vector<int32_t>& streamsToKeep,
5783 /*out*/ sp<CameraOfflineSessionBase>* session) {
5784 ATRACE_CALL();
5785 if (session == nullptr) {
5786 ALOGE("%s: session must not be null", __FUNCTION__);
5787 return BAD_VALUE;
5788 }
5789
5790 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005791
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005792 bool hasInputStream = mInputStream != nullptr;
5793 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
5794 bool inputStreamSupportsOffline = hasInputStream ?
5795 mInputStream->getOfflineProcessingSupport() : false;
5796 auto outputStreamIds = mOutputStreams.getStreamIds();
5797 auto streamIds = outputStreamIds;
5798 if (hasInputStream) {
5799 streamIds.push_back(mInputStream->getId());
5800 }
5801
5802 // Check all streams in streamsToKeep supports offline mode
5803 for (auto id : streamsToKeep) {
5804 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5805 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
5806 return BAD_VALUE;
5807 } else if (id == inputStreamId) {
5808 if (!inputStreamSupportsOffline) {
5809 ALOGE("%s: input stream %d cannot be switched to offline",
5810 __FUNCTION__, id);
5811 return BAD_VALUE;
5812 }
5813 } else {
5814 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
5815 if (!stream->getOfflineProcessingSupport()) {
5816 ALOGE("%s: output stream %d cannot be switched to offline",
5817 __FUNCTION__, id);
5818 return BAD_VALUE;
5819 }
5820 }
5821 }
5822
5823 // TODO: block surface sharing and surface group streams until we can support them
5824
5825 // Stop repeating request, wait until all remaining requests are submitted, then call into
5826 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005827 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
5828 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005829 camera3::BufferRecords bufferRecords;
5830 status_t ret = mRequestThread->switchToOffline(
5831 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005832
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005833 if (ret != OK) {
5834 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
5835 return ret;
5836 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005837
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005838 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
5839 if (!succ) {
5840 SET_ERR("HAL must not be calling requestStreamBuffers call");
5841 // TODO: block ALL callbacks from HAL till app configured new streams?
5842 return UNKNOWN_ERROR;
5843 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005844
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005845 // Verify offlineSessionInfo
5846 std::vector<int32_t> offlineStreamIds;
5847 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
5848 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5849 // verify stream IDs
5850 int32_t id = offlineStream.id;
5851 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5852 SET_ERR("stream ID %d not found!", id);
5853 return UNKNOWN_ERROR;
5854 }
5855
5856 // When not using HAL buf manager, only allow streams requested by app to be preserved
5857 if (!mUseHalBufManager) {
5858 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
5859 SET_ERR("stream ID %d must not be switched to offline!", id);
5860 return UNKNOWN_ERROR;
5861 }
5862 }
5863
5864 offlineStreamIds.push_back(id);
5865 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
5866 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
5867 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
5868 // Verify number of outstanding buffers
5869 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
5870 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
5871 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
5872 return UNKNOWN_ERROR;
5873 }
5874 }
5875
5876 // Verify all streams to be deleted don't have any outstanding buffers
5877 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5878 inputStreamId) == offlineStreamIds.end()) {
5879 if (mInputStream->hasOutstandingBuffers()) {
5880 SET_ERR("Input stream %d still has %zu outstanding buffer!",
5881 inputStreamId, mInputStream->getOutstandingBuffersCount());
5882 return UNKNOWN_ERROR;
5883 }
5884 }
5885
5886 for (const auto& outStreamId : outputStreamIds) {
5887 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5888 outStreamId) == offlineStreamIds.end()) {
5889 auto outStream = mOutputStreams.get(outStreamId);
5890 if (outStream->hasOutstandingBuffers()) {
5891 SET_ERR("Output stream %d still has %zu outstanding buffer!",
5892 outStreamId, outStream->getOutstandingBuffersCount());
5893 return UNKNOWN_ERROR;
5894 }
5895 }
5896 }
5897
5898 InFlightRequestMap offlineReqs;
5899 // Verify inflight requests and their pending buffers
5900 {
5901 std::lock_guard<std::mutex> l(mInFlightLock);
5902 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
5903 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
5904 if (idx == NAME_NOT_FOUND) {
5905 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
5906 return UNKNOWN_ERROR;
5907 }
5908
5909 const auto& inflightReq = mInFlightMap.valueAt(idx);
5910 // TODO: check specific stream IDs
5911 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
5912 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
5913 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
5914 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
5915 return UNKNOWN_ERROR;
5916 }
5917 offlineReqs.add(offlineReq.frameNumber, inflightReq);
5918 }
5919 }
5920
5921 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005922 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005923 camera3::StreamSet offlineStreamSet;
5924 sp<camera3::Camera3Stream> inputStream;
5925 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5926 int32_t id = offlineStream.id;
5927 if (mInputStream != nullptr && id == mInputStream->getId()) {
5928 inputStream = mInputStream;
5929 } else {
5930 offlineStreamSet.add(id, mOutputStreams.get(id));
5931 }
5932 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005933
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005934 // TODO: check if we need to lock before copying states
5935 // though technically no other thread should be talking to Camera3Device at this point
5936 Camera3OfflineStates offlineStates(
5937 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07005938 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
5939 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
5940 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
5941 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
5942 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
5943 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
5944 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005945
5946 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
5947 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
5948
5949 // Delete all streams that has been transferred to offline session
5950 Mutex::Autolock l(mLock);
5951 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5952 int32_t id = offlineStream.id;
5953 if (mInputStream != nullptr && id == mInputStream->getId()) {
5954 mInputStream.clear();
5955 } else {
5956 mOutputStreams.remove(id);
5957 }
5958 }
5959
5960 // disconnect all other streams and switch to UNCONFIGURED state
5961 if (mInputStream != nullptr) {
5962 ret = mInputStream->disconnect();
5963 if (ret != OK) {
5964 SET_ERR_L("disconnect input stream failed!");
5965 return UNKNOWN_ERROR;
5966 }
5967 }
5968
5969 for (auto streamId : mOutputStreams.getStreamIds()) {
5970 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
5971 ret = stream->disconnect();
5972 if (ret != OK) {
5973 SET_ERR_L("disconnect output stream %d failed!", streamId);
5974 return UNKNOWN_ERROR;
5975 }
5976 }
5977
5978 mInputStream.clear();
5979 mOutputStreams.clear();
5980 mNeedConfig = true;
5981 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
5982 mOperatingMode = NO_MODE;
5983 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005984 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005985
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005986 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005987 // TO be done by CameraDeviceClient/Camera3OfflineSession
5988 // register the offline client to camera service
5989 // Setup result passthing threads etc
5990 // Initialize offline session so HAL can start sending callback to it (result Fmq)
5991 // TODO: check how many onIdle callback will be sent
5992 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005993}
5994
Emilian Peevcc0b7952020-01-07 13:54:47 -08005995void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5996 ATRACE_CALL();
5997
5998 if (offlineStreamIds == nullptr) {
5999 return;
6000 }
6001
6002 Mutex::Autolock il(mInterfaceLock);
6003
6004 auto streamIds = mOutputStreams.getStreamIds();
6005 bool hasInputStream = mInputStream != nullptr;
6006 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
6007 offlineStreamIds->push_back(mInputStream->getId());
6008 }
6009
6010 for (const auto & streamId : streamIds) {
6011 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
6012 // Streams that use the camera buffer manager are currently not supported in
6013 // offline mode
6014 if (stream->getOfflineProcessingSupport() &&
6015 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6016 offlineStreamIds->push_back(streamId);
6017 }
6018 }
6019}
6020
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006021status_t Camera3Device::setRotateAndCropAutoBehavior(
6022 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6023 ATRACE_CALL();
6024 Mutex::Autolock il(mInterfaceLock);
6025 Mutex::Autolock l(mLock);
6026 if (mRequestThread == nullptr) {
6027 return INVALID_OPERATION;
6028 }
6029 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6030}
6031
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006032}; // namespace android