blob: e6154f0d6987d7cc66830d6cca3e43d9c462f51b [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"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070059#include "device3/Camera3DummyStream.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 */
273 mInFlightStatusId = mStatusTracker->addComponent();
274
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;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700312 mDummyStreamId = 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) {
1771 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1772 res);
1773 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001774 return res;
1775}
1776
Ruben Brunk183f0562015-08-12 12:55:02 -07001777
1778void Camera3Device::internalUpdateStatusLocked(Status status) {
1779 mStatus = status;
1780 mRecentStatusUpdates.add(mStatus);
1781 mStatusChanged.broadcast();
1782}
1783
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001784// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001785status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001786 if (mRequestThread.get() != nullptr) {
1787 mRequestThread->setPaused(true);
1788 } else {
1789 return NO_INIT;
1790 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001791
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001792 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1793 maxExpectedDuration);
1794 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001795 if (res != OK) {
1796 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001797 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001798 }
1799
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001800 return res;
1801}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001802
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001803// Resume after internalPauseAndWaitLocked
1804status_t Camera3Device::internalResumeLocked() {
1805 status_t res;
1806
1807 mRequestThread->setPaused(false);
1808
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001809 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1810 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001811 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1812 if (res != OK) {
1813 SET_ERR_L("Can't transition to active in %f seconds!",
1814 kActiveTimeout/1e9);
1815 }
1816 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001817 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001818}
1819
Ruben Brunk183f0562015-08-12 12:55:02 -07001820status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001821 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001822
1823 size_t startIndex = 0;
1824 if (mStatusWaiters == 0) {
1825 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1826 // this status list
1827 mRecentStatusUpdates.clear();
1828 } else {
1829 // If other threads are waiting on updates to this status list, set the position of the
1830 // first element that this list will check rather than clearing the list.
1831 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001832 }
1833
Ruben Brunk183f0562015-08-12 12:55:02 -07001834 mStatusWaiters++;
1835
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001836 if (!active && mUseHalBufManager) {
1837 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001838 if (mStatus == STATUS_ACTIVE) {
1839 mRequestThread->signalPipelineDrain(streamIds);
1840 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001841 mRequestBufferSM.onWaitUntilIdle();
1842 }
1843
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001844 bool stateSeen = false;
1845 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001846 if (active == (mStatus == STATUS_ACTIVE)) {
1847 // Desired state is current
1848 break;
1849 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001850
1851 res = mStatusChanged.waitRelative(mLock, timeout);
1852 if (res != OK) break;
1853
Ruben Brunk183f0562015-08-12 12:55:02 -07001854 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1855 // transitions.
1856 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1857 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1858 __FUNCTION__);
1859
1860 // Encountered desired state since we began waiting
1861 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001862 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1863 stateSeen = true;
1864 break;
1865 }
1866 }
1867 } while (!stateSeen);
1868
Ruben Brunk183f0562015-08-12 12:55:02 -07001869 mStatusWaiters--;
1870
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001871 return res;
1872}
1873
1874
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001875status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001876 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001877 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001878
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001879 if (listener != NULL && mListener != NULL) {
1880 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1881 }
1882 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001883 mRequestThread->setNotificationListener(listener);
1884 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001885
1886 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001887}
1888
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001889bool Camera3Device::willNotify3A() {
1890 return false;
1891}
1892
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001893status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001894 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001895 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001896
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001897 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001898 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1899 if (st == std::cv_status::timeout) {
1900 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001901 }
1902 }
1903 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001904}
1905
Jianing Weicb0652e2014-03-12 18:29:36 -07001906status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001907 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001908 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001909
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001910 if (mResultQueue.empty()) {
1911 return NOT_ENOUGH_DATA;
1912 }
1913
Jianing Weicb0652e2014-03-12 18:29:36 -07001914 if (frame == NULL) {
1915 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1916 return BAD_VALUE;
1917 }
1918
1919 CaptureResult &result = *(mResultQueue.begin());
1920 frame->mResultExtras = result.mResultExtras;
1921 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001922 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001923 mResultQueue.erase(mResultQueue.begin());
1924
1925 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001926}
1927
1928status_t Camera3Device::triggerAutofocus(uint32_t id) {
1929 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001930 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001931
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001932 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1933 // Mix-in this trigger into the next request and only the next request.
1934 RequestTrigger trigger[] = {
1935 {
1936 ANDROID_CONTROL_AF_TRIGGER,
1937 ANDROID_CONTROL_AF_TRIGGER_START
1938 },
1939 {
1940 ANDROID_CONTROL_AF_TRIGGER_ID,
1941 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001942 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001943 };
1944
1945 return mRequestThread->queueTrigger(trigger,
1946 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001947}
1948
1949status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1950 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001951 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001952
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001953 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1954 // Mix-in this trigger into the next request and only the next request.
1955 RequestTrigger trigger[] = {
1956 {
1957 ANDROID_CONTROL_AF_TRIGGER,
1958 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1959 },
1960 {
1961 ANDROID_CONTROL_AF_TRIGGER_ID,
1962 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001963 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001964 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001965
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001966 return mRequestThread->queueTrigger(trigger,
1967 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001968}
1969
1970status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1971 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001972 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001973
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001974 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1975 // Mix-in this trigger into the next request and only the next request.
1976 RequestTrigger trigger[] = {
1977 {
1978 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1979 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1980 },
1981 {
1982 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1983 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001984 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001985 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001986
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001987 return mRequestThread->queueTrigger(trigger,
1988 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001989}
1990
Jianing Weicb0652e2014-03-12 18:29:36 -07001991status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001992 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001993 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001994 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001995
Zhijun He7ef20392014-04-21 16:04:17 -07001996 {
1997 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001998
1999 // b/116514106 "disconnect()" can get called twice for the same device. The
2000 // camera device will not be initialized during the second run.
2001 if (mStatus == STATUS_UNINITIALIZED) {
2002 return OK;
2003 }
2004
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002005 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002006 }
2007
Emilian Peev08dd2452017-04-06 16:55:14 +01002008 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002009}
2010
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002011status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002012 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2013}
2014
2015status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002016 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002017 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002018 Mutex::Autolock il(mInterfaceLock);
2019 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002020
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002021 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2022 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002023 CLOGE("Stream %d does not exist", streamId);
2024 return BAD_VALUE;
2025 }
2026
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002027 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002028 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002029 return BAD_VALUE;
2030 }
2031
2032 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002033 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002034 return BAD_VALUE;
2035 }
2036
Ruben Brunkc78ac262015-08-13 17:58:46 -07002037 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002038}
2039
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002040status_t Camera3Device::tearDown(int streamId) {
2041 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002042 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002043 Mutex::Autolock il(mInterfaceLock);
2044 Mutex::Autolock l(mLock);
2045
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002046 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2047 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002048 CLOGE("Stream %d does not exist", streamId);
2049 return BAD_VALUE;
2050 }
2051
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002052 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2053 CLOGE("Stream %d is a target of a in-progress request", streamId);
2054 return BAD_VALUE;
2055 }
2056
2057 return stream->tearDown();
2058}
2059
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002060status_t Camera3Device::addBufferListenerForStream(int streamId,
2061 wp<Camera3StreamBufferListener> listener) {
2062 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002063 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002064 Mutex::Autolock il(mInterfaceLock);
2065 Mutex::Autolock l(mLock);
2066
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002067 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2068 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002069 CLOGE("Stream %d does not exist", streamId);
2070 return BAD_VALUE;
2071 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002072 stream->addBufferListener(listener);
2073
2074 return OK;
2075}
2076
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002077/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002078 * Methods called by subclasses
2079 */
2080
2081void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002082 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002083 {
2084 // Need mLock to safely update state and synchronize to current
2085 // state of methods in flight.
2086 Mutex::Autolock l(mLock);
2087 // We can get various system-idle notices from the status tracker
2088 // while starting up. Only care about them if we've actually sent
2089 // in some requests recently.
2090 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2091 return;
2092 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002093 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2094 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002095 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002096
2097 // Skip notifying listener if we're doing some user-transparent
2098 // state changes
2099 if (mPauseStateNotify) return;
2100 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002101
2102 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002103 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002104 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002105 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002106 }
2107 if (idle && listener != NULL) {
2108 listener->notifyIdle();
2109 }
2110}
2111
Shuzhen Wang758c2152017-01-10 18:26:18 -08002112status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002113 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002114 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002115 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2116 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002117
2118 if (surfaceIds == nullptr) {
2119 return BAD_VALUE;
2120 }
2121
Zhijun He5d677d12016-05-29 16:52:39 -07002122 Mutex::Autolock il(mInterfaceLock);
2123 Mutex::Autolock l(mLock);
2124
Shuzhen Wang758c2152017-01-10 18:26:18 -08002125 if (consumers.size() == 0) {
2126 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002127 return BAD_VALUE;
2128 }
2129
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002130 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2131 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002132 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002133 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002134 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002135
2136 // isConsumerConfigurationDeferred will be off after setConsumers
2137 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002138 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002139 if (res != OK) {
2140 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2141 return res;
2142 }
2143
Emilian Peev40ead602017-09-26 15:46:36 +01002144 for (auto &consumer : consumers) {
2145 int id = stream->getSurfaceId(consumer);
2146 if (id < 0) {
2147 CLOGE("Invalid surface id!");
2148 return BAD_VALUE;
2149 }
2150 surfaceIds->push_back(id);
2151 }
2152
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002153 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002154 if (!stream->isConfiguring()) {
2155 CLOGE("Stream %d was already fully configured.", streamId);
2156 return INVALID_OPERATION;
2157 }
Zhijun He5d677d12016-05-29 16:52:39 -07002158
Shuzhen Wang0129d522016-10-30 22:43:41 -07002159 res = stream->finishConfiguration();
2160 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002161 // If finishConfiguration fails due to abandoned surface, do not set
2162 // device to error state.
2163 bool isSurfaceAbandoned =
2164 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2165 if (!isSurfaceAbandoned) {
2166 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2167 stream->getId(), strerror(-res), res);
2168 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002169 return res;
2170 }
Zhijun He5d677d12016-05-29 16:52:39 -07002171 }
2172
2173 return OK;
2174}
2175
Emilian Peev40ead602017-09-26 15:46:36 +01002176status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2177 const std::vector<OutputStreamInfo> &outputInfo,
2178 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2179 Mutex::Autolock il(mInterfaceLock);
2180 Mutex::Autolock l(mLock);
2181
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002182 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2183 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002184 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002185 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002186 }
2187
2188 for (const auto &it : removedSurfaceIds) {
2189 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2190 CLOGE("Shared surface still part of a pending request!");
2191 return -EBUSY;
2192 }
2193 }
2194
Emilian Peev40ead602017-09-26 15:46:36 +01002195 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2196 if (res != OK) {
2197 CLOGE("Stream %d failed to update stream (error %d %s) ",
2198 streamId, res, strerror(-res));
2199 if (res == UNKNOWN_ERROR) {
2200 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2201 __FUNCTION__);
2202 }
2203 return res;
2204 }
2205
2206 return res;
2207}
2208
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002209status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2210 Mutex::Autolock il(mInterfaceLock);
2211 Mutex::Autolock l(mLock);
2212
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002213 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2214 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002215 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2216 return BAD_VALUE;
2217 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002218 return stream->dropBuffers(dropping);
2219}
2220
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002221/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002222 * Camera3Device private methods
2223 */
2224
2225sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002226 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002227 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002228
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002229 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002230 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002231
2232 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002233 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002234 if (inputStreams.count > 0) {
2235 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002236 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002237 CLOGE("Request references unknown input stream %d",
2238 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002239 return NULL;
2240 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002241
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002242 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002243 SET_ERR_L("%s: input stream %d is not configured!",
2244 __FUNCTION__, mInputStream->getId());
2245 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002246 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002247 // Check if stream prepare is blocking requests.
2248 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002249 CLOGE("Request references an input stream that's being prepared!");
2250 return NULL;
2251 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002252
2253 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002254 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002255 }
2256
2257 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002258 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002259 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002260 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002261 return NULL;
2262 }
2263
2264 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002265 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2266 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002267 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002268 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002269 return NULL;
2270 }
Zhijun He5d677d12016-05-29 16:52:39 -07002271 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002272 auto iter = surfaceMap.find(streams.data.i32[i]);
2273 if (iter != surfaceMap.end()) {
2274 const std::vector<size_t>& surfaces = iter->second;
2275 for (const auto& surface : surfaces) {
2276 if (stream->isConsumerConfigurationDeferred(surface)) {
2277 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2278 "due to deferred consumer", stream->getId(), surface);
2279 return NULL;
2280 }
2281 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002282 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002283 }
2284
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002285 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002286 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2287 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002288 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002289 // Check if stream prepare is blocking requests.
2290 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002291 CLOGE("Request references an output stream that's being prepared!");
2292 return NULL;
2293 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002294
2295 newRequest->mOutputStreams.push(stream);
2296 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002297 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002298 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002299
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002300 auto rotateAndCropEntry =
2301 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2302 if (rotateAndCropEntry.count > 0 &&
2303 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2304 newRequest->mRotateAndCropAuto = true;
2305 } else {
2306 newRequest->mRotateAndCropAuto = false;
2307 }
2308
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07002309 auto zoomRatioEntry =
2310 newRequest->mSettingsList.begin()->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
2311 if (zoomRatioEntry.count > 0 &&
2312 zoomRatioEntry.data.f[0] == 1.0f) {
2313 newRequest->mZoomRatioIs1x = true;
2314 } else {
2315 newRequest->mZoomRatioIs1x = false;
2316 }
2317
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002318 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002319}
2320
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002321void Camera3Device::cancelStreamsConfigurationLocked() {
2322 int res = OK;
2323 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2324 res = mInputStream->cancelConfiguration();
2325 if (res != OK) {
2326 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2327 mInputStream->getId(), strerror(-res), res);
2328 }
2329 }
2330
2331 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002332 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002333 if (outputStream->isConfiguring()) {
2334 res = outputStream->cancelConfiguration();
2335 if (res != OK) {
2336 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2337 outputStream->getId(), strerror(-res), res);
2338 }
2339 }
2340 }
2341
2342 // Return state to that at start of call, so that future configures
2343 // properly clean things up
2344 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2345 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002346
2347 res = mPreparerThread->resume();
2348 if (res != OK) {
2349 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2350 }
2351}
2352
Emilian Peev0d0191e2020-04-21 17:01:18 -07002353bool Camera3Device::checkAbandonedStreamsLocked() {
2354 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2355 return true;
2356 }
2357
2358 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2359 auto stream = mOutputStreams[i];
2360 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2361 return true;
2362 }
2363 }
2364
2365 return false;
2366}
2367
Emilian Peev3bead5f2020-05-28 17:29:08 -07002368bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002369 ATRACE_CALL();
2370 bool ret = false;
2371
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002372 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002373 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2374
2375 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002376 if (checkAbandonedStreamsLocked()) {
2377 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2378 __FUNCTION__);
2379 return true;
2380 }
2381
Emilian Peev3bead5f2020-05-28 17:29:08 -07002382 status_t rc = NO_ERROR;
2383 bool markClientActive = false;
2384 if (mStatus == STATUS_ACTIVE) {
2385 markClientActive = true;
2386 mPauseStateNotify = true;
2387 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2388
2389 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2390 }
2391
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002392 if (rc == NO_ERROR) {
2393 mNeedConfig = true;
2394 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2395 if (rc == NO_ERROR) {
2396 ret = true;
2397 mPauseStateNotify = false;
2398 //Moving to active state while holding 'mLock' is important.
2399 //There could be pending calls to 'create-/deleteStream' which
2400 //will trigger another stream configuration while the already
2401 //present streams end up with outstanding buffers that will
2402 //not get drained.
2403 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002404 } else if (rc == DEAD_OBJECT) {
2405 // DEAD_OBJECT can be returned if either the consumer surface is
2406 // abandoned, or the HAL has died.
2407 // - If the HAL has died, configureStreamsLocked call will set
2408 // device to error state,
2409 // - If surface is abandoned, we should not set device to error
2410 // state.
2411 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002412 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002413 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002414 }
2415 } else {
2416 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2417 }
2418
Emilian Peev3bead5f2020-05-28 17:29:08 -07002419 if (markClientActive) {
2420 mStatusTracker->markComponentActive(clientStatusId);
2421 }
2422
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002423 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002424}
2425
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002426status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002427 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002428 ATRACE_CALL();
2429 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002430
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002431 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002432 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002433 return INVALID_OPERATION;
2434 }
2435
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002436 if (operatingMode < 0) {
2437 CLOGE("Invalid operating mode: %d", operatingMode);
2438 return BAD_VALUE;
2439 }
2440
2441 bool isConstrainedHighSpeed =
2442 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2443 operatingMode;
2444
2445 if (mOperatingMode != operatingMode) {
2446 mNeedConfig = true;
2447 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2448 mOperatingMode = operatingMode;
2449 }
2450
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002451 // In case called from configureStreams, abort queued input buffers not belonging to
2452 // any pending requests.
2453 if (mInputStream != NULL && notifyRequestThread) {
2454 while (true) {
2455 camera3_stream_buffer_t inputBuffer;
2456 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2457 /*respectHalLimit*/ false);
2458 if (res != OK) {
2459 // Exhausted acquiring all input buffers.
2460 break;
2461 }
2462
2463 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2464 res = mInputStream->returnInputBuffer(inputBuffer);
2465 if (res != OK) {
2466 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2467 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2468 }
2469 }
2470 }
2471
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002472 if (!mNeedConfig) {
2473 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2474 return OK;
2475 }
2476
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002477 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2478 // adding a dummy stream instead.
2479 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2480 if (mOutputStreams.size() == 0) {
2481 addDummyStreamLocked();
2482 } else {
2483 tryRemoveDummyStreamLocked();
2484 }
2485
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002486 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002487 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002488
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002489 mPreparerThread->pause();
2490
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002491 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002492 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002493 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2494
2495 Vector<camera3_stream_t*> streams;
2496 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002497 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002498
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002499
2500 if (mInputStream != NULL) {
2501 camera3_stream_t *inputStream;
2502 inputStream = mInputStream->startConfiguration();
2503 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002504 CLOGE("Can't start input stream configuration");
2505 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002506 return INVALID_OPERATION;
2507 }
2508 streams.add(inputStream);
2509 }
2510
2511 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002512
2513 // Don't configure bidi streams twice, nor add them twice to the list
2514 if (mOutputStreams[i].get() ==
2515 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2516
2517 config.num_streams--;
2518 continue;
2519 }
2520
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002521 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002522 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002523 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002524 CLOGE("Can't start output stream configuration");
2525 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002526 return INVALID_OPERATION;
2527 }
2528 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002529
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002530 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002531 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2532 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002533 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2534 bufferSizes[k] = static_cast<uint32_t>(
2535 getJpegBufferSize(outputStream->width, outputStream->height));
2536 } else if (outputStream->data_space ==
2537 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2538 bufferSizes[k] = outputStream->width * outputStream->height;
2539 } else {
2540 ALOGW("%s: Blob dataSpace %d not supported",
2541 __FUNCTION__, outputStream->data_space);
2542 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002543 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002544 }
2545
2546 config.streams = streams.editArray();
2547
2548 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002549 // max_buffers, usage, and priv fields, as well as data_space and format
2550 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002551
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002552 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002553 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002554 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002555
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002556 if (res == BAD_VALUE) {
2557 // HAL rejected this set of streams as unsupported, clean up config
2558 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002559 CLOGE("Set of requested inputs/outputs not supported by HAL");
2560 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002561 return BAD_VALUE;
2562 } else if (res != OK) {
2563 // Some other kind of error from configure_streams - this is not
2564 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002565 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2566 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002567 return res;
2568 }
2569
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002570 // Finish all stream configuration immediately.
2571 // TODO: Try to relax this later back to lazy completion, which should be
2572 // faster
2573
Igor Murashkin073f8572013-05-02 14:59:28 -07002574 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002575 bool streamReConfigured = false;
2576 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002577 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002578 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002579 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002580 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002581 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2582 return DEAD_OBJECT;
2583 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002584 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002585 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002586 if (streamReConfigured) {
2587 mInterface->onStreamReConfigured(mInputStream->getId());
2588 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002589 }
2590
2591 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002592 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002593 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002594 bool streamReConfigured = false;
2595 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002596 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002597 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002598 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002599 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002600 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2601 return DEAD_OBJECT;
2602 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002603 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002604 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002605 if (streamReConfigured) {
2606 mInterface->onStreamReConfigured(outputStream->getId());
2607 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002608 }
2609 }
2610
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002611 // Request thread needs to know to avoid using repeat-last-settings protocol
2612 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002613 if (notifyRequestThread) {
2614 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2615 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002616
Zhijun He90f7c372016-08-16 16:19:43 -07002617 char value[PROPERTY_VALUE_MAX];
2618 property_get("camera.fifo.disable", value, "0");
2619 int32_t disableFifo = atoi(value);
2620 if (disableFifo != 1) {
2621 // Boost priority of request thread to SCHED_FIFO.
2622 pid_t requestThreadTid = mRequestThread->getTid();
2623 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002624 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002625 if (res != OK) {
2626 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2627 strerror(-res), res);
2628 } else {
2629 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2630 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002631 }
2632
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002633 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002634 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2635 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2636 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2637 sessionParams.unlock(newSessionParams);
2638 mSessionParams.unlock(currentSessionParams);
2639 if (updateSessionParams) {
2640 mSessionParams = sessionParams;
2641 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002642
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002643 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002644
Ruben Brunk183f0562015-08-12 12:55:02 -07002645 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2646 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002647
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002648 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002649
Zhijun He0a210512014-07-24 13:45:15 -07002650 // tear down the deleted streams after configure streams.
2651 mDeletedStreams.clear();
2652
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002653 auto rc = mPreparerThread->resume();
2654 if (rc != OK) {
2655 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2656 return rc;
2657 }
2658
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002659 if (mDummyStreamId == NO_STREAM) {
2660 mRequestBufferSM.onStreamsConfigured();
2661 }
2662
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002663 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002664}
2665
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002666status_t Camera3Device::addDummyStreamLocked() {
2667 ATRACE_CALL();
2668 status_t res;
2669
2670 if (mDummyStreamId != NO_STREAM) {
2671 // Should never be adding a second dummy stream when one is already
2672 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002673 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2674 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002675 return INVALID_OPERATION;
2676 }
2677
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002678 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002679
2680 sp<Camera3OutputStreamInterface> dummyStream =
2681 new Camera3DummyStream(mNextStreamId);
2682
2683 res = mOutputStreams.add(mNextStreamId, dummyStream);
2684 if (res < 0) {
2685 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2686 return res;
2687 }
2688
2689 mDummyStreamId = mNextStreamId;
2690 mNextStreamId++;
2691
2692 return OK;
2693}
2694
2695status_t Camera3Device::tryRemoveDummyStreamLocked() {
2696 ATRACE_CALL();
2697 status_t res;
2698
2699 if (mDummyStreamId == NO_STREAM) return OK;
2700 if (mOutputStreams.size() == 1) return OK;
2701
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002702 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002703
2704 // Ok, have a dummy stream and there's at least one other output stream,
2705 // so remove the dummy
2706
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002707 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2708 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002709 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2710 return INVALID_OPERATION;
2711 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002712 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002713
2714 // Free up the stream endpoint so that it can be used by some other stream
2715 res = deletedStream->disconnect();
2716 if (res != OK) {
2717 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2718 // fall through since we want to still list the stream as deleted.
2719 }
2720 mDeletedStreams.add(deletedStream);
2721 mDummyStreamId = NO_STREAM;
2722
2723 return res;
2724}
2725
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002726void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002727 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002728 Mutex::Autolock l(mLock);
2729 va_list args;
2730 va_start(args, fmt);
2731
2732 setErrorStateLockedV(fmt, args);
2733
2734 va_end(args);
2735}
2736
2737void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002738 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002739 Mutex::Autolock l(mLock);
2740 setErrorStateLockedV(fmt, args);
2741}
2742
2743void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2744 va_list args;
2745 va_start(args, fmt);
2746
2747 setErrorStateLockedV(fmt, args);
2748
2749 va_end(args);
2750}
2751
2752void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002753 // Print out all error messages to log
2754 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002755 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002756
2757 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002758 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002759
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002760 mErrorCause = errorCause;
2761
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002762 if (mRequestThread != nullptr) {
2763 mRequestThread->setPaused(true);
2764 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002765 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002766
2767 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002768 sp<NotificationListener> listener = mListener.promote();
2769 if (listener != NULL) {
2770 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002771 CaptureResultExtras());
2772 }
2773
2774 // Save stack trace. View by dumping it later.
2775 CameraTraces::saveTrace();
2776 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002777}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002778
2779/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002780 * In-flight request management
2781 */
2782
Jianing Weicb0652e2014-03-12 18:29:36 -07002783status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002784 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002785 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002786 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002787 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08002788 const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002789 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002790 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002791
2792 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002793 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002794 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002795 rotateAndCropAuto, cameraIdsWithZoom, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002796 if (res < 0) return res;
2797
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002798 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002799 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2800 // avoid a deadlock during reprocess requests.
2801 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002802 if (mStatusTracker != nullptr) {
2803 mStatusTracker->markComponentActive(mInFlightStatusId);
2804 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002805 }
2806
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002807 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002808 return OK;
2809}
2810
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002811void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002812 // Indicate idle inFlightMap to the status tracker
2813 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002814 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002815 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2816 // avoid a deadlock during reprocess requests.
2817 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002818 if (mStatusTracker != nullptr) {
2819 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2820 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002821 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002822 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002823}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002824
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002825void Camera3Device::checkInflightMapLengthLocked() {
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002826 // Sanity check - if we have too many in-flight frames with long total inflight duration,
2827 // something has likely gone wrong. This might still be legit only if application send in
2828 // a long burst of long exposure requests.
2829 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2830 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2831 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2832 mInFlightMap.size(), mExpectedInflightDuration);
2833 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2834 kInFlightWarnLimitHighSpeed) {
2835 CLOGW("In-flight list too large for high speed configuration: %zu,"
2836 "total inflight duration %" PRIu64,
2837 mInFlightMap.size(), mExpectedInflightDuration);
2838 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002839 }
2840}
2841
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002842void Camera3Device::onInflightMapFlushedLocked() {
2843 mExpectedInflightDuration = 0;
2844}
2845
2846void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002847 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002848 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2849 mInFlightMap.removeItemsAt(idx, 1);
2850
2851 onInflightEntryRemovedLocked(duration);
2852}
2853
2854
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002855void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002856 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002857 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002858 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002859 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002860 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002861 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002862
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002863 FlushInflightReqStates states {
2864 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
2865 listener, *this, *mInterface, *this};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002866
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002867 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002868}
2869
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002870CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002871 ALOGV("%s", __FUNCTION__);
2872
Igor Murashkin1e479c02013-09-06 16:55:14 -07002873 CameraMetadata retVal;
2874
2875 if (mRequestThread != NULL) {
2876 retVal = mRequestThread->getLatestRequest();
2877 }
2878
Igor Murashkin1e479c02013-09-06 16:55:14 -07002879 return retVal;
2880}
2881
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002882void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002883 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2884 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2885
2886 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2887 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002888}
2889
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002890/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002891 * HalInterface inner class methods
2892 */
2893
Yifan Hongf79b5542017-04-11 14:44:25 -07002894Camera3Device::HalInterface::HalInterface(
2895 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002896 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002897 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002898 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002899 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08002900 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002901 mIsReconfigurationQuerySupported(true),
2902 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002903 // Check with hardware service manager if we can downcast these interfaces
2904 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002905 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
2906 if (castResult_3_6.isOk()) {
2907 mHidlSession_3_6 = castResult_3_6;
2908 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002909 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
2910 if (castResult_3_5.isOk()) {
2911 mHidlSession_3_5 = castResult_3_5;
2912 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002913 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
2914 if (castResult_3_4.isOk()) {
2915 mHidlSession_3_4 = castResult_3_4;
2916 }
2917 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
2918 if (castResult_3_3.isOk()) {
2919 mHidlSession_3_3 = castResult_3_3;
2920 }
2921}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002922
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002923Camera3Device::HalInterface::HalInterface() :
2924 mUseHalBufManager(false),
2925 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002926
2927Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002928 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002929 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002930 mUseHalBufManager(other.mUseHalBufManager),
2931 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002932
2933bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01002934 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002935}
2936
2937void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002938 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00002939 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00002940 mHidlSession_3_4.clear();
2941 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002942 mHidlSession.clear();
2943}
2944
2945status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2946 camera3_request_template_t templateId,
2947 /*out*/ camera_metadata_t **requestTemplate) {
2948 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
2949 if (!valid()) return INVALID_OPERATION;
2950 status_t res = OK;
2951
Emilian Peev31abd0a2017-05-11 18:37:46 +01002952 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002953
2954 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01002955 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002956 status = s;
2957 if (status == common::V1_0::Status::OK) {
2958 const camera_metadata *r =
2959 reinterpret_cast<const camera_metadata_t*>(request.data());
2960 size_t expectedSize = request.size();
2961 int ret = validate_camera_metadata_structure(r, &expectedSize);
2962 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
2963 *requestTemplate = clone_camera_metadata(r);
2964 if (*requestTemplate == nullptr) {
2965 ALOGE("%s: Unable to clone camera metadata received from HAL",
2966 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01002967 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002968 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002969 } else {
2970 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
2971 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01002972 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002973 }
2974 };
2975 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08002976 RequestTemplate id;
2977 switch (templateId) {
2978 case CAMERA3_TEMPLATE_PREVIEW:
2979 id = RequestTemplate::PREVIEW;
2980 break;
2981 case CAMERA3_TEMPLATE_STILL_CAPTURE:
2982 id = RequestTemplate::STILL_CAPTURE;
2983 break;
2984 case CAMERA3_TEMPLATE_VIDEO_RECORD:
2985 id = RequestTemplate::VIDEO_RECORD;
2986 break;
2987 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
2988 id = RequestTemplate::VIDEO_SNAPSHOT;
2989 break;
2990 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
2991 id = RequestTemplate::ZERO_SHUTTER_LAG;
2992 break;
2993 case CAMERA3_TEMPLATE_MANUAL:
2994 id = RequestTemplate::MANUAL;
2995 break;
2996 default:
2997 // Unknown template ID, or this HAL is too old to support it
2998 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002999 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003000 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003001
Emilian Peev31abd0a2017-05-11 18:37:46 +01003002 if (!err.isOk()) {
3003 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3004 res = DEAD_OBJECT;
3005 } else {
3006 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003007 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003008
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003009 return res;
3010}
3011
Emilian Peev4ec17882019-01-24 17:16:58 -08003012bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3013 CameraMetadata& newSessionParams) {
3014 // We do reconfiguration by default;
3015 bool ret = true;
3016 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3017 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3018 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3019 oldSessionParams.getAndLock());
3020 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3021 newSessionParams.getAndLock());
3022 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3023 get_camera_metadata_size(oldSessioMeta));
3024 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3025 get_camera_metadata_size(newSessioMeta));
3026 hardware::camera::common::V1_0::Status callStatus;
3027 bool required;
3028 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3029 bool requiredFlag) {
3030 callStatus = s;
3031 required = requiredFlag;
3032 };
3033 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3034 oldSessionParams.unlock(oldSessioMeta);
3035 newSessionParams.unlock(newSessioMeta);
3036 if (err.isOk()) {
3037 switch (callStatus) {
3038 case hardware::camera::common::V1_0::Status::OK:
3039 ret = required;
3040 break;
3041 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3042 mIsReconfigurationQuerySupported = false;
3043 ret = true;
3044 break;
3045 default:
3046 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3047 ret = true;
3048 }
3049 } else {
3050 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3051 ret = true;
3052 }
3053 }
3054
3055 return ret;
3056}
3057
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003058status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003059 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003060 ATRACE_NAME("CameraHal::configureStreams");
3061 if (!valid()) return INVALID_OPERATION;
3062 status_t res = OK;
3063
Emilian Peev31abd0a2017-05-11 18:37:46 +01003064 // Convert stream config to HIDL
3065 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003066 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3067 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3068 requestedConfiguration3_2.streams.resize(config->num_streams);
3069 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003070 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003071 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3072 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003073 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003074
Emilian Peev31abd0a2017-05-11 18:37:46 +01003075 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3076 cam3stream->setBufferFreedListener(this);
3077 int streamId = cam3stream->getId();
3078 StreamType streamType;
3079 switch (src->stream_type) {
3080 case CAMERA3_STREAM_OUTPUT:
3081 streamType = StreamType::OUTPUT;
3082 break;
3083 case CAMERA3_STREAM_INPUT:
3084 streamType = StreamType::INPUT;
3085 break;
3086 default:
3087 ALOGE("%s: Stream %d: Unsupported stream type %d",
3088 __FUNCTION__, streamId, config->streams[i]->stream_type);
3089 return BAD_VALUE;
3090 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003091 dst3_2.id = streamId;
3092 dst3_2.streamType = streamType;
3093 dst3_2.width = src->width;
3094 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003095 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003096 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003097 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3098 // to HAL are original, not the overriden ones.
3099 if (mHidlSession_3_5 != nullptr) {
3100 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3101 cam3stream->getOriginalFormat() : src->format);
3102 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3103 cam3stream->getOriginalDataSpace() : src->data_space);
3104 } else {
3105 dst3_2.format = mapToPixelFormat(src->format);
3106 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3107 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003108 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003109 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003110 if (src->physical_camera_id != nullptr) {
3111 dst3_4.physicalCameraId = src->physical_camera_id;
3112 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003113
3114 activeStreams.insert(streamId);
3115 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003116 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003117 }
3118 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003119 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003120
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003121 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003122 res = mapToStreamConfigurationMode(
3123 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003124 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003125 if (res != OK) {
3126 return res;
3127 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003128 requestedConfiguration3_2.operationMode = operationMode;
3129 requestedConfiguration3_4.operationMode = operationMode;
3130 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003131 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3132 get_camera_metadata_size(sessionParams));
3133
Emilian Peev31abd0a2017-05-11 18:37:46 +01003134 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003135 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003136 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003137 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003138 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003139
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003140 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003141 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3142 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003143 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003144 };
3145
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003146 auto configStream36Cb = [&status, &finalConfiguration3_6]
3147 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3148 finalConfiguration3_6 = halConfiguration;
3149 status = s;
3150 };
3151
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003152 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3153 (hardware::Return<void>& err) -> status_t {
3154 if (!err.isOk()) {
3155 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3156 return DEAD_OBJECT;
3157 }
3158 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3159 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3160 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3161 }
3162 return OK;
3163 };
3164
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003165 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3166 (hardware::Return<void>& err) -> status_t {
3167 if (!err.isOk()) {
3168 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3169 return DEAD_OBJECT;
3170 }
3171 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3172 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3173 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3174 }
3175 return OK;
3176 };
3177
Shuzhen Wang92653952019-05-07 15:11:43 -07003178 // See which version of HAL we have
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003179 if (mHidlSession_3_6 != nullptr) {
3180 ALOGV("%s: v3.6 device found", __FUNCTION__);
3181 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3182 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3183 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3184 auto err = mHidlSession_3_6->configureStreams_3_6(
3185 requestedConfiguration3_5, configStream36Cb);
3186 res = postprocConfigStream36(err);
3187 if (res != OK) {
3188 return res;
3189 }
3190 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003191 ALOGV("%s: v3.5 device found", __FUNCTION__);
3192 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3193 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3194 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3195 auto err = mHidlSession_3_5->configureStreams_3_5(
3196 requestedConfiguration3_5, configStream34Cb);
3197 res = postprocConfigStream34(err);
3198 if (res != OK) {
3199 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003200 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003201 } else if (mHidlSession_3_4 != nullptr) {
3202 // We do; use v3.4 for the call
3203 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003204 auto err = mHidlSession_3_4->configureStreams_3_4(
3205 requestedConfiguration3_4, configStream34Cb);
3206 res = postprocConfigStream34(err);
3207 if (res != OK) {
3208 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003209 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003210 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003211 // We do; use v3.3 for the call
3212 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003213 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003214 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003215 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003216 finalConfiguration = halConfiguration;
3217 status = s;
3218 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003219 if (!err.isOk()) {
3220 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3221 return DEAD_OBJECT;
3222 }
3223 } else {
3224 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3225 ALOGV("%s: v3.2 device found", __FUNCTION__);
3226 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003227 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003228 [&status, &finalConfiguration_3_2]
3229 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3230 finalConfiguration_3_2 = halConfiguration;
3231 status = s;
3232 });
3233 if (!err.isOk()) {
3234 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3235 return DEAD_OBJECT;
3236 }
3237 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3238 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3239 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3240 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003241 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003242 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003243 }
3244
3245 if (status != common::V1_0::Status::OK ) {
3246 return CameraProviderManager::mapToStatusT(status);
3247 }
3248
3249 // And convert output stream configuration from HIDL
3250
3251 for (size_t i = 0; i < config->num_streams; i++) {
3252 camera3_stream_t *dst = config->streams[i];
3253 int streamId = Camera3Stream::cast(dst)->getId();
3254
3255 // Start scan at i, with the assumption that the stream order matches
3256 size_t realIdx = i;
3257 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003258 size_t halStreamCount = finalConfiguration.streams.size();
3259 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003260 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003261 found = true;
3262 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003263 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003264 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003265 }
3266 if (!found) {
3267 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3268 __FUNCTION__, streamId);
3269 return INVALID_OPERATION;
3270 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003271 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003272 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003273
Emilian Peev710c1422017-08-30 11:19:38 +01003274 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003275 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3276 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3277
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003278 if (mHidlSession_3_6 != nullptr) {
3279 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3280 }
3281
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003282 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003283 dstStream->setFormatOverride(false);
3284 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003285 if (dst->format != overrideFormat) {
3286 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3287 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003288 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003289 if (dst->data_space != overrideDataSpace) {
3290 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3291 streamId, dst->format);
3292 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003293 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003294 bool needFormatOverride =
3295 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3296 bool needDataspaceOverride =
3297 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003298 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003299 dstStream->setFormatOverride(needFormatOverride);
3300 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003301 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003302 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003303 }
3304
Emilian Peev31abd0a2017-05-11 18:37:46 +01003305 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003306 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003307 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003308 __FUNCTION__, streamId);
3309 return INVALID_OPERATION;
3310 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003311 dstStream->setUsage(
3312 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003313 } else {
3314 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003315 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003316 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3317 __FUNCTION__, streamId);
3318 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003319 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003320 dstStream->setUsage(
3321 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003322 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003323 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003324 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003325
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003326 return res;
3327}
3328
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003329status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003330 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003331 /*out*/std::vector<native_handle_t*>* handlesCreated,
3332 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003333 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003334 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3335 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3336 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003337 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003338 }
3339
3340 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003341
3342 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003343
3344 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003345 if (request->input_buffer != nullptr) {
3346 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3347 buffer_handle_t buf = *(request->input_buffer->buffer);
3348 auto pair = getBufferId(buf, streamId);
3349 bool isNewBuffer = pair.first;
3350 uint64_t bufferId = pair.second;
3351 captureRequest->inputBuffer.streamId = streamId;
3352 captureRequest->inputBuffer.bufferId = bufferId;
3353 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3354 captureRequest->inputBuffer.status = BufferStatus::OK;
3355 native_handle_t *acquireFence = nullptr;
3356 if (request->input_buffer->acquire_fence != -1) {
3357 acquireFence = native_handle_create(1,0);
3358 acquireFence->data[0] = request->input_buffer->acquire_fence;
3359 handlesCreated->push_back(acquireFence);
3360 }
3361 captureRequest->inputBuffer.acquireFence = acquireFence;
3362 captureRequest->inputBuffer.releaseFence = nullptr;
3363
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003364 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003365 request->input_buffer->buffer);
3366 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003367 } else {
3368 captureRequest->inputBuffer.streamId = -1;
3369 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3370 }
3371
3372 captureRequest->outputBuffers.resize(request->num_output_buffers);
3373 for (size_t i = 0; i < request->num_output_buffers; i++) {
3374 const camera3_stream_buffer_t *src = request->output_buffers + i;
3375 StreamBuffer &dst = captureRequest->outputBuffers[i];
3376 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003377 if (src->buffer != nullptr) {
3378 buffer_handle_t buf = *(src->buffer);
3379 auto pair = getBufferId(buf, streamId);
3380 bool isNewBuffer = pair.first;
3381 dst.bufferId = pair.second;
3382 dst.buffer = isNewBuffer ? buf : nullptr;
3383 native_handle_t *acquireFence = nullptr;
3384 if (src->acquire_fence != -1) {
3385 acquireFence = native_handle_create(1,0);
3386 acquireFence->data[0] = src->acquire_fence;
3387 handlesCreated->push_back(acquireFence);
3388 }
3389 dst.acquireFence = acquireFence;
3390 } else if (mUseHalBufManager) {
3391 // HAL buffer management path
3392 dst.bufferId = BUFFER_ID_NO_BUFFER;
3393 dst.buffer = nullptr;
3394 dst.acquireFence = nullptr;
3395 } else {
3396 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3397 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003398 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003399 dst.streamId = streamId;
3400 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003401 dst.releaseFence = nullptr;
3402
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003403 // Output buffers are empty when using HAL buffer manager
3404 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003405 mBufferRecords.pushInflightBuffer(
3406 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003407 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003408 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003409 }
3410 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003411 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003412}
3413
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003414void Camera3Device::HalInterface::cleanupNativeHandles(
3415 std::vector<native_handle_t*> *handles, bool closeFd) {
3416 if (handles == nullptr) {
3417 return;
3418 }
3419 if (closeFd) {
3420 for (auto& handle : *handles) {
3421 native_handle_close(handle);
3422 }
3423 }
3424 for (auto& handle : *handles) {
3425 native_handle_delete(handle);
3426 }
3427 handles->clear();
3428 return;
3429}
3430
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003431status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3432 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3433 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3434 if (!valid()) return INVALID_OPERATION;
3435
Emilian Peevaebbe412018-01-15 13:53:24 +00003436 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3437 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3438 if (castResult_3_4.isOk()) {
3439 hidlSession_3_4 = castResult_3_4;
3440 }
3441
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003442 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003443 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003444 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003445 if (hidlSession_3_4 != nullptr) {
3446 captureRequests_3_4.resize(batchSize);
3447 } else {
3448 captureRequests.resize(batchSize);
3449 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003450 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003451 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003452
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003453 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003454 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003455 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003456 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003457 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003458 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003459 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3460 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003461 }
3462 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003463 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003464 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003465 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003466 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003467 }
3468
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003469 std::vector<device::V3_2::BufferCache> cachesToRemove;
3470 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003471 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003472 for (auto& pair : mFreedBuffers) {
3473 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003474 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003475 cachesToRemove.push_back({pair.first, pair.second});
3476 }
3477 }
3478 mFreedBuffers.clear();
3479 }
3480
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003481 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3482 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003483
3484 // Write metadata to FMQ.
3485 for (size_t i = 0; i < batchSize; i++) {
3486 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003487 device::V3_2::CaptureRequest* captureRequest;
3488 if (hidlSession_3_4 != nullptr) {
3489 captureRequest = &captureRequests_3_4[i].v3_2;
3490 } else {
3491 captureRequest = &captureRequests[i];
3492 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003493
3494 if (request->settings != nullptr) {
3495 size_t settingsSize = get_camera_metadata_size(request->settings);
3496 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3497 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3498 captureRequest->settings.resize(0);
3499 captureRequest->fmqSettingsSize = settingsSize;
3500 } else {
3501 if (mRequestMetadataQueue != nullptr) {
3502 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3503 }
3504 captureRequest->settings.setToExternal(
3505 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3506 get_camera_metadata_size(request->settings));
3507 captureRequest->fmqSettingsSize = 0u;
3508 }
3509 } else {
3510 // A null request settings maps to a size-0 CameraMetadata
3511 captureRequest->settings.resize(0);
3512 captureRequest->fmqSettingsSize = 0u;
3513 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003514
3515 if (hidlSession_3_4 != nullptr) {
3516 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3517 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003518 if (request->physcam_settings != nullptr) {
3519 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3520 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3521 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3522 settingsSize)) {
3523 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3524 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3525 settingsSize;
3526 } else {
3527 if (mRequestMetadataQueue != nullptr) {
3528 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3529 }
3530 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3531 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3532 request->physcam_settings[j])),
3533 get_camera_metadata_size(request->physcam_settings[j]));
3534 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003535 }
Emilian Peev00420d22018-02-05 21:33:13 +00003536 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003537 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003538 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003539 }
3540 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3541 request->physcam_id[j];
3542 }
3543 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003544 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003545
3546 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003547 auto resultCallback =
3548 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3549 status = s;
3550 *numRequestProcessed = n;
3551 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003552 if (hidlSession_3_4 != nullptr) {
3553 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003554 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003555 } else {
3556 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003557 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003558 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003559 if (!err.isOk()) {
3560 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003561 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003562 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003563
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003564 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3565 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3566 __FUNCTION__, *numRequestProcessed, batchSize);
3567 status = common::V1_0::Status::INTERNAL_ERROR;
3568 }
3569
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003570 res = CameraProviderManager::mapToStatusT(status);
3571 if (res == OK) {
3572 if (mHidlSession->isRemote()) {
3573 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3574 // sent to camera HAL processes)
3575 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3576 } else {
3577 // In passthrough mode the FDs are now owned by HAL
3578 cleanupNativeHandles(&handlesCreated);
3579 }
3580 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003581 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003582 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003583 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003584 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003585}
3586
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003587status_t Camera3Device::HalInterface::flush() {
3588 ATRACE_NAME("CameraHal::flush");
3589 if (!valid()) return INVALID_OPERATION;
3590 status_t res = OK;
3591
Emilian Peev31abd0a2017-05-11 18:37:46 +01003592 auto err = mHidlSession->flush();
3593 if (!err.isOk()) {
3594 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3595 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003596 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003597 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003598 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003599
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003600 return res;
3601}
3602
Emilian Peev31abd0a2017-05-11 18:37:46 +01003603status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003604 ATRACE_NAME("CameraHal::dump");
3605 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003606
Emilian Peev31abd0a2017-05-11 18:37:46 +01003607 // Handled by CameraProviderManager::dump
3608
3609 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003610}
3611
3612status_t Camera3Device::HalInterface::close() {
3613 ATRACE_NAME("CameraHal::close()");
3614 if (!valid()) return INVALID_OPERATION;
3615 status_t res = OK;
3616
Emilian Peev31abd0a2017-05-11 18:37:46 +01003617 auto err = mHidlSession->close();
3618 // Interface will be dead shortly anyway, so don't log errors
3619 if (!err.isOk()) {
3620 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003621 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003622
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003623 return res;
3624}
3625
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003626void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3627 ATRACE_NAME("CameraHal::signalPipelineDrain");
3628 if (!valid() || mHidlSession_3_5 == nullptr) {
3629 ALOGE("%s called on invalid camera!", __FUNCTION__);
3630 return;
3631 }
3632
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003633 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003634 if (!err.isOk()) {
3635 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3636 return;
3637 }
3638}
3639
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003640status_t Camera3Device::HalInterface::switchToOffline(
3641 const std::vector<int32_t>& streamsToKeep,
3642 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003643 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3644 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003645 ATRACE_NAME("CameraHal::switchToOffline");
3646 if (!valid() || mHidlSession_3_6 == nullptr) {
3647 ALOGE("%s called on invalid camera!", __FUNCTION__);
3648 return INVALID_OPERATION;
3649 }
3650
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003651 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3652 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003653 return INVALID_OPERATION;
3654 }
3655
3656 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003657 auto resultCallback =
3658 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3659 status = s;
3660 *offlineSessionInfo = info;
3661 *offlineSession = session;
3662 };
3663 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3664
3665 if (!err.isOk()) {
3666 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3667 return DEAD_OBJECT;
3668 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003669
3670 status_t ret = CameraProviderManager::mapToStatusT(status);
3671 if (ret != OK) {
3672 return ret;
3673 }
3674
3675 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3676 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3677 // returns from switchToOffline.
3678
3679
3680 // Validate buffer caches
3681 std::vector<int32_t> streams;
3682 streams.reserve(offlineSessionInfo->offlineStreams.size());
3683 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3684 int32_t id = offlineStream.id;
3685 streams.push_back(id);
3686 // Verify buffer caches
3687 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3688 offlineStream.circulatingBufferIds.end());
3689 if (!verifyBufferIds(id, bufIds)) {
3690 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3691 return UNKNOWN_ERROR;
3692 }
3693 }
3694
3695 // Move buffer records
3696 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3697 bufferRecords->takeInflightBufferMap(mBufferRecords);
3698 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3699 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003700}
3701
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003702void Camera3Device::HalInterface::getInflightBufferKeys(
3703 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003704 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003705 return;
3706}
3707
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003708void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3709 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003710 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003711 return;
3712}
3713
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003714bool Camera3Device::HalInterface::verifyBufferIds(
3715 int32_t streamId, std::vector<uint64_t>& bufIds) {
3716 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003717}
3718
3719status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003720 int32_t frameNumber, int32_t streamId,
3721 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003722 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003723}
3724
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003725status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003726 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003727 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003728}
3729
3730// Find and pop a buffer_handle_t based on bufferId
3731status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003732 uint64_t bufferId,
3733 /*out*/ buffer_handle_t** buffer,
3734 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003735 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003736}
3737
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003738std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3739 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003740 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003741}
3742
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003743void Camera3Device::HalInterface::onBufferFreed(
3744 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003745 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3746 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3747 if (bufferId != BUFFER_ID_NO_BUFFER) {
3748 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003749 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003750}
3751
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003752void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003753 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3754 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3755 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003756 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3757 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003758}
3759
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003760/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003761 * RequestThread inner class methods
3762 */
3763
3764Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003765 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003766 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3767 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003768 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003769 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003770 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003771 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003772 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003773 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003774 mReconfigured(false),
3775 mDoPause(false),
3776 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003777 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003778 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003779 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003780 mCurrentAfTriggerId(0),
3781 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003782 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003783 mRepeatingLastFrameNumber(
3784 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003785 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003786 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003787 mRequestLatency(kRequestLatencyBinSize),
3788 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003789 mLatestSessionParams(sessionParamKeys.size()),
3790 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003791 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003792}
3793
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003794Camera3Device::RequestThread::~RequestThread() {}
3795
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003796void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003797 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003798 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003799 Mutex::Autolock l(mRequestLock);
3800 mListener = listener;
3801}
3802
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003803void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3804 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003805 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003806 Mutex::Autolock l(mRequestLock);
3807 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003808 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003809 // Prepare video stream for high speed recording.
3810 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003811 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003812}
3813
Jianing Wei90e59c92014-03-12 18:29:36 -07003814status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003815 List<sp<CaptureRequest> > &requests,
3816 /*out*/
3817 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003818 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003819 Mutex::Autolock l(mRequestLock);
3820 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3821 ++it) {
3822 mRequestQueue.push_back(*it);
3823 }
3824
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003825 if (lastFrameNumber != NULL) {
3826 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3827 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3828 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3829 *lastFrameNumber);
3830 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003831
Jianing Wei90e59c92014-03-12 18:29:36 -07003832 unpauseForNewRequests();
3833
3834 return OK;
3835}
3836
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003837
3838status_t Camera3Device::RequestThread::queueTrigger(
3839 RequestTrigger trigger[],
3840 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003841 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003842 Mutex::Autolock l(mTriggerMutex);
3843 status_t ret;
3844
3845 for (size_t i = 0; i < count; ++i) {
3846 ret = queueTriggerLocked(trigger[i]);
3847
3848 if (ret != OK) {
3849 return ret;
3850 }
3851 }
3852
3853 return OK;
3854}
3855
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003856const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3857 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003858 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003859 if (d != nullptr) return d->mId;
3860 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003861}
3862
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003863status_t Camera3Device::RequestThread::queueTriggerLocked(
3864 RequestTrigger trigger) {
3865
3866 uint32_t tag = trigger.metadataTag;
3867 ssize_t index = mTriggerMap.indexOfKey(tag);
3868
3869 switch (trigger.getTagType()) {
3870 case TYPE_BYTE:
3871 // fall-through
3872 case TYPE_INT32:
3873 break;
3874 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003875 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3876 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003877 return INVALID_OPERATION;
3878 }
3879
3880 /**
3881 * Collect only the latest trigger, since we only have 1 field
3882 * in the request settings per trigger tag, and can't send more than 1
3883 * trigger per request.
3884 */
3885 if (index != NAME_NOT_FOUND) {
3886 mTriggerMap.editValueAt(index) = trigger;
3887 } else {
3888 mTriggerMap.add(tag, trigger);
3889 }
3890
3891 return OK;
3892}
3893
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003894status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003895 const RequestList &requests,
3896 /*out*/
3897 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003898 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003899 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003900 if (lastFrameNumber != NULL) {
3901 *lastFrameNumber = mRepeatingLastFrameNumber;
3902 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003903 mRepeatingRequests.clear();
3904 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3905 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003906
3907 unpauseForNewRequests();
3908
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003909 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003910 return OK;
3911}
3912
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003913bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003914 if (mRepeatingRequests.empty()) {
3915 return false;
3916 }
3917 int32_t requestId = requestIn->mResultExtras.requestId;
3918 const RequestList &repeatRequests = mRepeatingRequests;
3919 // All repeating requests are guaranteed to have same id so only check first quest
3920 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3921 return (firstRequest->mResultExtras.requestId == requestId);
3922}
3923
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003924status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003925 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003926 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003927 return clearRepeatingRequestsLocked(lastFrameNumber);
3928
3929}
3930
3931status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003932 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003933 if (lastFrameNumber != NULL) {
3934 *lastFrameNumber = mRepeatingLastFrameNumber;
3935 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003936 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003937 return OK;
3938}
3939
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003940status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003941 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003942 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003943 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003944 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003945
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003946 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003947
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003948 // Send errors for all requests pending in the request queue, including
3949 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003950 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003951 if (listener != NULL) {
3952 for (RequestList::iterator it = mRequestQueue.begin();
3953 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003954 // Abort the input buffers for reprocess requests.
3955 if ((*it)->mInputStream != NULL) {
3956 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003957 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3958 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003959 if (res != OK) {
3960 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3961 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3962 } else {
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07003963 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003964 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3965 if (res != OK) {
3966 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3967 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3968 }
3969 }
3970 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003971 // Set the frame number this request would have had, if it
3972 // had been submitted; this frame number will not be reused.
3973 // The requestId and burstId fields were set when the request was
3974 // submitted originally (in convertMetadataListToRequestListLocked)
3975 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003976 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003977 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003978 }
3979 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003980 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003981
3982 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003983 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003984 if (lastFrameNumber != NULL) {
3985 *lastFrameNumber = mRepeatingLastFrameNumber;
3986 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003987 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003988 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003989 return OK;
3990}
3991
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003992status_t Camera3Device::RequestThread::flush() {
3993 ATRACE_CALL();
3994 Mutex::Autolock l(mFlushLock);
3995
Emilian Peev08dd2452017-04-06 16:55:14 +01003996 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003997}
3998
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003999void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004000 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004001 Mutex::Autolock l(mPauseLock);
4002 mDoPause = paused;
4003 mDoPauseSignal.signal();
4004}
4005
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004006status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4007 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004008 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004009 Mutex::Autolock l(mLatestRequestMutex);
4010 status_t res;
4011 while (mLatestRequestId != requestId) {
4012 nsecs_t startTime = systemTime();
4013
4014 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4015 if (res != OK) return res;
4016
4017 timeout -= (systemTime() - startTime);
4018 }
4019
4020 return OK;
4021}
4022
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004023void Camera3Device::RequestThread::requestExit() {
4024 // Call parent to set up shutdown
4025 Thread::requestExit();
4026 // The exit from any possible waits
4027 mDoPauseSignal.signal();
4028 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004029
4030 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4031 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004032}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004033
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004034void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004035 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004036 bool surfaceAbandoned = false;
4037 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004038 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004039 {
4040 Mutex::Autolock l(mRequestLock);
4041 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4042 // repeating requests.
4043 for (const auto& request : mRepeatingRequests) {
4044 for (const auto& s : request->mOutputStreams) {
4045 if (s->isAbandoned()) {
4046 surfaceAbandoned = true;
4047 clearRepeatingRequestsLocked(&lastFrameNumber);
4048 break;
4049 }
4050 }
4051 if (surfaceAbandoned) {
4052 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004053 }
4054 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004055 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004056 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004057
4058 if (listener != NULL && surfaceAbandoned) {
4059 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004060 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004061}
4062
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004063bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004064 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004065 status_t res;
4066 size_t batchSize = mNextRequests.size();
4067 std::vector<camera3_capture_request_t*> requests(batchSize);
4068 uint32_t numRequestProcessed = 0;
4069 for (size_t i = 0; i < batchSize; i++) {
4070 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004071 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004072 }
4073
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004074 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4075
4076 bool triggerRemoveFailed = false;
4077 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4078 for (size_t i = 0; i < numRequestProcessed; i++) {
4079 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4080 nextRequest.submitted = true;
4081
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004082 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004083
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004084 if (!triggerRemoveFailed) {
4085 // Remove any previously queued triggers (after unlock)
4086 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4087 if (removeTriggerRes != OK) {
4088 triggerRemoveFailed = true;
4089 triggerFailedRequest = nextRequest;
4090 }
4091 }
4092 }
4093
4094 if (triggerRemoveFailed) {
4095 SET_ERR("RequestThread: Unable to remove triggers "
4096 "(capture request %d, HAL device: %s (%d)",
4097 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4098 cleanUpFailedRequests(/*sendRequestError*/ false);
4099 return false;
4100 }
4101
4102 if (res != OK) {
4103 // Should only get a failure here for malformed requests or device-level
4104 // errors, so consider all errors fatal. Bad metadata failures should
4105 // come through notify.
4106 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4107 mNextRequests[numRequestProcessed].halRequest.frame_number,
4108 strerror(-res), res);
4109 cleanUpFailedRequests(/*sendRequestError*/ false);
4110 return false;
4111 }
4112 return true;
4113}
4114
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004115nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4116 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4117 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4118 find_camera_metadata_ro_entry(request,
4119 ANDROID_CONTROL_AE_MODE,
4120 &e);
4121 if (e.count == 0) return maxExpectedDuration;
4122
4123 switch (e.data.u8[0]) {
4124 case ANDROID_CONTROL_AE_MODE_OFF:
4125 find_camera_metadata_ro_entry(request,
4126 ANDROID_SENSOR_EXPOSURE_TIME,
4127 &e);
4128 if (e.count > 0) {
4129 maxExpectedDuration = e.data.i64[0];
4130 }
4131 find_camera_metadata_ro_entry(request,
4132 ANDROID_SENSOR_FRAME_DURATION,
4133 &e);
4134 if (e.count > 0) {
4135 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4136 }
4137 break;
4138 default:
4139 find_camera_metadata_ro_entry(request,
4140 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4141 &e);
4142 if (e.count > 1) {
4143 maxExpectedDuration = 1e9 / e.data.u8[0];
4144 }
4145 break;
4146 }
4147
4148 return maxExpectedDuration;
4149}
4150
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004151bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4152 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4153 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4154 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4155 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4156 return true;
4157 }
4158
4159 return false;
4160}
4161
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004162void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4163 // Update the latest request sent to HAL
4164 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4165 Mutex::Autolock al(mLatestRequestMutex);
4166
4167 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4168 mLatestRequest.acquire(cloned);
4169
4170 mLatestPhysicalRequest.clear();
4171 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
4172 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
4173 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
4174 CameraMetadata(cloned));
4175 }
4176
4177 sp<Camera3Device> parent = mParent.promote();
4178 if (parent != NULL) {
4179 parent->monitorMetadata(TagMonitor::REQUEST,
4180 nextRequest.halRequest.frame_number,
4181 0, mLatestRequest, mLatestPhysicalRequest);
4182 }
4183 }
4184
4185 if (nextRequest.halRequest.settings != NULL) {
4186 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4187 nextRequest.halRequest.settings);
4188 }
4189
4190 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4191}
4192
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004193bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4194 ATRACE_CALL();
4195 bool updatesDetected = false;
4196
Emilian Peev4ec17882019-01-24 17:16:58 -08004197 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004198 for (auto tag : mSessionParamKeys) {
4199 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004200 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004201
4202 if (entry.count > 0) {
4203 bool isDifferent = false;
4204 if (lastEntry.count > 0) {
4205 // Have a last value, compare to see if changed
4206 if (lastEntry.type == entry.type &&
4207 lastEntry.count == entry.count) {
4208 // Same type and count, compare values
4209 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4210 size_t entryBytes = bytesPerValue * lastEntry.count;
4211 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4212 if (cmp != 0) {
4213 isDifferent = true;
4214 }
4215 } else {
4216 // Count or type has changed
4217 isDifferent = true;
4218 }
4219 } else {
4220 // No last entry, so always consider to be different
4221 isDifferent = true;
4222 }
4223
4224 if (isDifferent) {
4225 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004226 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4227 updatesDetected = true;
4228 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004229 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004230 }
4231 } else if (lastEntry.count > 0) {
4232 // Value has been removed
4233 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004234 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004235 updatesDetected = true;
4236 }
4237 }
4238
Emilian Peev4ec17882019-01-24 17:16:58 -08004239 bool reconfigureRequired;
4240 if (updatesDetected) {
4241 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4242 updatedParams);
4243 mLatestSessionParams = updatedParams;
4244 } else {
4245 reconfigureRequired = false;
4246 }
4247
4248 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004249}
4250
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004251bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004252 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004253 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004254 // Any function called from threadLoop() must not hold mInterfaceLock since
4255 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4256 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004257
4258 // Handle paused state.
4259 if (waitIfPaused()) {
4260 return true;
4261 }
4262
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004263 // Wait for the next batch of requests.
4264 waitForNextRequestBatch();
4265 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004266 return true;
4267 }
4268
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004269 // Get the latest request ID, if any
4270 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004271 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004272 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004273 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004274 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004275 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004276 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4277 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004278 }
4279
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004280 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4281 // or a single request from streaming or burst. In either case the first element
4282 // should contain the latest camera settings that we need to check for any session
4283 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004284 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004285 res = OK;
4286
4287 //Input stream buffers are already acquired at this point so an input stream
4288 //will not be able to move to idle state unless we force it.
4289 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4290 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4291 if (res != OK) {
4292 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4293 cleanUpFailedRequests(/*sendRequestError*/ false);
4294 return false;
4295 }
4296 }
4297
4298 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004299 sp<Camera3Device> parent = mParent.promote();
4300 if (parent != nullptr) {
4301 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004302 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004303 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004304
4305 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4306 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4307 if (res != OK) {
4308 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4309 cleanUpFailedRequests(/*sendRequestError*/ false);
4310 return false;
4311 }
4312 }
4313 }
4314 }
4315
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004316 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004317 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004318 if (res == TIMED_OUT) {
4319 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004320 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004321 // Check if any stream is abandoned.
4322 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004323 return true;
4324 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004325 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004326 return false;
4327 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004328
Zhijun Hecc27e112013-10-03 16:12:43 -07004329 // Inform waitUntilRequestProcessed thread of a new request ID
4330 {
4331 Mutex::Autolock al(mLatestRequestMutex);
4332
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004333 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004334 mLatestRequestSignal.signal();
4335 }
4336
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004337 // Submit a batch of requests to HAL.
4338 // Use flush lock only when submitting multilple requests in a batch.
4339 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4340 // which may take a long time to finish so synchronizing flush() and
4341 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4342 // For now, only synchronize for high speed recording and we should figure something out for
4343 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004344 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004345
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004346 if (useFlushLock) {
4347 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004348 }
4349
Zhijun Hef0645c12016-08-02 00:58:11 -07004350 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004351 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004352
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004353 sp<Camera3Device> parent = mParent.promote();
4354 if (parent != nullptr) {
4355 parent->mRequestBufferSM.onSubmittingRequest();
4356 }
4357
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004358 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004359 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004360 submitRequestSuccess = sendRequestsBatch();
4361
Shuzhen Wang686f6442017-06-20 16:16:04 -07004362 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4363 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004364
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004365 if (useFlushLock) {
4366 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004367 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004368
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004369 // Unset as current request
4370 {
4371 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004372 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004373 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004374 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004375
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004376 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004377}
4378
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004379status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004380 ATRACE_CALL();
4381
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004382 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004383 for (size_t i = 0; i < mNextRequests.size(); i++) {
4384 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004385 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4386 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4387 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4388
4389 // Prepare a request to HAL
4390 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4391
4392 // Insert any queued triggers (before metadata is locked)
4393 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004394 if (res < 0) {
4395 SET_ERR("RequestThread: Unable to insert triggers "
4396 "(capture request %d, HAL device: %s (%d)",
4397 halRequest->frame_number, strerror(-res), res);
4398 return INVALID_OPERATION;
4399 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004400
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004401 int triggerCount = res;
4402 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4403 mPrevTriggers = triggerCount;
4404
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004405 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
4406
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004407 // If the request is the same as last, or we had triggers last time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004408 bool newRequest =
4409 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004410 // Request settings are all the same within one batch, so only treat the first
4411 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004412 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004413 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004414 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004415 /**
4416 * HAL workaround:
4417 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4418 */
4419 res = addDummyTriggerIds(captureRequest);
4420 if (res != OK) {
4421 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4422 "(capture request %d, HAL device: %s (%d)",
4423 halRequest->frame_number, strerror(-res), res);
4424 return INVALID_OPERATION;
4425 }
4426
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004427 {
4428 // Correct metadata regions for distortion correction if enabled
4429 sp<Camera3Device> parent = mParent.promote();
4430 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004431 List<PhysicalCameraSettings>::iterator it;
4432 for (it = captureRequest->mSettingsList.begin();
4433 it != captureRequest->mSettingsList.end(); it++) {
4434 if (parent->mDistortionMappers.find(it->cameraId) ==
4435 parent->mDistortionMappers.end()) {
4436 continue;
4437 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004438
4439 if (!captureRequest->mDistortionCorrectionUpdated) {
4440 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4441 &(it->metadata));
4442 if (res != OK) {
4443 SET_ERR("RequestThread: Unable to correct capture requests "
4444 "for lens distortion for request %d: %s (%d)",
4445 halRequest->frame_number, strerror(-res), res);
4446 return INVALID_OPERATION;
4447 }
4448 captureRequest->mDistortionCorrectionUpdated = true;
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004449 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004450 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004451
4452 for (it = captureRequest->mSettingsList.begin();
4453 it != captureRequest->mSettingsList.end(); it++) {
4454 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4455 parent->mZoomRatioMappers.end()) {
4456 continue;
4457 }
4458
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004459 if (!captureRequest->mZoomRatioIs1x) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004460 cameraIdsWithZoom.insert(it->cameraId);
4461 }
4462
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004463 if (!captureRequest->mZoomRatioUpdated) {
4464 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4465 &(it->metadata));
4466 if (res != OK) {
4467 SET_ERR("RequestThread: Unable to correct capture requests "
4468 "for zoom ratio for request %d: %s (%d)",
4469 halRequest->frame_number, strerror(-res), res);
4470 return INVALID_OPERATION;
4471 }
4472 captureRequest->mZoomRatioUpdated = true;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004473 }
4474 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004475 if (captureRequest->mRotateAndCropAuto &&
4476 !captureRequest->mRotationAndCropUpdated) {
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004477 for (it = captureRequest->mSettingsList.begin();
4478 it != captureRequest->mSettingsList.end(); it++) {
4479 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4480 if (mapper != parent->mRotateAndCropMappers.end()) {
4481 res = mapper->second.updateCaptureRequest(&(it->metadata));
4482 if (res != OK) {
4483 SET_ERR("RequestThread: Unable to correct capture requests "
4484 "for rotate-and-crop for request %d: %s (%d)",
4485 halRequest->frame_number, strerror(-res), res);
4486 return INVALID_OPERATION;
4487 }
4488 }
4489 }
Shuzhen Wangd1d051a2020-08-20 15:42:23 -07004490 captureRequest->mRotationAndCropUpdated = true;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004491 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004492 }
4493 }
4494
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004495 /**
4496 * The request should be presorted so accesses in HAL
4497 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4498 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004499 captureRequest->mSettingsList.begin()->metadata.sort();
4500 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004501 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004502 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004503 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4504
4505 IF_ALOGV() {
4506 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4507 find_camera_metadata_ro_entry(
4508 halRequest->settings,
4509 ANDROID_CONTROL_AF_TRIGGER,
4510 &e
4511 );
4512 if (e.count > 0) {
4513 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4514 __FUNCTION__,
4515 halRequest->frame_number,
4516 e.data.u8[0]);
4517 }
4518 }
4519 } else {
4520 // leave request.settings NULL to indicate 'reuse latest given'
4521 ALOGVV("%s: Request settings are REUSED",
4522 __FUNCTION__);
4523 }
4524
Emilian Peevaebbe412018-01-15 13:53:24 +00004525 if (captureRequest->mSettingsList.size() > 1) {
4526 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4527 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004528 if (newRequest) {
4529 halRequest->physcam_settings =
4530 new const camera_metadata* [halRequest->num_physcam_settings];
4531 } else {
4532 halRequest->physcam_settings = nullptr;
4533 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004534 auto it = ++captureRequest->mSettingsList.begin();
4535 size_t i = 0;
4536 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4537 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004538 if (newRequest) {
4539 it->metadata.sort();
4540 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4541 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004542 }
4543 }
4544
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004545 uint32_t totalNumBuffers = 0;
4546
4547 // Fill in buffers
4548 if (captureRequest->mInputStream != NULL) {
4549 halRequest->input_buffer = &captureRequest->mInputBuffer;
4550 totalNumBuffers += 1;
4551 } else {
4552 halRequest->input_buffer = NULL;
4553 }
4554
4555 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4556 captureRequest->mOutputStreams.size());
4557 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004558 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004559
4560 sp<Camera3Device> parent = mParent.promote();
4561 if (parent == NULL) {
4562 // Should not happen, and nowhere to send errors to, so just log it
4563 CLOGE("RequestThread: Parent is gone");
4564 return INVALID_OPERATION;
4565 }
4566 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4567
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004568 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004569 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004570 sp<Camera3OutputStreamInterface> outputStream =
4571 captureRequest->mOutputStreams.editItemAt(j);
4572 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004573
4574 // Prepare video buffers for high speed recording on the first video request.
4575 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4576 // Only try to prepare video stream on the first video request.
4577 mPrepareVideoStream = false;
4578
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004579 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4580 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004581 while (res == NOT_ENOUGH_DATA) {
4582 res = outputStream->prepareNextBuffer();
4583 }
4584 if (res != OK) {
4585 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4586 __FUNCTION__, strerror(-res), res);
4587 outputStream->cancelPrepare();
4588 }
4589 }
4590
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004591 std::vector<size_t> uniqueSurfaceIds;
4592 res = outputStream->getUniqueSurfaceIds(
4593 captureRequest->mOutputSurfaces[streamId],
4594 &uniqueSurfaceIds);
4595 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4596 if (res != OK && res != INVALID_OPERATION) {
4597 ALOGE("%s: failed to query stream %d unique surface IDs",
4598 __FUNCTION__, streamId);
4599 return res;
4600 }
4601 if (res == OK) {
4602 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4603 }
4604
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004605 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004606 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004607 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004608 return TIMED_OUT;
4609 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004610 // HAL will request buffer through requestStreamBuffer API
4611 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
4612 buffer.stream = outputStream->asHalStream();
4613 buffer.buffer = nullptr;
4614 buffer.status = CAMERA3_BUFFER_STATUS_OK;
4615 buffer.acquire_fence = -1;
4616 buffer.release_fence = -1;
4617 } else {
4618 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4619 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004620 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004621 if (res != OK) {
4622 // Can't get output buffer from gralloc queue - this could be due to
4623 // abandoned queue or other consumer misbehavior, so not a fatal
4624 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004625 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004626 " %s (%d)", strerror(-res), res);
4627
4628 return TIMED_OUT;
4629 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004630 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004631
4632 {
4633 sp<Camera3Device> parent = mParent.promote();
4634 if (parent != nullptr) {
4635 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4636 for (const auto& settings : captureRequest->mSettingsList) {
4637 if ((streamCameraId.isEmpty() &&
4638 parent->getId() == settings.cameraId.c_str()) ||
4639 streamCameraId == settings.cameraId.c_str()) {
4640 outputStream->fireBufferRequestForFrameNumber(
4641 captureRequest->mResultExtras.frameNumber,
4642 settings.metadata);
4643 }
4644 }
4645 }
4646 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004647
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004648 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4649
4650 if (!physicalCameraId.isEmpty()) {
4651 // Physical stream isn't supported for input request.
4652 if (halRequest->input_buffer) {
4653 CLOGE("Physical stream is not supported for input request");
4654 return INVALID_OPERATION;
4655 }
4656 requestedPhysicalCameras.insert(physicalCameraId);
4657 }
4658 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004659 }
4660 totalNumBuffers += halRequest->num_output_buffers;
4661
4662 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004663 // If this request list is for constrained high speed recording (not
4664 // preview), and the current request is not the last one in the batch,
4665 // do not send callback to the app.
4666 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004667 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004668 hasCallback = false;
4669 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004670 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004671 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01004672 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4673 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4674 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4675 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4676 isStillCapture = true;
4677 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4678 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004679
4680 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
4681 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4682 isZslCapture = true;
4683 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004684 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004685 res = parent->registerInFlight(halRequest->frame_number,
4686 totalNumBuffers, captureRequest->mResultExtras,
4687 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004688 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004689 calculateMaxExpectedDuration(halRequest->settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004690 requestedPhysicalCameras, isStillCapture, isZslCapture,
4691 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004692 (mUseHalBufManager) ? uniqueSurfaceIdMap :
4693 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004694 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4695 ", burstId = %" PRId32 ".",
4696 __FUNCTION__,
4697 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4698 captureRequest->mResultExtras.burstId);
4699 if (res != OK) {
4700 SET_ERR("RequestThread: Unable to register new in-flight request:"
4701 " %s (%d)", strerror(-res), res);
4702 return INVALID_OPERATION;
4703 }
4704 }
4705
4706 return OK;
4707}
4708
Igor Murashkin1e479c02013-09-06 16:55:14 -07004709CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004710 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004711 Mutex::Autolock al(mLatestRequestMutex);
4712
4713 ALOGV("RequestThread::%s", __FUNCTION__);
4714
4715 return mLatestRequest;
4716}
4717
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004718bool Camera3Device::RequestThread::isStreamPending(
4719 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004720 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004721 Mutex::Autolock l(mRequestLock);
4722
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004723 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004724 if (!nextRequest.submitted) {
4725 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4726 if (stream == s) return true;
4727 }
4728 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004729 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004730 }
4731
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004732 for (const auto& request : mRequestQueue) {
4733 for (const auto& s : request->mOutputStreams) {
4734 if (stream == s) return true;
4735 }
4736 if (stream == request->mInputStream) return true;
4737 }
4738
4739 for (const auto& request : mRepeatingRequests) {
4740 for (const auto& s : request->mOutputStreams) {
4741 if (stream == s) return true;
4742 }
4743 if (stream == request->mInputStream) return true;
4744 }
4745
4746 return false;
4747}
Jianing Weicb0652e2014-03-12 18:29:36 -07004748
Emilian Peev40ead602017-09-26 15:46:36 +01004749bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4750 ATRACE_CALL();
4751 Mutex::Autolock l(mRequestLock);
4752
4753 for (const auto& nextRequest : mNextRequests) {
4754 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4755 if (s.first == streamId) {
4756 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4757 if (it != s.second.end()) {
4758 return true;
4759 }
4760 }
4761 }
4762 }
4763
4764 for (const auto& request : mRequestQueue) {
4765 for (const auto& s : request->mOutputSurfaces) {
4766 if (s.first == streamId) {
4767 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4768 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004769 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004770 }
4771 }
4772 }
4773 }
4774
4775 for (const auto& request : mRepeatingRequests) {
4776 for (const auto& s : request->mOutputSurfaces) {
4777 if (s.first == streamId) {
4778 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4779 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004780 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004781 }
4782 }
4783 }
4784 }
4785
4786 return false;
4787}
4788
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004789void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4790 if (!mUseHalBufManager) {
4791 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4792 return;
4793 }
4794
4795 Mutex::Autolock pl(mPauseLock);
4796 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004797 mInterface->signalPipelineDrain(streamIds);
4798 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004799 }
4800 // If request thread is still busy, wait until paused then notify HAL
4801 mNotifyPipelineDrain = true;
4802 mStreamIdsToBeDrained = streamIds;
4803}
4804
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004805void Camera3Device::RequestThread::clearPreviousRequest() {
4806 Mutex::Autolock l(mRequestLock);
4807 mPrevRequest.clear();
4808}
4809
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004810status_t Camera3Device::RequestThread::switchToOffline(
4811 const std::vector<int32_t>& streamsToKeep,
4812 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004813 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4814 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004815 Mutex::Autolock l(mRequestLock);
4816 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
4817
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004818 // Wait until request thread is fully stopped
4819 // TBD: check if request thread is being paused by other APIs (shouldn't be)
4820
4821 // We could also check for mRepeatingRequests.empty(), but the API interface
4822 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
4823 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004824 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4825 while (!queueEmpty) {
4826 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
4827 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004828 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004829 return res;
4830 } else if (res != OK) {
4831 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
4832 __FUNCTION__, strerror(-res), res);
4833 return res;
4834 }
4835 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4836 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004837
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004838 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004839 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004840}
4841
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004842status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4843 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4844 ATRACE_CALL();
4845 Mutex::Autolock l(mTriggerMutex);
4846 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4847 return BAD_VALUE;
4848 }
4849 mRotateAndCropOverride = rotateAndCropValue;
4850 return OK;
4851}
4852
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004853nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004854 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004855 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004856 return mExpectedInflightDuration > kMinInflightDuration ?
4857 mExpectedInflightDuration : kMinInflightDuration;
4858}
4859
Emilian Peevaebbe412018-01-15 13:53:24 +00004860void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4861 camera3_capture_request_t *halRequest) {
4862 if ((request == nullptr) || (halRequest == nullptr)) {
4863 ALOGE("%s: Invalid request!", __FUNCTION__);
4864 return;
4865 }
4866
4867 if (halRequest->num_physcam_settings > 0) {
4868 if (halRequest->physcam_id != nullptr) {
4869 delete [] halRequest->physcam_id;
4870 halRequest->physcam_id = nullptr;
4871 }
4872 if (halRequest->physcam_settings != nullptr) {
4873 auto it = ++(request->mSettingsList.begin());
4874 size_t i = 0;
4875 for (; it != request->mSettingsList.end(); it++, i++) {
4876 it->metadata.unlock(halRequest->physcam_settings[i]);
4877 }
4878 delete [] halRequest->physcam_settings;
4879 halRequest->physcam_settings = nullptr;
4880 }
4881 }
4882}
4883
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004884void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4885 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004886 return;
4887 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004888
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004889 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004890 // Skip the ones that have been submitted successfully.
4891 if (nextRequest.submitted) {
4892 continue;
4893 }
4894
4895 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4896 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4897 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4898
4899 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004900 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004901 }
4902
Emilian Peevaebbe412018-01-15 13:53:24 +00004903 cleanupPhysicalSettings(captureRequest, halRequest);
4904
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004905 if (captureRequest->mInputStream != NULL) {
4906 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4907 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4908 }
4909
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004910 // No output buffer can be returned when using HAL buffer manager
4911 if (!mUseHalBufManager) {
4912 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4913 //Buffers that failed processing could still have
4914 //valid acquire fence.
4915 int acquireFence = (*outputBuffers)[i].acquire_fence;
4916 if (0 <= acquireFence) {
4917 close(acquireFence);
4918 outputBuffers->editItemAt(i).acquire_fence = -1;
4919 }
4920 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4921 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
4922 /*timestampIncreasing*/true, std::vector<size_t> (),
4923 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004924 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004925 }
4926
4927 if (sendRequestError) {
4928 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004929 sp<NotificationListener> listener = mListener.promote();
4930 if (listener != NULL) {
4931 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004932 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004933 captureRequest->mResultExtras);
4934 }
4935 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004936
4937 // Remove yet-to-be submitted inflight request from inflightMap
4938 {
4939 sp<Camera3Device> parent = mParent.promote();
4940 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004941 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004942 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4943 if (idx >= 0) {
4944 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4945 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4946 parent->removeInFlightMapEntryLocked(idx);
4947 }
4948 }
4949 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004950 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004951
4952 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004953 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004954}
4955
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004956void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004957 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004958 // Optimized a bit for the simple steady-state case (single repeating
4959 // request), to avoid putting that request in the queue temporarily.
4960 Mutex::Autolock l(mRequestLock);
4961
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004962 assert(mNextRequests.empty());
4963
4964 NextRequest nextRequest;
4965 nextRequest.captureRequest = waitForNextRequestLocked();
4966 if (nextRequest.captureRequest == nullptr) {
4967 return;
4968 }
4969
4970 nextRequest.halRequest = camera3_capture_request_t();
4971 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004972 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004973
4974 // Wait for additional requests
4975 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4976
4977 for (size_t i = 1; i < batchSize; i++) {
4978 NextRequest additionalRequest;
4979 additionalRequest.captureRequest = waitForNextRequestLocked();
4980 if (additionalRequest.captureRequest == nullptr) {
4981 break;
4982 }
4983
4984 additionalRequest.halRequest = camera3_capture_request_t();
4985 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004986 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004987 }
4988
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004989 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004990 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004991 mNextRequests.size(), batchSize);
4992 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004993 }
4994
4995 return;
4996}
4997
4998sp<Camera3Device::CaptureRequest>
4999 Camera3Device::RequestThread::waitForNextRequestLocked() {
5000 status_t res;
5001 sp<CaptureRequest> nextRequest;
5002
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005003 while (mRequestQueue.empty()) {
5004 if (!mRepeatingRequests.empty()) {
5005 // Always atomically enqueue all requests in a repeating request
5006 // list. Guarantees a complete in-sequence set of captures to
5007 // application.
5008 const RequestList &requests = mRepeatingRequests;
5009 RequestList::const_iterator firstRequest =
5010 requests.begin();
5011 nextRequest = *firstRequest;
5012 mRequestQueue.insert(mRequestQueue.end(),
5013 ++firstRequest,
5014 requests.end());
5015 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005016
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005017 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005018
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005019 break;
5020 }
5021
5022 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5023
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005024 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5025 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005026 Mutex::Autolock pl(mPauseLock);
5027 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005028 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005029 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005030 if (mNotifyPipelineDrain) {
5031 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5032 mNotifyPipelineDrain = false;
5033 mStreamIdsToBeDrained.clear();
5034 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005035 // Let the tracker know
5036 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5037 if (statusTracker != 0) {
5038 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5039 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005040 sp<Camera3Device> parent = mParent.promote();
5041 if (parent != nullptr) {
5042 parent->mRequestBufferSM.onRequestThreadPaused();
5043 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005044 }
5045 // Stop waiting for now and let thread management happen
5046 return NULL;
5047 }
5048 }
5049
5050 if (nextRequest == NULL) {
5051 // Don't have a repeating request already in hand, so queue
5052 // must have an entry now.
5053 RequestList::iterator firstRequest =
5054 mRequestQueue.begin();
5055 nextRequest = *firstRequest;
5056 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005057 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5058 sp<NotificationListener> listener = mListener.promote();
5059 if (listener != NULL) {
5060 listener->notifyRequestQueueEmpty();
5061 }
5062 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005063 }
5064
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005065 // In case we've been unpaused by setPaused clearing mDoPause, need to
5066 // update internal pause state (capture/setRepeatingRequest unpause
5067 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005068 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005069 if (mPaused) {
5070 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5071 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5072 if (statusTracker != 0) {
5073 statusTracker->markComponentActive(mStatusId);
5074 }
5075 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005076 mPaused = false;
5077
5078 // Check if we've reconfigured since last time, and reset the preview
5079 // request if so. Can't use 'NULL request == repeat' across configure calls.
5080 if (mReconfigured) {
5081 mPrevRequest.clear();
5082 mReconfigured = false;
5083 }
5084
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005085 if (nextRequest != NULL) {
5086 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005087 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5088 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005089
5090 // Since RequestThread::clear() removes buffers from the input stream,
5091 // get the right buffer here before unlocking mRequestLock
5092 if (nextRequest->mInputStream != NULL) {
5093 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5094 if (res != OK) {
5095 // Can't get input buffer from gralloc queue - this could be due to
5096 // disconnected queue or other producer misbehavior, so not a fatal
5097 // error
5098 ALOGE("%s: Can't get input buffer, skipping request:"
5099 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005100
5101 sp<NotificationListener> listener = mListener.promote();
5102 if (listener != NULL) {
5103 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005104 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005105 nextRequest->mResultExtras);
5106 }
5107 return NULL;
5108 }
5109 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005110 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005111
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005112 return nextRequest;
5113}
5114
5115bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005116 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005117 status_t res;
5118 Mutex::Autolock l(mPauseLock);
5119 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005120 if (mPaused == false) {
5121 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005122 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005123 if (mNotifyPipelineDrain) {
5124 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5125 mNotifyPipelineDrain = false;
5126 mStreamIdsToBeDrained.clear();
5127 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005128 // Let the tracker know
5129 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5130 if (statusTracker != 0) {
5131 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5132 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005133 sp<Camera3Device> parent = mParent.promote();
5134 if (parent != nullptr) {
5135 parent->mRequestBufferSM.onRequestThreadPaused();
5136 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005137 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005138
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005139 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005140 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005141 return true;
5142 }
5143 }
5144 // We don't set mPaused to false here, because waitForNextRequest needs
5145 // to further manage the paused state in case of starvation.
5146 return false;
5147}
5148
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005149void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005150 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005151 // With work to do, mark thread as unpaused.
5152 // If paused by request (setPaused), don't resume, to avoid
5153 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005154 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005155 Mutex::Autolock p(mPauseLock);
5156 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005157 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5158 if (mPaused) {
5159 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5160 if (statusTracker != 0) {
5161 statusTracker->markComponentActive(mStatusId);
5162 }
5163 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005164 mPaused = false;
5165 }
5166}
5167
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005168void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5169 sp<Camera3Device> parent = mParent.promote();
5170 if (parent != NULL) {
5171 va_list args;
5172 va_start(args, fmt);
5173
5174 parent->setErrorStateV(fmt, args);
5175
5176 va_end(args);
5177 }
5178}
5179
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005180status_t Camera3Device::RequestThread::insertTriggers(
5181 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005182 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005183 Mutex::Autolock al(mTriggerMutex);
5184
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005185 sp<Camera3Device> parent = mParent.promote();
5186 if (parent == NULL) {
5187 CLOGE("RequestThread: Parent is gone");
5188 return DEAD_OBJECT;
5189 }
5190
Emilian Peevaebbe412018-01-15 13:53:24 +00005191 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005192 size_t count = mTriggerMap.size();
5193
5194 for (size_t i = 0; i < count; ++i) {
5195 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005196 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005197
5198 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5199 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5200 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005201 if (isAeTrigger) {
5202 request->mResultExtras.precaptureTriggerId = triggerId;
5203 mCurrentPreCaptureTriggerId = triggerId;
5204 } else {
5205 request->mResultExtras.afTriggerId = triggerId;
5206 mCurrentAfTriggerId = triggerId;
5207 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005208 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005209 }
5210
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005211 camera_metadata_entry entry = metadata.find(tag);
5212
5213 if (entry.count > 0) {
5214 /**
5215 * Already has an entry for this trigger in the request.
5216 * Rewrite it with our requested trigger value.
5217 */
5218 RequestTrigger oldTrigger = trigger;
5219
5220 oldTrigger.entryValue = entry.data.u8[0];
5221
5222 mTriggerReplacedMap.add(tag, oldTrigger);
5223 } else {
5224 /**
5225 * More typical, no trigger entry, so we just add it
5226 */
5227 mTriggerRemovedMap.add(tag, trigger);
5228 }
5229
5230 status_t res;
5231
5232 switch (trigger.getTagType()) {
5233 case TYPE_BYTE: {
5234 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5235 res = metadata.update(tag,
5236 &entryValue,
5237 /*count*/1);
5238 break;
5239 }
5240 case TYPE_INT32:
5241 res = metadata.update(tag,
5242 &trigger.entryValue,
5243 /*count*/1);
5244 break;
5245 default:
5246 ALOGE("%s: Type not supported: 0x%x",
5247 __FUNCTION__,
5248 trigger.getTagType());
5249 return INVALID_OPERATION;
5250 }
5251
5252 if (res != OK) {
5253 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5254 ", value %d", __FUNCTION__, trigger.getTagName(),
5255 trigger.entryValue);
5256 return res;
5257 }
5258
5259 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5260 trigger.getTagName(),
5261 trigger.entryValue);
5262 }
5263
5264 mTriggerMap.clear();
5265
5266 return count;
5267}
5268
5269status_t Camera3Device::RequestThread::removeTriggers(
5270 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005271 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005272 Mutex::Autolock al(mTriggerMutex);
5273
Emilian Peevaebbe412018-01-15 13:53:24 +00005274 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005275
5276 /**
5277 * Replace all old entries with their old values.
5278 */
5279 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5280 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5281
5282 status_t res;
5283
5284 uint32_t tag = trigger.metadataTag;
5285 switch (trigger.getTagType()) {
5286 case TYPE_BYTE: {
5287 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5288 res = metadata.update(tag,
5289 &entryValue,
5290 /*count*/1);
5291 break;
5292 }
5293 case TYPE_INT32:
5294 res = metadata.update(tag,
5295 &trigger.entryValue,
5296 /*count*/1);
5297 break;
5298 default:
5299 ALOGE("%s: Type not supported: 0x%x",
5300 __FUNCTION__,
5301 trigger.getTagType());
5302 return INVALID_OPERATION;
5303 }
5304
5305 if (res != OK) {
5306 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5307 ", trigger value %d", __FUNCTION__,
5308 trigger.getTagName(), trigger.entryValue);
5309 return res;
5310 }
5311 }
5312 mTriggerReplacedMap.clear();
5313
5314 /**
5315 * Remove all new entries.
5316 */
5317 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5318 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5319 status_t res = metadata.erase(trigger.metadataTag);
5320
5321 if (res != OK) {
5322 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5323 ", trigger value %d", __FUNCTION__,
5324 trigger.getTagName(), trigger.entryValue);
5325 return res;
5326 }
5327 }
5328 mTriggerRemovedMap.clear();
5329
5330 return OK;
5331}
5332
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005333status_t Camera3Device::RequestThread::addDummyTriggerIds(
5334 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005335 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005336 static const int32_t dummyTriggerId = 1;
5337 status_t res;
5338
Emilian Peevaebbe412018-01-15 13:53:24 +00005339 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005340
5341 // If AF trigger is active, insert a dummy AF trigger ID if none already
5342 // exists
5343 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5344 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5345 if (afTrigger.count > 0 &&
5346 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5347 afId.count == 0) {
5348 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5349 if (res != OK) return res;
5350 }
5351
5352 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5353 // if none already exists
5354 camera_metadata_entry pcTrigger =
5355 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5356 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5357 if (pcTrigger.count > 0 &&
5358 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5359 pcId.count == 0) {
5360 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5361 &dummyTriggerId, 1);
5362 if (res != OK) return res;
5363 }
5364
5365 return OK;
5366}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005367
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005368bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5369 const sp<CaptureRequest> &request) {
5370 ATRACE_CALL();
5371
5372 if (request->mRotateAndCropAuto) {
5373 Mutex::Autolock l(mTriggerMutex);
5374 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5375
5376 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5377 if (rotateAndCropEntry.count > 0) {
5378 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5379 return false;
5380 } else {
5381 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5382 return true;
5383 }
5384 } else {
5385 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5386 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5387 &rotateAndCrop_u8, 1);
5388 return true;
5389 }
5390 }
5391 return false;
5392}
5393
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005394/**
5395 * PreparerThread inner class methods
5396 */
5397
5398Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005399 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005400 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005401}
5402
5403Camera3Device::PreparerThread::~PreparerThread() {
5404 Thread::requestExitAndWait();
5405 if (mCurrentStream != nullptr) {
5406 mCurrentStream->cancelPrepare();
5407 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5408 mCurrentStream.clear();
5409 }
5410 clear();
5411}
5412
Ruben Brunkc78ac262015-08-13 17:58:46 -07005413status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005414 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005415 status_t res;
5416
5417 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005418 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005419
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005420 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005421 if (res == OK) {
5422 // No preparation needed, fire listener right off
5423 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005424 if (listener != NULL) {
5425 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005426 }
5427 return OK;
5428 } else if (res != NOT_ENOUGH_DATA) {
5429 return res;
5430 }
5431
5432 // Need to prepare, start up thread if necessary
5433 if (!mActive) {
5434 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5435 // isn't running
5436 Thread::requestExitAndWait();
5437 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5438 if (res != OK) {
5439 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005440 if (listener != NULL) {
5441 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005442 }
5443 return res;
5444 }
5445 mCancelNow = false;
5446 mActive = true;
5447 ALOGV("%s: Preparer stream started", __FUNCTION__);
5448 }
5449
5450 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005451 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005452 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5453
5454 return OK;
5455}
5456
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005457void Camera3Device::PreparerThread::pause() {
5458 ATRACE_CALL();
5459
5460 Mutex::Autolock l(mLock);
5461
5462 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5463 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5464 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5465 int currentMaxCount = mCurrentMaxCount;
5466 mPendingStreams.clear();
5467 mCancelNow = true;
5468 while (mActive) {
5469 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5470 if (res == TIMED_OUT) {
5471 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5472 return;
5473 } else if (res != OK) {
5474 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5475 return;
5476 }
5477 }
5478
5479 //Check whether the prepare thread was able to complete the current
5480 //stream. In case work is still pending emplace it along with the rest
5481 //of the streams in the pending list.
5482 if (currentStream != nullptr) {
5483 if (!mCurrentPrepareComplete) {
5484 pendingStreams.emplace(currentMaxCount, currentStream);
5485 }
5486 }
5487
5488 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5489 for (const auto& it : mPendingStreams) {
5490 it.second->cancelPrepare();
5491 }
5492}
5493
5494status_t Camera3Device::PreparerThread::resume() {
5495 ATRACE_CALL();
5496 status_t res;
5497
5498 Mutex::Autolock l(mLock);
5499 sp<NotificationListener> listener = mListener.promote();
5500
5501 if (mActive) {
5502 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5503 return NO_INIT;
5504 }
5505
5506 auto it = mPendingStreams.begin();
5507 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005508 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005509 if (res == OK) {
5510 if (listener != NULL) {
5511 listener->notifyPrepared(it->second->getId());
5512 }
5513 it = mPendingStreams.erase(it);
5514 } else if (res != NOT_ENOUGH_DATA) {
5515 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5516 res, strerror(-res));
5517 it = mPendingStreams.erase(it);
5518 } else {
5519 it++;
5520 }
5521 }
5522
5523 if (mPendingStreams.empty()) {
5524 return OK;
5525 }
5526
5527 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5528 if (res != OK) {
5529 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5530 __FUNCTION__, res, strerror(-res));
5531 return res;
5532 }
5533 mCancelNow = false;
5534 mActive = true;
5535 ALOGV("%s: Preparer stream started", __FUNCTION__);
5536
5537 return OK;
5538}
5539
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005540status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005541 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005542 Mutex::Autolock l(mLock);
5543
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005544 for (const auto& it : mPendingStreams) {
5545 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005546 }
5547 mPendingStreams.clear();
5548 mCancelNow = true;
5549
5550 return OK;
5551}
5552
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005553void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
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 mListener = listener;
5557}
5558
5559bool Camera3Device::PreparerThread::threadLoop() {
5560 status_t res;
5561 {
5562 Mutex::Autolock l(mLock);
5563 if (mCurrentStream == nullptr) {
5564 // End thread if done with work
5565 if (mPendingStreams.empty()) {
5566 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5567 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5568 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5569 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005570 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005571 return false;
5572 }
5573
5574 // Get next stream to prepare
5575 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005576 mCurrentStream = it->second;
5577 mCurrentMaxCount = it->first;
5578 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005579 mPendingStreams.erase(it);
5580 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5581 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5582 } else if (mCancelNow) {
5583 mCurrentStream->cancelPrepare();
5584 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5585 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5586 mCurrentStream.clear();
5587 mCancelNow = false;
5588 return true;
5589 }
5590 }
5591
5592 res = mCurrentStream->prepareNextBuffer();
5593 if (res == NOT_ENOUGH_DATA) return true;
5594 if (res != OK) {
5595 // Something bad happened; try to recover by cancelling prepare and
5596 // signalling listener anyway
5597 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5598 mCurrentStream->getId(), res, strerror(-res));
5599 mCurrentStream->cancelPrepare();
5600 }
5601
5602 // This stream has finished, notify listener
5603 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005604 sp<NotificationListener> listener = mListener.promote();
5605 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005606 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5607 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005608 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005609 }
5610
5611 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5612 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005613 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005614
5615 return true;
5616}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005617
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005618status_t Camera3Device::RequestBufferStateMachine::initialize(
5619 sp<camera3::StatusTracker> statusTracker) {
5620 if (statusTracker == nullptr) {
5621 ALOGE("%s: statusTracker is null", __FUNCTION__);
5622 return BAD_VALUE;
5623 }
5624
5625 std::lock_guard<std::mutex> lock(mLock);
5626 mStatusTracker = statusTracker;
5627 mRequestBufferStatusId = statusTracker->addComponent();
5628 return OK;
5629}
5630
5631bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5632 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005633 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005634 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005635 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005636 return true;
5637 }
5638 return false;
5639}
5640
5641void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5642 std::lock_guard<std::mutex> lock(mLock);
5643 if (!mRequestBufferOngoing) {
5644 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5645 return;
5646 }
5647 mRequestBufferOngoing = false;
5648 if (mStatus == RB_STATUS_PENDING_STOP) {
5649 checkSwitchToStopLocked();
5650 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005651 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005652}
5653
5654void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5655 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005656 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005657 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005658 return;
5659}
5660
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005661void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005662 std::lock_guard<std::mutex> lock(mLock);
5663 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005664 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5665 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005666 mInflightMapEmpty = false;
5667 if (mStatus == RB_STATUS_STOPPED) {
5668 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005669 }
5670 return;
5671}
5672
5673void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5674 std::lock_guard<std::mutex> lock(mLock);
5675 mRequestThreadPaused = true;
5676 if (mStatus == RB_STATUS_PENDING_STOP) {
5677 checkSwitchToStopLocked();
5678 }
5679 return;
5680}
5681
5682void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5683 std::lock_guard<std::mutex> lock(mLock);
5684 mInflightMapEmpty = true;
5685 if (mStatus == RB_STATUS_PENDING_STOP) {
5686 checkSwitchToStopLocked();
5687 }
5688 return;
5689}
5690
5691void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5692 std::lock_guard<std::mutex> lock(mLock);
5693 if (!checkSwitchToStopLocked()) {
5694 mStatus = RB_STATUS_PENDING_STOP;
5695 }
5696 return;
5697}
5698
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005699bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5700 std::lock_guard<std::mutex> lock(mLock);
5701 if (mRequestBufferOngoing) {
5702 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5703 __FUNCTION__);
5704 return false;
5705 }
5706 mSwitchedToOffline = true;
5707 mInflightMapEmpty = true;
5708 mRequestThreadPaused = true;
5709 mStatus = RB_STATUS_STOPPED;
5710 return true;
5711}
5712
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005713void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5714 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5715 if (statusTracker != nullptr) {
5716 if (active) {
5717 statusTracker->markComponentActive(mRequestBufferStatusId);
5718 } else {
5719 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5720 }
5721 }
5722}
5723
5724bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5725 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5726 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005727 return true;
5728 }
5729 return false;
5730}
5731
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005732bool Camera3Device::startRequestBuffer() {
5733 return mRequestBufferSM.startRequestBuffer();
5734}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005735
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005736void Camera3Device::endRequestBuffer() {
5737 mRequestBufferSM.endRequestBuffer();
5738}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005739
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005740nsecs_t Camera3Device::getWaitDuration() {
5741 return kBaseGetBufferWait + getExpectedInFlightDuration();
5742}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005743
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005744void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5745 mInterface->getInflightBufferKeys(out);
5746}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005747
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005748void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5749 mInterface->getInflightRequestBufferKeys(out);
5750}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005751
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005752std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5753 std::vector<sp<Camera3StreamInterface>> ret;
5754 bool hasInputStream = mInputStream != nullptr;
5755 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5756 if (hasInputStream) {
5757 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005758 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005759 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5760 ret.push_back(mOutputStreams[i]);
5761 }
5762 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5763 ret.push_back(mDeletedStreams[i]);
5764 }
5765 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005766}
5767
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005768status_t Camera3Device::switchToOffline(
5769 const std::vector<int32_t>& streamsToKeep,
5770 /*out*/ sp<CameraOfflineSessionBase>* session) {
5771 ATRACE_CALL();
5772 if (session == nullptr) {
5773 ALOGE("%s: session must not be null", __FUNCTION__);
5774 return BAD_VALUE;
5775 }
5776
5777 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005778
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005779 bool hasInputStream = mInputStream != nullptr;
5780 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
5781 bool inputStreamSupportsOffline = hasInputStream ?
5782 mInputStream->getOfflineProcessingSupport() : false;
5783 auto outputStreamIds = mOutputStreams.getStreamIds();
5784 auto streamIds = outputStreamIds;
5785 if (hasInputStream) {
5786 streamIds.push_back(mInputStream->getId());
5787 }
5788
5789 // Check all streams in streamsToKeep supports offline mode
5790 for (auto id : streamsToKeep) {
5791 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5792 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
5793 return BAD_VALUE;
5794 } else if (id == inputStreamId) {
5795 if (!inputStreamSupportsOffline) {
5796 ALOGE("%s: input stream %d cannot be switched to offline",
5797 __FUNCTION__, id);
5798 return BAD_VALUE;
5799 }
5800 } else {
5801 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
5802 if (!stream->getOfflineProcessingSupport()) {
5803 ALOGE("%s: output stream %d cannot be switched to offline",
5804 __FUNCTION__, id);
5805 return BAD_VALUE;
5806 }
5807 }
5808 }
5809
5810 // TODO: block surface sharing and surface group streams until we can support them
5811
5812 // Stop repeating request, wait until all remaining requests are submitted, then call into
5813 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005814 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
5815 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005816 camera3::BufferRecords bufferRecords;
5817 status_t ret = mRequestThread->switchToOffline(
5818 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005819
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005820 if (ret != OK) {
5821 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
5822 return ret;
5823 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005824
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005825 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
5826 if (!succ) {
5827 SET_ERR("HAL must not be calling requestStreamBuffers call");
5828 // TODO: block ALL callbacks from HAL till app configured new streams?
5829 return UNKNOWN_ERROR;
5830 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005831
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005832 // Verify offlineSessionInfo
5833 std::vector<int32_t> offlineStreamIds;
5834 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
5835 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5836 // verify stream IDs
5837 int32_t id = offlineStream.id;
5838 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5839 SET_ERR("stream ID %d not found!", id);
5840 return UNKNOWN_ERROR;
5841 }
5842
5843 // When not using HAL buf manager, only allow streams requested by app to be preserved
5844 if (!mUseHalBufManager) {
5845 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
5846 SET_ERR("stream ID %d must not be switched to offline!", id);
5847 return UNKNOWN_ERROR;
5848 }
5849 }
5850
5851 offlineStreamIds.push_back(id);
5852 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
5853 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
5854 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
5855 // Verify number of outstanding buffers
5856 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
5857 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
5858 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
5859 return UNKNOWN_ERROR;
5860 }
5861 }
5862
5863 // Verify all streams to be deleted don't have any outstanding buffers
5864 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5865 inputStreamId) == offlineStreamIds.end()) {
5866 if (mInputStream->hasOutstandingBuffers()) {
5867 SET_ERR("Input stream %d still has %zu outstanding buffer!",
5868 inputStreamId, mInputStream->getOutstandingBuffersCount());
5869 return UNKNOWN_ERROR;
5870 }
5871 }
5872
5873 for (const auto& outStreamId : outputStreamIds) {
5874 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5875 outStreamId) == offlineStreamIds.end()) {
5876 auto outStream = mOutputStreams.get(outStreamId);
5877 if (outStream->hasOutstandingBuffers()) {
5878 SET_ERR("Output stream %d still has %zu outstanding buffer!",
5879 outStreamId, outStream->getOutstandingBuffersCount());
5880 return UNKNOWN_ERROR;
5881 }
5882 }
5883 }
5884
5885 InFlightRequestMap offlineReqs;
5886 // Verify inflight requests and their pending buffers
5887 {
5888 std::lock_guard<std::mutex> l(mInFlightLock);
5889 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
5890 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
5891 if (idx == NAME_NOT_FOUND) {
5892 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
5893 return UNKNOWN_ERROR;
5894 }
5895
5896 const auto& inflightReq = mInFlightMap.valueAt(idx);
5897 // TODO: check specific stream IDs
5898 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
5899 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
5900 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
5901 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
5902 return UNKNOWN_ERROR;
5903 }
5904 offlineReqs.add(offlineReq.frameNumber, inflightReq);
5905 }
5906 }
5907
5908 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005909 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005910 camera3::StreamSet offlineStreamSet;
5911 sp<camera3::Camera3Stream> inputStream;
5912 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5913 int32_t id = offlineStream.id;
5914 if (mInputStream != nullptr && id == mInputStream->getId()) {
5915 inputStream = mInputStream;
5916 } else {
5917 offlineStreamSet.add(id, mOutputStreams.get(id));
5918 }
5919 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005920
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005921 // TODO: check if we need to lock before copying states
5922 // though technically no other thread should be talking to Camera3Device at this point
5923 Camera3OfflineStates offlineStates(
5924 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07005925 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
5926 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
5927 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
5928 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
5929 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
5930 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
5931 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005932
5933 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
5934 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
5935
5936 // Delete all streams that has been transferred to offline session
5937 Mutex::Autolock l(mLock);
5938 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5939 int32_t id = offlineStream.id;
5940 if (mInputStream != nullptr && id == mInputStream->getId()) {
5941 mInputStream.clear();
5942 } else {
5943 mOutputStreams.remove(id);
5944 }
5945 }
5946
5947 // disconnect all other streams and switch to UNCONFIGURED state
5948 if (mInputStream != nullptr) {
5949 ret = mInputStream->disconnect();
5950 if (ret != OK) {
5951 SET_ERR_L("disconnect input stream failed!");
5952 return UNKNOWN_ERROR;
5953 }
5954 }
5955
5956 for (auto streamId : mOutputStreams.getStreamIds()) {
5957 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
5958 ret = stream->disconnect();
5959 if (ret != OK) {
5960 SET_ERR_L("disconnect output stream %d failed!", streamId);
5961 return UNKNOWN_ERROR;
5962 }
5963 }
5964
5965 mInputStream.clear();
5966 mOutputStreams.clear();
5967 mNeedConfig = true;
5968 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
5969 mOperatingMode = NO_MODE;
5970 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005971 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005972
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005973 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005974 // TO be done by CameraDeviceClient/Camera3OfflineSession
5975 // register the offline client to camera service
5976 // Setup result passthing threads etc
5977 // Initialize offline session so HAL can start sending callback to it (result Fmq)
5978 // TODO: check how many onIdle callback will be sent
5979 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005980}
5981
Emilian Peevcc0b7952020-01-07 13:54:47 -08005982void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5983 ATRACE_CALL();
5984
5985 if (offlineStreamIds == nullptr) {
5986 return;
5987 }
5988
5989 Mutex::Autolock il(mInterfaceLock);
5990
5991 auto streamIds = mOutputStreams.getStreamIds();
5992 bool hasInputStream = mInputStream != nullptr;
5993 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5994 offlineStreamIds->push_back(mInputStream->getId());
5995 }
5996
5997 for (const auto & streamId : streamIds) {
5998 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5999 // Streams that use the camera buffer manager are currently not supported in
6000 // offline mode
6001 if (stream->getOfflineProcessingSupport() &&
6002 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
6003 offlineStreamIds->push_back(streamId);
6004 }
6005 }
6006}
6007
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006008status_t Camera3Device::setRotateAndCropAutoBehavior(
6009 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6010 ATRACE_CALL();
6011 Mutex::Autolock il(mInterfaceLock);
6012 Mutex::Autolock l(mLock);
6013 if (mRequestThread == nullptr) {
6014 return INVALID_OPERATION;
6015 }
6016 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6017}
6018
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006019}; // namespace android