blob: 453040e94aaf0bea2f7e004e78e87eb69fc571fc [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"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080063
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080064#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080065#include <tuple>
66
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080068using namespace android::hardware::camera;
69using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080070
71namespace android {
72
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080073Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080074 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080075 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070076 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070077 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070078 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070079 mUsePartialResult(false),
80 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080081 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070082 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070083 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070084 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070085 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070086 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070087 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000088 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010089 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070090 mLastTemplateId(-1),
91 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080092{
93 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080094 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080095}
96
97Camera3Device::~Camera3Device()
98{
99 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800100 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700101 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102}
103
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800104const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800105 return mId;
106}
107
Emilian Peevbd8c5032018-02-14 23:05:40 +0000108status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800109 ATRACE_CALL();
110 Mutex::Autolock il(mInterfaceLock);
111 Mutex::Autolock l(mLock);
112
113 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
114 if (mStatus != STATUS_UNINITIALIZED) {
115 CLOGE("Already initialized!");
116 return INVALID_OPERATION;
117 }
118 if (manager == nullptr) return INVALID_OPERATION;
119
120 sp<ICameraDeviceSession> session;
121 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800122 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 /*out*/ &session);
124 ATRACE_END();
125 if (res != OK) {
126 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
127 return res;
128 }
129
Steven Moreland5ff9c912017-03-09 23:13:00 -0800130 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800131 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700132 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800133 session->close();
134 return res;
135 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800136 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800137
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700138 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700139 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700140 if (isLogical) {
141 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700142 res = manager->getCameraCharacteristics(
143 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700144 if (res != OK) {
145 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
146 physicalId.c_str(), strerror(-res), res);
147 session->close();
148 return res;
149 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700150
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800151 bool usePrecorrectArray =
152 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
153 if (usePrecorrectArray) {
154 res = mDistortionMappers[physicalId].setupStaticInfo(
155 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700156 if (res != OK) {
157 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
158 "correction", physicalId.c_str());
159 session->close();
160 return res;
161 }
162 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800163
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800164 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800165 &mPhysicalDeviceInfoMap[physicalId],
166 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700167 }
168 }
169
Yifan Hongf79b5542017-04-11 14:44:25 -0700170 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700171 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
172 [&queue](const auto& descriptor) {
173 queue = std::make_shared<RequestMetadataQueue>(descriptor);
174 if (!queue->isValid() || queue->availableToWrite() <= 0) {
175 ALOGE("HAL returns empty request metadata fmq, not use it");
176 queue = nullptr;
177 // don't use the queue onwards.
178 }
179 });
180 if (!requestQueueRet.isOk()) {
181 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
182 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700183 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700184 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700185
186 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700187 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700188 [&resQueue](const auto& descriptor) {
189 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
190 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700191 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700192 resQueue = nullptr;
193 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700194 }
195 });
196 if (!resultQueueRet.isOk()) {
197 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
198 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700199 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700200 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700201 IF_ALOGV() {
202 session->interfaceChain([](
203 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
204 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800205 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700206 ALOGV(" %s", iface.c_str());
207 }
208 });
209 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700210
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800211 camera_metadata_entry bufMgrMode =
212 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
213 if (bufMgrMode.count > 0) {
214 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
215 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
216 }
217
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700218 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
219 for (size_t i = 0; i < capabilities.count; i++) {
220 uint8_t capability = capabilities.data.u8[i];
221 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
222 mSupportOfflineProcessing = true;
223 }
224 }
225
226 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000227 std::string providerType;
228 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000229 mTagMonitor.initialize(mVendorTagId);
230 if (!monitorTags.isEmpty()) {
231 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
232 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800233
Shuzhen Wang268a1362018-10-16 16:32:59 -0700234 // Metadata tags needs fixup for monochrome camera device version less
235 // than 3.5.
236 hardware::hidl_version maxVersion{0,0};
237 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
238 if (res != OK) {
239 ALOGE("%s: Error in getting camera device version id: %s (%d)",
240 __FUNCTION__, strerror(-res), res);
241 return res;
242 }
243 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
244 maxVersion.get_major(), maxVersion.get_minor());
245
246 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700247 for (size_t i = 0; i < capabilities.count; i++) {
248 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700249 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
250 isMonochrome = true;
251 }
252 }
253 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
254
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800255 return initializeCommonLocked();
256}
257
258status_t Camera3Device::initializeCommonLocked() {
259
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700260 /** Start up status tracker thread */
261 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800262 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700263 if (res != OK) {
264 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
265 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800266 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700267 mStatusTracker.clear();
268 return res;
269 }
270
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700271 /** Register in-flight map to the status tracker */
272 mInFlightStatusId = mStatusTracker->addComponent();
273
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700274 if (mUseHalBufManager) {
275 res = mRequestBufferSM.initialize(mStatusTracker);
276 if (res != OK) {
277 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
278 strerror(-res), res);
279 mInterface->close();
280 mStatusTracker.clear();
281 return res;
282 }
283 }
284
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800285 /** Create buffer manager */
286 mBufferManager = new Camera3BufferManager();
287
288 Vector<int32_t> sessionParamKeys;
289 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
290 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
291 if (sessionKeysEntry.count > 0) {
292 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
293 }
294
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700295 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700296 mRequestThread = new RequestThread(
297 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800298 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800299 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700300 SET_ERR_L("Unable to start request queue thread: %s (%d)",
301 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800302 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800303 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800304 return res;
305 }
306
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700307 mPreparerThread = new PreparerThread();
308
Ruben Brunk183f0562015-08-12 12:55:02 -0700309 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800310 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700311 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700312 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700313 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800314
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800315 // Measure the clock domain offset between camera and video/hw_composer
316 camera_metadata_entry timestampSource =
317 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
318 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
319 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
320 mTimestampOffset = getMonoToBoottimeOffset();
321 }
322
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700323 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100324 camera_metadata_entry partialResultsCount =
325 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
326 if (partialResultsCount.count > 0) {
327 mNumPartialResults = partialResultsCount.data.i32[0];
328 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700329 }
330
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700331 camera_metadata_entry configs =
332 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
333 for (uint32_t i = 0; i < configs.count; i += 4) {
334 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
335 configs.data.i32[i + 3] ==
336 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
337 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
338 configs.data.i32[i + 2]));
339 }
340 }
341
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800342 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
343 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700344 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700345 if (res != OK) {
346 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
347 return res;
348 }
349 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800350
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800351 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800352 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800353
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800354 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
355 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
356 }
357
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800358 return OK;
359}
360
361status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700362 return disconnectImpl();
363}
364
365status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800366 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700367 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800368
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700369 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700370 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700371 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800372 Mutex::Autolock il(mInterfaceLock);
373 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
374 {
375 Mutex::Autolock l(mLock);
376 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700377
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800378 if (mStatus == STATUS_ACTIVE ||
379 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
380 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700381 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800382 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700383 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800384 } else {
385 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
386 if (res != OK) {
387 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
388 maxExpectedDuration);
389 // Continue to close device even in case of error
390 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700391 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700392 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800393
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800394 if (mStatus == STATUS_ERROR) {
395 CLOGE("Shutting down in an error state");
396 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700397
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800398 if (mStatusTracker != NULL) {
399 mStatusTracker->requestExit();
400 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700401
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800402 if (mRequestThread != NULL) {
403 mRequestThread->requestExit();
404 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700405
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800406 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
407 for (size_t i = 0; i < mOutputStreams.size(); i++) {
408 streams.push_back(mOutputStreams[i]);
409 }
410 if (mInputStream != nullptr) {
411 streams.push_back(mInputStream);
412 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700413 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700414 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800415 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
416 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700417 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
418 // HAL may be in a bad state, so waiting for request thread
419 // (which may be stuck in the HAL processCaptureRequest call)
420 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800421 // give up mInterfaceLock here and then lock it again. Could this lead
422 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700423 mRequestThread->join();
424 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700425 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800426 Mutex::Autolock il(mInterfaceLock);
427 if (mStatusTracker != NULL) {
428 mStatusTracker->join();
429 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800430
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800431 HalInterface* interface;
432 {
433 Mutex::Autolock l(mLock);
434 mRequestThread.clear();
435 Mutex::Autolock stLock(mTrackerLock);
436 mStatusTracker.clear();
437 interface = mInterface.get();
438 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700439
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800440 // Call close without internal mutex held, as the HAL close may need to
441 // wait on assorted callbacks,etc, to complete before it can return.
442 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700443
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800444 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800445
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800446 {
447 Mutex::Autolock l(mLock);
448 mInterface->clear();
449 mOutputStreams.clear();
450 mInputStream.clear();
451 mDeletedStreams.clear();
452 mBufferManager.clear();
453 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
454 }
455
456 for (auto& weakStream : streams) {
457 sp<Camera3StreamInterface> stream = weakStream.promote();
458 if (stream != nullptr) {
459 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
460 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
461 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700462 }
463 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700464 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700465 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800466}
467
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700468// For dumping/debugging only -
469// try to acquire a lock a few times, eventually give up to proceed with
470// debug/dump operations
471bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
472 bool gotLock = false;
473 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
474 if (lock.tryLock() == NO_ERROR) {
475 gotLock = true;
476 break;
477 } else {
478 usleep(kDumpSleepDuration);
479 }
480 }
481 return gotLock;
482}
483
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700484Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
485 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100486 const int STREAM_CONFIGURATION_SIZE = 4;
487 const int STREAM_FORMAT_OFFSET = 0;
488 const int STREAM_WIDTH_OFFSET = 1;
489 const int STREAM_HEIGHT_OFFSET = 2;
490 const int STREAM_IS_INPUT_OFFSET = 3;
491 camera_metadata_ro_entry_t availableStreamConfigs =
492 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
493 if (availableStreamConfigs.count == 0 ||
494 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
495 return Size(0, 0);
496 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700497
Emilian Peev08dd2452017-04-06 16:55:14 +0100498 // Get max jpeg size (area-wise).
499 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
500 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
501 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
502 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
503 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
504 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
505 && format == HAL_PIXEL_FORMAT_BLOB &&
506 (width * height > maxJpegWidth * maxJpegHeight)) {
507 maxJpegWidth = width;
508 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700509 }
510 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100511
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700512 return Size(maxJpegWidth, maxJpegHeight);
513}
514
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800515nsecs_t Camera3Device::getMonoToBoottimeOffset() {
516 // try three times to get the clock offset, choose the one
517 // with the minimum gap in measurements.
518 const int tries = 3;
519 nsecs_t bestGap, measured;
520 for (int i = 0; i < tries; ++i) {
521 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
522 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
523 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
524 const nsecs_t gap = tmono2 - tmono;
525 if (i == 0 || gap < bestGap) {
526 bestGap = gap;
527 measured = tbase - ((tmono + tmono2) >> 1);
528 }
529 }
530 return measured;
531}
532
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800533hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
534 int frameworkFormat) {
535 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
536}
537
538DataspaceFlags Camera3Device::mapToHidlDataspace(
539 android_dataspace dataSpace) {
540 return dataSpace;
541}
542
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700543BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100544 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700545 return usage;
546}
547
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800548StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
549 switch (rotation) {
550 case CAMERA3_STREAM_ROTATION_0:
551 return StreamRotation::ROTATION_0;
552 case CAMERA3_STREAM_ROTATION_90:
553 return StreamRotation::ROTATION_90;
554 case CAMERA3_STREAM_ROTATION_180:
555 return StreamRotation::ROTATION_180;
556 case CAMERA3_STREAM_ROTATION_270:
557 return StreamRotation::ROTATION_270;
558 }
559 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
560 return StreamRotation::ROTATION_0;
561}
562
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800563status_t Camera3Device::mapToStreamConfigurationMode(
564 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
565 if (mode == nullptr) return BAD_VALUE;
566 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
567 switch(operationMode) {
568 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
569 *mode = StreamConfigurationMode::NORMAL_MODE;
570 break;
571 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
572 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
573 break;
574 default:
575 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
576 return BAD_VALUE;
577 }
578 } else {
579 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800580 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800581 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800582}
583
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800584int Camera3Device::mapToFrameworkFormat(
585 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
586 return static_cast<uint32_t>(pixelFormat);
587}
588
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700589android_dataspace Camera3Device::mapToFrameworkDataspace(
590 DataspaceFlags dataSpace) {
591 return static_cast<android_dataspace>(dataSpace);
592}
593
Emilian Peev050f5dc2017-05-18 14:43:56 +0100594uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700595 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700596 return usage;
597}
598
Emilian Peev050f5dc2017-05-18 14:43:56 +0100599uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700600 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700601 return usage;
602}
603
Zhijun Hef7da0962014-04-24 13:27:56 -0700604ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700605 // Get max jpeg size (area-wise).
606 Size maxJpegResolution = getMaxJpegResolution();
607 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800608 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
609 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700610 return BAD_VALUE;
611 }
612
Zhijun Hef7da0962014-04-24 13:27:56 -0700613 // Get max jpeg buffer size
614 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700615 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
616 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800617 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
618 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700619 return BAD_VALUE;
620 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700621 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800622 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700623
624 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700625 float scaleFactor = ((float) (width * height)) /
626 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800627 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
628 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700629 if (jpegBufferSize > maxJpegBufferSize) {
630 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700631 }
632
633 return jpegBufferSize;
634}
635
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700636ssize_t Camera3Device::getPointCloudBufferSize() const {
637 const int FLOATS_PER_POINT=4;
638 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
639 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800640 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
641 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700642 return BAD_VALUE;
643 }
644 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
645 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
646 return maxBytesForPointCloud;
647}
648
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800649ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800650 const int PER_CONFIGURATION_SIZE = 3;
651 const int WIDTH_OFFSET = 0;
652 const int HEIGHT_OFFSET = 1;
653 const int SIZE_OFFSET = 2;
654 camera_metadata_ro_entry rawOpaqueSizes =
655 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800656 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800657 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800658 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
659 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800660 return BAD_VALUE;
661 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700662
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800663 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
664 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
665 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
666 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
667 }
668 }
669
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800670 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
671 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800672 return BAD_VALUE;
673}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700674
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800675status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
676 ATRACE_CALL();
677 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700678
679 // Try to lock, but continue in case of failure (to avoid blocking in
680 // deadlocks)
681 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
682 bool gotLock = tryLockSpinRightRound(mLock);
683
684 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800685 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
686 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700687 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800688 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
689 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700690
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800691 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700692
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800693 String16 templatesOption("-t");
694 int n = args.size();
695 for (int i = 0; i < n; i++) {
696 if (args[i] == templatesOption) {
697 dumpTemplates = true;
698 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000699 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700700 if (i + 1 < n) {
701 String8 monitorTags = String8(args[i + 1]);
702 if (monitorTags == "off") {
703 mTagMonitor.disableMonitoring();
704 } else {
705 mTagMonitor.parseTagsToMonitor(monitorTags);
706 }
707 } else {
708 mTagMonitor.disableMonitoring();
709 }
710 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800711 }
712
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800713 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800714
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800715 const char *status =
716 mStatus == STATUS_ERROR ? "ERROR" :
717 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700718 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
719 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800720 mStatus == STATUS_ACTIVE ? "ACTIVE" :
721 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700722
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800723 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700724 if (mStatus == STATUS_ERROR) {
725 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
726 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800727 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800728 const char *mode =
729 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
730 mOperatingMode == static_cast<int>(
731 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
732 "CUSTOM";
733 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800734
735 if (mInputStream != NULL) {
736 write(fd, lines.string(), lines.size());
737 mInputStream->dump(fd, args);
738 } else {
739 lines.appendFormat(" No input stream.\n");
740 write(fd, lines.string(), lines.size());
741 }
742 for (size_t i = 0; i < mOutputStreams.size(); i++) {
743 mOutputStreams[i]->dump(fd,args);
744 }
745
Zhijun He431503c2016-03-07 17:30:16 -0800746 if (mBufferManager != NULL) {
747 lines = String8(" Camera3 Buffer Manager:\n");
748 write(fd, lines.string(), lines.size());
749 mBufferManager->dump(fd, args);
750 }
Zhijun He125684a2015-12-26 15:07:30 -0800751
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700752 lines = String8(" In-flight requests:\n");
753 if (mInFlightMap.size() == 0) {
754 lines.append(" None\n");
755 } else {
756 for (size_t i = 0; i < mInFlightMap.size(); i++) {
757 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700758 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Shuzhen Wang730a7912020-05-07 11:59:02 -0700759 " arrived: %s, buffers left: %d, buffers returned with STATUS_ERROR: %d, "
760 " buffers notified with error: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800761 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Shuzhen Wang730a7912020-05-07 11:59:02 -0700762 r.numBuffersLeft, r.numErrorBuffersReturned, r.numErrorBuffersNotified);
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 Wang730a7912020-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 Wang730a7912020-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 Wang730a7912020-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 Talvala002001b2018-01-23 16:53:50 -08001784void Camera3Device::pauseStateNotify(bool enable) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08001785 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001786 Mutex::Autolock l(mLock);
1787
1788 mPauseStateNotify = enable;
1789}
1790
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001791// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001792status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001793 if (mRequestThread.get() != nullptr) {
1794 mRequestThread->setPaused(true);
1795 } else {
1796 return NO_INIT;
1797 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001798
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001799 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1800 maxExpectedDuration);
1801 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001802 if (res != OK) {
1803 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001804 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001805 }
1806
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001807 return res;
1808}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001809
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001810// Resume after internalPauseAndWaitLocked
1811status_t Camera3Device::internalResumeLocked() {
1812 status_t res;
1813
1814 mRequestThread->setPaused(false);
1815
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001816 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1817 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001818 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1819 if (res != OK) {
1820 SET_ERR_L("Can't transition to active in %f seconds!",
1821 kActiveTimeout/1e9);
1822 }
1823 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001824 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001825}
1826
Ruben Brunk183f0562015-08-12 12:55:02 -07001827status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001829
1830 size_t startIndex = 0;
1831 if (mStatusWaiters == 0) {
1832 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1833 // this status list
1834 mRecentStatusUpdates.clear();
1835 } else {
1836 // If other threads are waiting on updates to this status list, set the position of the
1837 // first element that this list will check rather than clearing the list.
1838 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001839 }
1840
Ruben Brunk183f0562015-08-12 12:55:02 -07001841 mStatusWaiters++;
1842
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001843 if (!active && mUseHalBufManager) {
1844 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001845 if (mStatus == STATUS_ACTIVE) {
1846 mRequestThread->signalPipelineDrain(streamIds);
1847 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001848 mRequestBufferSM.onWaitUntilIdle();
1849 }
1850
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001851 bool stateSeen = false;
1852 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001853 if (active == (mStatus == STATUS_ACTIVE)) {
1854 // Desired state is current
1855 break;
1856 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001857
1858 res = mStatusChanged.waitRelative(mLock, timeout);
1859 if (res != OK) break;
1860
Ruben Brunk183f0562015-08-12 12:55:02 -07001861 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1862 // transitions.
1863 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1864 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1865 __FUNCTION__);
1866
1867 // Encountered desired state since we began waiting
1868 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001869 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1870 stateSeen = true;
1871 break;
1872 }
1873 }
1874 } while (!stateSeen);
1875
Ruben Brunk183f0562015-08-12 12:55:02 -07001876 mStatusWaiters--;
1877
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001878 return res;
1879}
1880
1881
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001882status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001883 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001884 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001885
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001886 if (listener != NULL && mListener != NULL) {
1887 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1888 }
1889 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001890 mRequestThread->setNotificationListener(listener);
1891 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001892
1893 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001894}
1895
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001896bool Camera3Device::willNotify3A() {
1897 return false;
1898}
1899
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001900status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001901 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001902 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001903
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001904 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001905 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1906 if (st == std::cv_status::timeout) {
1907 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001908 }
1909 }
1910 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001911}
1912
Jianing Weicb0652e2014-03-12 18:29:36 -07001913status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001914 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001915 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001916
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001917 if (mResultQueue.empty()) {
1918 return NOT_ENOUGH_DATA;
1919 }
1920
Jianing Weicb0652e2014-03-12 18:29:36 -07001921 if (frame == NULL) {
1922 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1923 return BAD_VALUE;
1924 }
1925
1926 CaptureResult &result = *(mResultQueue.begin());
1927 frame->mResultExtras = result.mResultExtras;
1928 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001929 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001930 mResultQueue.erase(mResultQueue.begin());
1931
1932 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001933}
1934
1935status_t Camera3Device::triggerAutofocus(uint32_t id) {
1936 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001937 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001938
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001939 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1940 // Mix-in this trigger into the next request and only the next request.
1941 RequestTrigger trigger[] = {
1942 {
1943 ANDROID_CONTROL_AF_TRIGGER,
1944 ANDROID_CONTROL_AF_TRIGGER_START
1945 },
1946 {
1947 ANDROID_CONTROL_AF_TRIGGER_ID,
1948 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001949 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001950 };
1951
1952 return mRequestThread->queueTrigger(trigger,
1953 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001954}
1955
1956status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1957 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001958 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001959
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001960 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1961 // Mix-in this trigger into the next request and only the next request.
1962 RequestTrigger trigger[] = {
1963 {
1964 ANDROID_CONTROL_AF_TRIGGER,
1965 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1966 },
1967 {
1968 ANDROID_CONTROL_AF_TRIGGER_ID,
1969 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001970 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001971 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001972
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001973 return mRequestThread->queueTrigger(trigger,
1974 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001975}
1976
1977status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1978 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001979 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001980
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001981 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1982 // Mix-in this trigger into the next request and only the next request.
1983 RequestTrigger trigger[] = {
1984 {
1985 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1986 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1987 },
1988 {
1989 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1990 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001991 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001992 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001993
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001994 return mRequestThread->queueTrigger(trigger,
1995 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001996}
1997
Jianing Weicb0652e2014-03-12 18:29:36 -07001998status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001999 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002000 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002001 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002002
Zhijun He7ef20392014-04-21 16:04:17 -07002003 {
2004 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002005
2006 // b/116514106 "disconnect()" can get called twice for the same device. The
2007 // camera device will not be initialized during the second run.
2008 if (mStatus == STATUS_UNINITIALIZED) {
2009 return OK;
2010 }
2011
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002012 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002013 }
2014
Emilian Peev08dd2452017-04-06 16:55:14 +01002015 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002016}
2017
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002018status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002019 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2020}
2021
2022status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002023 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002024 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002025 Mutex::Autolock il(mInterfaceLock);
2026 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002027
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002028 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2029 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002030 CLOGE("Stream %d does not exist", streamId);
2031 return BAD_VALUE;
2032 }
2033
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002034 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002035 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002036 return BAD_VALUE;
2037 }
2038
2039 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002040 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002041 return BAD_VALUE;
2042 }
2043
Ruben Brunkc78ac262015-08-13 17:58:46 -07002044 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002045}
2046
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002047status_t Camera3Device::tearDown(int streamId) {
2048 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002049 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002050 Mutex::Autolock il(mInterfaceLock);
2051 Mutex::Autolock l(mLock);
2052
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002053 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2054 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002055 CLOGE("Stream %d does not exist", streamId);
2056 return BAD_VALUE;
2057 }
2058
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002059 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2060 CLOGE("Stream %d is a target of a in-progress request", streamId);
2061 return BAD_VALUE;
2062 }
2063
2064 return stream->tearDown();
2065}
2066
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002067status_t Camera3Device::addBufferListenerForStream(int streamId,
2068 wp<Camera3StreamBufferListener> listener) {
2069 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002070 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002071 Mutex::Autolock il(mInterfaceLock);
2072 Mutex::Autolock l(mLock);
2073
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002074 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2075 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002076 CLOGE("Stream %d does not exist", streamId);
2077 return BAD_VALUE;
2078 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002079 stream->addBufferListener(listener);
2080
2081 return OK;
2082}
2083
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002084/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002085 * Methods called by subclasses
2086 */
2087
2088void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002089 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002090 {
2091 // Need mLock to safely update state and synchronize to current
2092 // state of methods in flight.
2093 Mutex::Autolock l(mLock);
2094 // We can get various system-idle notices from the status tracker
2095 // while starting up. Only care about them if we've actually sent
2096 // in some requests recently.
2097 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2098 return;
2099 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002100 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2101 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002102 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002103
2104 // Skip notifying listener if we're doing some user-transparent
2105 // state changes
2106 if (mPauseStateNotify) return;
2107 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002108
2109 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002110 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002111 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002112 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002113 }
2114 if (idle && listener != NULL) {
2115 listener->notifyIdle();
2116 }
2117}
2118
Shuzhen Wang758c2152017-01-10 18:26:18 -08002119status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002120 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002121 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002122 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2123 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002124
2125 if (surfaceIds == nullptr) {
2126 return BAD_VALUE;
2127 }
2128
Zhijun He5d677d12016-05-29 16:52:39 -07002129 Mutex::Autolock il(mInterfaceLock);
2130 Mutex::Autolock l(mLock);
2131
Shuzhen Wang758c2152017-01-10 18:26:18 -08002132 if (consumers.size() == 0) {
2133 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002134 return BAD_VALUE;
2135 }
2136
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002137 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2138 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002139 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002140 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002141 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002142
2143 // isConsumerConfigurationDeferred will be off after setConsumers
2144 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002145 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002146 if (res != OK) {
2147 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2148 return res;
2149 }
2150
Emilian Peev40ead602017-09-26 15:46:36 +01002151 for (auto &consumer : consumers) {
2152 int id = stream->getSurfaceId(consumer);
2153 if (id < 0) {
2154 CLOGE("Invalid surface id!");
2155 return BAD_VALUE;
2156 }
2157 surfaceIds->push_back(id);
2158 }
2159
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002160 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002161 if (!stream->isConfiguring()) {
2162 CLOGE("Stream %d was already fully configured.", streamId);
2163 return INVALID_OPERATION;
2164 }
Zhijun He5d677d12016-05-29 16:52:39 -07002165
Shuzhen Wang0129d522016-10-30 22:43:41 -07002166 res = stream->finishConfiguration();
2167 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002168 // If finishConfiguration fails due to abandoned surface, do not set
2169 // device to error state.
2170 bool isSurfaceAbandoned =
2171 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2172 if (!isSurfaceAbandoned) {
2173 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2174 stream->getId(), strerror(-res), res);
2175 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002176 return res;
2177 }
Zhijun He5d677d12016-05-29 16:52:39 -07002178 }
2179
2180 return OK;
2181}
2182
Emilian Peev40ead602017-09-26 15:46:36 +01002183status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2184 const std::vector<OutputStreamInfo> &outputInfo,
2185 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2186 Mutex::Autolock il(mInterfaceLock);
2187 Mutex::Autolock l(mLock);
2188
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002189 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2190 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002191 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002192 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002193 }
2194
2195 for (const auto &it : removedSurfaceIds) {
2196 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2197 CLOGE("Shared surface still part of a pending request!");
2198 return -EBUSY;
2199 }
2200 }
2201
Emilian Peev40ead602017-09-26 15:46:36 +01002202 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2203 if (res != OK) {
2204 CLOGE("Stream %d failed to update stream (error %d %s) ",
2205 streamId, res, strerror(-res));
2206 if (res == UNKNOWN_ERROR) {
2207 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2208 __FUNCTION__);
2209 }
2210 return res;
2211 }
2212
2213 return res;
2214}
2215
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002216status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2217 Mutex::Autolock il(mInterfaceLock);
2218 Mutex::Autolock l(mLock);
2219
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002220 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2221 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002222 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2223 return BAD_VALUE;
2224 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002225 return stream->dropBuffers(dropping);
2226}
2227
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002228/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002229 * Camera3Device private methods
2230 */
2231
2232sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002233 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002234 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002235
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002236 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002237 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002238
2239 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002240 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002241 if (inputStreams.count > 0) {
2242 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002243 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002244 CLOGE("Request references unknown input stream %d",
2245 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002246 return NULL;
2247 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002248
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002249 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002250 SET_ERR_L("%s: input stream %d is not configured!",
2251 __FUNCTION__, mInputStream->getId());
2252 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002253 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002254 // Check if stream prepare is blocking requests.
2255 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002256 CLOGE("Request references an input stream that's being prepared!");
2257 return NULL;
2258 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002259
2260 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002261 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002262 }
2263
2264 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002265 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002266 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002267 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002268 return NULL;
2269 }
2270
2271 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002272 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2273 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002274 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002275 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002276 return NULL;
2277 }
Zhijun He5d677d12016-05-29 16:52:39 -07002278 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002279 auto iter = surfaceMap.find(streams.data.i32[i]);
2280 if (iter != surfaceMap.end()) {
2281 const std::vector<size_t>& surfaces = iter->second;
2282 for (const auto& surface : surfaces) {
2283 if (stream->isConsumerConfigurationDeferred(surface)) {
2284 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2285 "due to deferred consumer", stream->getId(), surface);
2286 return NULL;
2287 }
2288 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002289 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002290 }
2291
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002292 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002293 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2294 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002295 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002296 // Check if stream prepare is blocking requests.
2297 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002298 CLOGE("Request references an output stream that's being prepared!");
2299 return NULL;
2300 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002301
2302 newRequest->mOutputStreams.push(stream);
2303 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002304 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002305 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002306
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002307 auto rotateAndCropEntry =
2308 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2309 if (rotateAndCropEntry.count > 0 &&
2310 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2311 newRequest->mRotateAndCropAuto = true;
2312 } else {
2313 newRequest->mRotateAndCropAuto = false;
2314 }
2315
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002316 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002317}
2318
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002319void Camera3Device::cancelStreamsConfigurationLocked() {
2320 int res = OK;
2321 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2322 res = mInputStream->cancelConfiguration();
2323 if (res != OK) {
2324 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2325 mInputStream->getId(), strerror(-res), res);
2326 }
2327 }
2328
2329 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002330 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002331 if (outputStream->isConfiguring()) {
2332 res = outputStream->cancelConfiguration();
2333 if (res != OK) {
2334 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2335 outputStream->getId(), strerror(-res), res);
2336 }
2337 }
2338 }
2339
2340 // Return state to that at start of call, so that future configures
2341 // properly clean things up
2342 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2343 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002344
2345 res = mPreparerThread->resume();
2346 if (res != OK) {
2347 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2348 }
2349}
2350
Emilian Peev0d0191e2020-04-21 17:01:18 -07002351bool Camera3Device::checkAbandonedStreamsLocked() {
2352 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2353 return true;
2354 }
2355
2356 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2357 auto stream = mOutputStreams[i];
2358 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2359 return true;
2360 }
2361 }
2362
2363 return false;
2364}
2365
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002366bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2367 ATRACE_CALL();
2368 bool ret = false;
2369
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002370 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002371 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2372
2373 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002374 if (checkAbandonedStreamsLocked()) {
2375 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2376 __FUNCTION__);
2377 return true;
2378 }
2379
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002380 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2381 if (rc == NO_ERROR) {
2382 mNeedConfig = true;
2383 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2384 if (rc == NO_ERROR) {
2385 ret = true;
2386 mPauseStateNotify = false;
2387 //Moving to active state while holding 'mLock' is important.
2388 //There could be pending calls to 'create-/deleteStream' which
2389 //will trigger another stream configuration while the already
2390 //present streams end up with outstanding buffers that will
2391 //not get drained.
2392 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002393 } else if (rc == DEAD_OBJECT) {
2394 // DEAD_OBJECT can be returned if either the consumer surface is
2395 // abandoned, or the HAL has died.
2396 // - If the HAL has died, configureStreamsLocked call will set
2397 // device to error state,
2398 // - If surface is abandoned, we should not set device to error
2399 // state.
2400 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002401 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002402 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002403 }
2404 } else {
2405 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2406 }
2407
2408 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002409}
2410
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002411status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002412 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002413 ATRACE_CALL();
2414 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002415
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002416 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002417 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002418 return INVALID_OPERATION;
2419 }
2420
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002421 if (operatingMode < 0) {
2422 CLOGE("Invalid operating mode: %d", operatingMode);
2423 return BAD_VALUE;
2424 }
2425
2426 bool isConstrainedHighSpeed =
2427 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2428 operatingMode;
2429
2430 if (mOperatingMode != operatingMode) {
2431 mNeedConfig = true;
2432 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2433 mOperatingMode = operatingMode;
2434 }
2435
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002436 // In case called from configureStreams, abort queued input buffers not belonging to
2437 // any pending requests.
2438 if (mInputStream != NULL && notifyRequestThread) {
2439 while (true) {
2440 camera3_stream_buffer_t inputBuffer;
2441 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2442 /*respectHalLimit*/ false);
2443 if (res != OK) {
2444 // Exhausted acquiring all input buffers.
2445 break;
2446 }
2447
2448 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2449 res = mInputStream->returnInputBuffer(inputBuffer);
2450 if (res != OK) {
2451 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2452 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2453 }
2454 }
2455 }
2456
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002457 if (!mNeedConfig) {
2458 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2459 return OK;
2460 }
2461
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002462 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2463 // adding a dummy stream instead.
2464 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2465 if (mOutputStreams.size() == 0) {
2466 addDummyStreamLocked();
2467 } else {
2468 tryRemoveDummyStreamLocked();
2469 }
2470
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002471 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002472 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002473
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002474 mPreparerThread->pause();
2475
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002476 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002477 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002478 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2479
2480 Vector<camera3_stream_t*> streams;
2481 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002482 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002483
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002484
2485 if (mInputStream != NULL) {
2486 camera3_stream_t *inputStream;
2487 inputStream = mInputStream->startConfiguration();
2488 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002489 CLOGE("Can't start input stream configuration");
2490 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002491 return INVALID_OPERATION;
2492 }
2493 streams.add(inputStream);
2494 }
2495
2496 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002497
2498 // Don't configure bidi streams twice, nor add them twice to the list
2499 if (mOutputStreams[i].get() ==
2500 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2501
2502 config.num_streams--;
2503 continue;
2504 }
2505
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002506 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002507 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002508 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002509 CLOGE("Can't start output stream configuration");
2510 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002511 return INVALID_OPERATION;
2512 }
2513 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002514
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002515 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002516 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2517 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002518 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2519 bufferSizes[k] = static_cast<uint32_t>(
2520 getJpegBufferSize(outputStream->width, outputStream->height));
2521 } else if (outputStream->data_space ==
2522 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2523 bufferSizes[k] = outputStream->width * outputStream->height;
2524 } else {
2525 ALOGW("%s: Blob dataSpace %d not supported",
2526 __FUNCTION__, outputStream->data_space);
2527 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002528 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002529 }
2530
2531 config.streams = streams.editArray();
2532
2533 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002534 // max_buffers, usage, and priv fields, as well as data_space and format
2535 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002536
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002537 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002538 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002539 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002540
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002541 if (res == BAD_VALUE) {
2542 // HAL rejected this set of streams as unsupported, clean up config
2543 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002544 CLOGE("Set of requested inputs/outputs not supported by HAL");
2545 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002546 return BAD_VALUE;
2547 } else if (res != OK) {
2548 // Some other kind of error from configure_streams - this is not
2549 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002550 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2551 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002552 return res;
2553 }
2554
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002555 // Finish all stream configuration immediately.
2556 // TODO: Try to relax this later back to lazy completion, which should be
2557 // faster
2558
Igor Murashkin073f8572013-05-02 14:59:28 -07002559 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002560 bool streamReConfigured = false;
2561 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002562 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002563 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002564 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002565 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002566 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2567 return DEAD_OBJECT;
2568 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002569 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002570 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002571 if (streamReConfigured) {
2572 mInterface->onStreamReConfigured(mInputStream->getId());
2573 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002574 }
2575
2576 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002577 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002578 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002579 bool streamReConfigured = false;
2580 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002581 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002582 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002583 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002584 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002585 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2586 return DEAD_OBJECT;
2587 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002588 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002589 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002590 if (streamReConfigured) {
2591 mInterface->onStreamReConfigured(outputStream->getId());
2592 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002593 }
2594 }
2595
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002596 // Request thread needs to know to avoid using repeat-last-settings protocol
2597 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002598 if (notifyRequestThread) {
2599 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2600 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002601
Zhijun He90f7c372016-08-16 16:19:43 -07002602 char value[PROPERTY_VALUE_MAX];
2603 property_get("camera.fifo.disable", value, "0");
2604 int32_t disableFifo = atoi(value);
2605 if (disableFifo != 1) {
2606 // Boost priority of request thread to SCHED_FIFO.
2607 pid_t requestThreadTid = mRequestThread->getTid();
2608 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002609 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002610 if (res != OK) {
2611 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2612 strerror(-res), res);
2613 } else {
2614 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2615 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002616 }
2617
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002618 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002619 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2620 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2621 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2622 sessionParams.unlock(newSessionParams);
2623 mSessionParams.unlock(currentSessionParams);
2624 if (updateSessionParams) {
2625 mSessionParams = sessionParams;
2626 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002627
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002628 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002629
Ruben Brunk183f0562015-08-12 12:55:02 -07002630 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2631 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002632
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002633 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002634
Zhijun He0a210512014-07-24 13:45:15 -07002635 // tear down the deleted streams after configure streams.
2636 mDeletedStreams.clear();
2637
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002638 auto rc = mPreparerThread->resume();
2639 if (rc != OK) {
2640 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2641 return rc;
2642 }
2643
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002644 if (mDummyStreamId == NO_STREAM) {
2645 mRequestBufferSM.onStreamsConfigured();
2646 }
2647
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002648 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002649}
2650
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002651status_t Camera3Device::addDummyStreamLocked() {
2652 ATRACE_CALL();
2653 status_t res;
2654
2655 if (mDummyStreamId != NO_STREAM) {
2656 // Should never be adding a second dummy stream when one is already
2657 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002658 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2659 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002660 return INVALID_OPERATION;
2661 }
2662
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002663 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002664
2665 sp<Camera3OutputStreamInterface> dummyStream =
2666 new Camera3DummyStream(mNextStreamId);
2667
2668 res = mOutputStreams.add(mNextStreamId, dummyStream);
2669 if (res < 0) {
2670 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2671 return res;
2672 }
2673
2674 mDummyStreamId = mNextStreamId;
2675 mNextStreamId++;
2676
2677 return OK;
2678}
2679
2680status_t Camera3Device::tryRemoveDummyStreamLocked() {
2681 ATRACE_CALL();
2682 status_t res;
2683
2684 if (mDummyStreamId == NO_STREAM) return OK;
2685 if (mOutputStreams.size() == 1) return OK;
2686
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002687 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002688
2689 // Ok, have a dummy stream and there's at least one other output stream,
2690 // so remove the dummy
2691
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002692 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2693 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002694 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2695 return INVALID_OPERATION;
2696 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002697 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002698
2699 // Free up the stream endpoint so that it can be used by some other stream
2700 res = deletedStream->disconnect();
2701 if (res != OK) {
2702 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2703 // fall through since we want to still list the stream as deleted.
2704 }
2705 mDeletedStreams.add(deletedStream);
2706 mDummyStreamId = NO_STREAM;
2707
2708 return res;
2709}
2710
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002711void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002712 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002713 Mutex::Autolock l(mLock);
2714 va_list args;
2715 va_start(args, fmt);
2716
2717 setErrorStateLockedV(fmt, args);
2718
2719 va_end(args);
2720}
2721
2722void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002723 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002724 Mutex::Autolock l(mLock);
2725 setErrorStateLockedV(fmt, args);
2726}
2727
2728void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2729 va_list args;
2730 va_start(args, fmt);
2731
2732 setErrorStateLockedV(fmt, args);
2733
2734 va_end(args);
2735}
2736
2737void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002738 // Print out all error messages to log
2739 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002740 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002741
2742 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002743 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002744
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002745 mErrorCause = errorCause;
2746
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002747 if (mRequestThread != nullptr) {
2748 mRequestThread->setPaused(true);
2749 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002750 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002751
2752 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002753 sp<NotificationListener> listener = mListener.promote();
2754 if (listener != NULL) {
2755 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002756 CaptureResultExtras());
2757 }
2758
2759 // Save stack trace. View by dumping it later.
2760 CameraTraces::saveTrace();
2761 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002762}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002763
2764/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002765 * In-flight request management
2766 */
2767
Jianing Weicb0652e2014-03-12 18:29:36 -07002768status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002769 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002770 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002771 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002772 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08002773 const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002774 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002775 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002776
2777 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002778 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002779 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002780 rotateAndCropAuto, cameraIdsWithZoom, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002781 if (res < 0) return res;
2782
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002783 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002784 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2785 // avoid a deadlock during reprocess requests.
2786 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002787 if (mStatusTracker != nullptr) {
2788 mStatusTracker->markComponentActive(mInFlightStatusId);
2789 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002790 }
2791
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002792 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002793 return OK;
2794}
2795
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002796void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002797 // Indicate idle inFlightMap to the status tracker
2798 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002799 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002800 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2801 // avoid a deadlock during reprocess requests.
2802 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002803 if (mStatusTracker != nullptr) {
2804 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2805 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002806 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002807 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002808}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002809
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002810void Camera3Device::checkInflightMapLengthLocked() {
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002811 // Sanity check - if we have too many in-flight frames with long total inflight duration,
2812 // something has likely gone wrong. This might still be legit only if application send in
2813 // a long burst of long exposure requests.
2814 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2815 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2816 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2817 mInFlightMap.size(), mExpectedInflightDuration);
2818 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2819 kInFlightWarnLimitHighSpeed) {
2820 CLOGW("In-flight list too large for high speed configuration: %zu,"
2821 "total inflight duration %" PRIu64,
2822 mInFlightMap.size(), mExpectedInflightDuration);
2823 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002824 }
2825}
2826
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002827void Camera3Device::onInflightMapFlushedLocked() {
2828 mExpectedInflightDuration = 0;
2829}
2830
2831void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2832 ATRACE_CALL();
2833 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2834 mInFlightMap.removeItemsAt(idx, 1);
2835
2836 onInflightEntryRemovedLocked(duration);
2837}
2838
2839
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002840void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002841 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002842 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002843 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002844 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002845 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002846 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002847
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002848 FlushInflightReqStates states {
2849 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
2850 listener, *this, *mInterface, *this};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002851
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002852 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002853}
2854
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002855CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002856 ALOGV("%s", __FUNCTION__);
2857
Igor Murashkin1e479c02013-09-06 16:55:14 -07002858 CameraMetadata retVal;
2859
2860 if (mRequestThread != NULL) {
2861 retVal = mRequestThread->getLatestRequest();
2862 }
2863
Igor Murashkin1e479c02013-09-06 16:55:14 -07002864 return retVal;
2865}
2866
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002867void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002868 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2869 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2870
2871 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2872 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002873}
2874
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002875/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002876 * HalInterface inner class methods
2877 */
2878
Yifan Hongf79b5542017-04-11 14:44:25 -07002879Camera3Device::HalInterface::HalInterface(
2880 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002881 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002882 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002883 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002884 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08002885 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002886 mIsReconfigurationQuerySupported(true),
2887 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002888 // Check with hardware service manager if we can downcast these interfaces
2889 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002890 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
2891 if (castResult_3_6.isOk()) {
2892 mHidlSession_3_6 = castResult_3_6;
2893 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002894 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
2895 if (castResult_3_5.isOk()) {
2896 mHidlSession_3_5 = castResult_3_5;
2897 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002898 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
2899 if (castResult_3_4.isOk()) {
2900 mHidlSession_3_4 = castResult_3_4;
2901 }
2902 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
2903 if (castResult_3_3.isOk()) {
2904 mHidlSession_3_3 = castResult_3_3;
2905 }
2906}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002907
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002908Camera3Device::HalInterface::HalInterface() :
2909 mUseHalBufManager(false),
2910 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002911
2912Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002913 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002914 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002915 mUseHalBufManager(other.mUseHalBufManager),
2916 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002917
2918bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01002919 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002920}
2921
2922void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002923 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00002924 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00002925 mHidlSession_3_4.clear();
2926 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002927 mHidlSession.clear();
2928}
2929
2930status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2931 camera3_request_template_t templateId,
2932 /*out*/ camera_metadata_t **requestTemplate) {
2933 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
2934 if (!valid()) return INVALID_OPERATION;
2935 status_t res = OK;
2936
Emilian Peev31abd0a2017-05-11 18:37:46 +01002937 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002938
2939 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01002940 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002941 status = s;
2942 if (status == common::V1_0::Status::OK) {
2943 const camera_metadata *r =
2944 reinterpret_cast<const camera_metadata_t*>(request.data());
2945 size_t expectedSize = request.size();
2946 int ret = validate_camera_metadata_structure(r, &expectedSize);
2947 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
2948 *requestTemplate = clone_camera_metadata(r);
2949 if (*requestTemplate == nullptr) {
2950 ALOGE("%s: Unable to clone camera metadata received from HAL",
2951 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01002952 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002953 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002954 } else {
2955 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
2956 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01002957 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002958 }
2959 };
2960 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08002961 RequestTemplate id;
2962 switch (templateId) {
2963 case CAMERA3_TEMPLATE_PREVIEW:
2964 id = RequestTemplate::PREVIEW;
2965 break;
2966 case CAMERA3_TEMPLATE_STILL_CAPTURE:
2967 id = RequestTemplate::STILL_CAPTURE;
2968 break;
2969 case CAMERA3_TEMPLATE_VIDEO_RECORD:
2970 id = RequestTemplate::VIDEO_RECORD;
2971 break;
2972 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
2973 id = RequestTemplate::VIDEO_SNAPSHOT;
2974 break;
2975 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
2976 id = RequestTemplate::ZERO_SHUTTER_LAG;
2977 break;
2978 case CAMERA3_TEMPLATE_MANUAL:
2979 id = RequestTemplate::MANUAL;
2980 break;
2981 default:
2982 // Unknown template ID, or this HAL is too old to support it
2983 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002984 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08002985 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002986
Emilian Peev31abd0a2017-05-11 18:37:46 +01002987 if (!err.isOk()) {
2988 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
2989 res = DEAD_OBJECT;
2990 } else {
2991 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002992 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01002993
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002994 return res;
2995}
2996
Emilian Peev4ec17882019-01-24 17:16:58 -08002997bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
2998 CameraMetadata& newSessionParams) {
2999 // We do reconfiguration by default;
3000 bool ret = true;
3001 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3002 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3003 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3004 oldSessionParams.getAndLock());
3005 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3006 newSessionParams.getAndLock());
3007 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3008 get_camera_metadata_size(oldSessioMeta));
3009 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3010 get_camera_metadata_size(newSessioMeta));
3011 hardware::camera::common::V1_0::Status callStatus;
3012 bool required;
3013 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3014 bool requiredFlag) {
3015 callStatus = s;
3016 required = requiredFlag;
3017 };
3018 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3019 oldSessionParams.unlock(oldSessioMeta);
3020 newSessionParams.unlock(newSessioMeta);
3021 if (err.isOk()) {
3022 switch (callStatus) {
3023 case hardware::camera::common::V1_0::Status::OK:
3024 ret = required;
3025 break;
3026 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3027 mIsReconfigurationQuerySupported = false;
3028 ret = true;
3029 break;
3030 default:
3031 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3032 ret = true;
3033 }
3034 } else {
3035 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3036 ret = true;
3037 }
3038 }
3039
3040 return ret;
3041}
3042
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003043status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003044 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003045 ATRACE_NAME("CameraHal::configureStreams");
3046 if (!valid()) return INVALID_OPERATION;
3047 status_t res = OK;
3048
Emilian Peev31abd0a2017-05-11 18:37:46 +01003049 // Convert stream config to HIDL
3050 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003051 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3052 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3053 requestedConfiguration3_2.streams.resize(config->num_streams);
3054 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003055 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003056 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3057 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003058 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003059
Emilian Peev31abd0a2017-05-11 18:37:46 +01003060 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3061 cam3stream->setBufferFreedListener(this);
3062 int streamId = cam3stream->getId();
3063 StreamType streamType;
3064 switch (src->stream_type) {
3065 case CAMERA3_STREAM_OUTPUT:
3066 streamType = StreamType::OUTPUT;
3067 break;
3068 case CAMERA3_STREAM_INPUT:
3069 streamType = StreamType::INPUT;
3070 break;
3071 default:
3072 ALOGE("%s: Stream %d: Unsupported stream type %d",
3073 __FUNCTION__, streamId, config->streams[i]->stream_type);
3074 return BAD_VALUE;
3075 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003076 dst3_2.id = streamId;
3077 dst3_2.streamType = streamType;
3078 dst3_2.width = src->width;
3079 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003080 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003081 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003082 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3083 // to HAL are original, not the overriden ones.
3084 if (mHidlSession_3_5 != nullptr) {
3085 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3086 cam3stream->getOriginalFormat() : src->format);
3087 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3088 cam3stream->getOriginalDataSpace() : src->data_space);
3089 } else {
3090 dst3_2.format = mapToPixelFormat(src->format);
3091 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3092 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003093 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003094 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003095 if (src->physical_camera_id != nullptr) {
3096 dst3_4.physicalCameraId = src->physical_camera_id;
3097 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003098
3099 activeStreams.insert(streamId);
3100 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003101 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003102 }
3103 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003104 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003105
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003106 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003107 res = mapToStreamConfigurationMode(
3108 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003109 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003110 if (res != OK) {
3111 return res;
3112 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003113 requestedConfiguration3_2.operationMode = operationMode;
3114 requestedConfiguration3_4.operationMode = operationMode;
3115 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003116 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3117 get_camera_metadata_size(sessionParams));
3118
Emilian Peev31abd0a2017-05-11 18:37:46 +01003119 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003120 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003121 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003122 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003123 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003124
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003125 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003126 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3127 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003128 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003129 };
3130
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003131 auto configStream36Cb = [&status, &finalConfiguration3_6]
3132 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3133 finalConfiguration3_6 = halConfiguration;
3134 status = s;
3135 };
3136
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003137 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3138 (hardware::Return<void>& err) -> status_t {
3139 if (!err.isOk()) {
3140 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3141 return DEAD_OBJECT;
3142 }
3143 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3144 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3145 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3146 }
3147 return OK;
3148 };
3149
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003150 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3151 (hardware::Return<void>& err) -> status_t {
3152 if (!err.isOk()) {
3153 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3154 return DEAD_OBJECT;
3155 }
3156 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3157 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3158 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3159 }
3160 return OK;
3161 };
3162
Shuzhen Wang92653952019-05-07 15:11:43 -07003163 // See which version of HAL we have
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003164 if (mHidlSession_3_6 != nullptr) {
3165 ALOGV("%s: v3.6 device found", __FUNCTION__);
3166 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3167 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3168 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3169 auto err = mHidlSession_3_6->configureStreams_3_6(
3170 requestedConfiguration3_5, configStream36Cb);
3171 res = postprocConfigStream36(err);
3172 if (res != OK) {
3173 return res;
3174 }
3175 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003176 ALOGV("%s: v3.5 device found", __FUNCTION__);
3177 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3178 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3179 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3180 auto err = mHidlSession_3_5->configureStreams_3_5(
3181 requestedConfiguration3_5, configStream34Cb);
3182 res = postprocConfigStream34(err);
3183 if (res != OK) {
3184 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003185 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003186 } else if (mHidlSession_3_4 != nullptr) {
3187 // We do; use v3.4 for the call
3188 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003189 auto err = mHidlSession_3_4->configureStreams_3_4(
3190 requestedConfiguration3_4, configStream34Cb);
3191 res = postprocConfigStream34(err);
3192 if (res != OK) {
3193 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003194 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003195 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003196 // We do; use v3.3 for the call
3197 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003198 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003199 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003200 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003201 finalConfiguration = halConfiguration;
3202 status = s;
3203 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003204 if (!err.isOk()) {
3205 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3206 return DEAD_OBJECT;
3207 }
3208 } else {
3209 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3210 ALOGV("%s: v3.2 device found", __FUNCTION__);
3211 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003212 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003213 [&status, &finalConfiguration_3_2]
3214 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3215 finalConfiguration_3_2 = halConfiguration;
3216 status = s;
3217 });
3218 if (!err.isOk()) {
3219 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3220 return DEAD_OBJECT;
3221 }
3222 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3223 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3224 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3225 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003226 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003227 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003228 }
3229
3230 if (status != common::V1_0::Status::OK ) {
3231 return CameraProviderManager::mapToStatusT(status);
3232 }
3233
3234 // And convert output stream configuration from HIDL
3235
3236 for (size_t i = 0; i < config->num_streams; i++) {
3237 camera3_stream_t *dst = config->streams[i];
3238 int streamId = Camera3Stream::cast(dst)->getId();
3239
3240 // Start scan at i, with the assumption that the stream order matches
3241 size_t realIdx = i;
3242 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003243 size_t halStreamCount = finalConfiguration.streams.size();
3244 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003245 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003246 found = true;
3247 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003248 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003249 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003250 }
3251 if (!found) {
3252 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3253 __FUNCTION__, streamId);
3254 return INVALID_OPERATION;
3255 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003256 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003257 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003258
Emilian Peev710c1422017-08-30 11:19:38 +01003259 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003260 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3261 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3262
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003263 if (mHidlSession_3_6 != nullptr) {
3264 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3265 }
3266
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003267 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003268 dstStream->setFormatOverride(false);
3269 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003270 if (dst->format != overrideFormat) {
3271 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3272 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003273 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003274 if (dst->data_space != overrideDataSpace) {
3275 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3276 streamId, dst->format);
3277 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003278 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003279 bool needFormatOverride =
3280 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3281 bool needDataspaceOverride =
3282 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003283 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003284 dstStream->setFormatOverride(needFormatOverride);
3285 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003286 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003287 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003288 }
3289
Emilian Peev31abd0a2017-05-11 18:37:46 +01003290 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003291 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003292 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003293 __FUNCTION__, streamId);
3294 return INVALID_OPERATION;
3295 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003296 dstStream->setUsage(
3297 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003298 } else {
3299 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003300 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003301 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3302 __FUNCTION__, streamId);
3303 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003304 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003305 dstStream->setUsage(
3306 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003307 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003308 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003309 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003310
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003311 return res;
3312}
3313
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003314status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003315 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003316 /*out*/std::vector<native_handle_t*>* handlesCreated,
3317 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003318 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003319 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3320 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3321 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003322 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003323 }
3324
3325 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003326
3327 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003328
3329 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003330 if (request->input_buffer != nullptr) {
3331 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3332 buffer_handle_t buf = *(request->input_buffer->buffer);
3333 auto pair = getBufferId(buf, streamId);
3334 bool isNewBuffer = pair.first;
3335 uint64_t bufferId = pair.second;
3336 captureRequest->inputBuffer.streamId = streamId;
3337 captureRequest->inputBuffer.bufferId = bufferId;
3338 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3339 captureRequest->inputBuffer.status = BufferStatus::OK;
3340 native_handle_t *acquireFence = nullptr;
3341 if (request->input_buffer->acquire_fence != -1) {
3342 acquireFence = native_handle_create(1,0);
3343 acquireFence->data[0] = request->input_buffer->acquire_fence;
3344 handlesCreated->push_back(acquireFence);
3345 }
3346 captureRequest->inputBuffer.acquireFence = acquireFence;
3347 captureRequest->inputBuffer.releaseFence = nullptr;
3348
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003349 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003350 request->input_buffer->buffer);
3351 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003352 } else {
3353 captureRequest->inputBuffer.streamId = -1;
3354 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3355 }
3356
3357 captureRequest->outputBuffers.resize(request->num_output_buffers);
3358 for (size_t i = 0; i < request->num_output_buffers; i++) {
3359 const camera3_stream_buffer_t *src = request->output_buffers + i;
3360 StreamBuffer &dst = captureRequest->outputBuffers[i];
3361 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003362 if (src->buffer != nullptr) {
3363 buffer_handle_t buf = *(src->buffer);
3364 auto pair = getBufferId(buf, streamId);
3365 bool isNewBuffer = pair.first;
3366 dst.bufferId = pair.second;
3367 dst.buffer = isNewBuffer ? buf : nullptr;
3368 native_handle_t *acquireFence = nullptr;
3369 if (src->acquire_fence != -1) {
3370 acquireFence = native_handle_create(1,0);
3371 acquireFence->data[0] = src->acquire_fence;
3372 handlesCreated->push_back(acquireFence);
3373 }
3374 dst.acquireFence = acquireFence;
3375 } else if (mUseHalBufManager) {
3376 // HAL buffer management path
3377 dst.bufferId = BUFFER_ID_NO_BUFFER;
3378 dst.buffer = nullptr;
3379 dst.acquireFence = nullptr;
3380 } else {
3381 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3382 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003383 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003384 dst.streamId = streamId;
3385 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003386 dst.releaseFence = nullptr;
3387
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003388 // Output buffers are empty when using HAL buffer manager
3389 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003390 mBufferRecords.pushInflightBuffer(
3391 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003392 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003393 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003394 }
3395 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003396 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003397}
3398
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003399void Camera3Device::HalInterface::cleanupNativeHandles(
3400 std::vector<native_handle_t*> *handles, bool closeFd) {
3401 if (handles == nullptr) {
3402 return;
3403 }
3404 if (closeFd) {
3405 for (auto& handle : *handles) {
3406 native_handle_close(handle);
3407 }
3408 }
3409 for (auto& handle : *handles) {
3410 native_handle_delete(handle);
3411 }
3412 handles->clear();
3413 return;
3414}
3415
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003416status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3417 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3418 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3419 if (!valid()) return INVALID_OPERATION;
3420
Emilian Peevaebbe412018-01-15 13:53:24 +00003421 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3422 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3423 if (castResult_3_4.isOk()) {
3424 hidlSession_3_4 = castResult_3_4;
3425 }
3426
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003427 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003428 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003429 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003430 if (hidlSession_3_4 != nullptr) {
3431 captureRequests_3_4.resize(batchSize);
3432 } else {
3433 captureRequests.resize(batchSize);
3434 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003435 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003436 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003437
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003438 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003439 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003440 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003441 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003442 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003443 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003444 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3445 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003446 }
3447 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003448 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003449 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003450 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003451 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003452 }
3453
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003454 std::vector<device::V3_2::BufferCache> cachesToRemove;
3455 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003456 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003457 for (auto& pair : mFreedBuffers) {
3458 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003459 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003460 cachesToRemove.push_back({pair.first, pair.second});
3461 }
3462 }
3463 mFreedBuffers.clear();
3464 }
3465
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003466 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3467 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003468
3469 // Write metadata to FMQ.
3470 for (size_t i = 0; i < batchSize; i++) {
3471 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003472 device::V3_2::CaptureRequest* captureRequest;
3473 if (hidlSession_3_4 != nullptr) {
3474 captureRequest = &captureRequests_3_4[i].v3_2;
3475 } else {
3476 captureRequest = &captureRequests[i];
3477 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003478
3479 if (request->settings != nullptr) {
3480 size_t settingsSize = get_camera_metadata_size(request->settings);
3481 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3482 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3483 captureRequest->settings.resize(0);
3484 captureRequest->fmqSettingsSize = settingsSize;
3485 } else {
3486 if (mRequestMetadataQueue != nullptr) {
3487 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3488 }
3489 captureRequest->settings.setToExternal(
3490 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3491 get_camera_metadata_size(request->settings));
3492 captureRequest->fmqSettingsSize = 0u;
3493 }
3494 } else {
3495 // A null request settings maps to a size-0 CameraMetadata
3496 captureRequest->settings.resize(0);
3497 captureRequest->fmqSettingsSize = 0u;
3498 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003499
3500 if (hidlSession_3_4 != nullptr) {
3501 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3502 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003503 if (request->physcam_settings != nullptr) {
3504 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3505 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3506 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3507 settingsSize)) {
3508 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3509 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3510 settingsSize;
3511 } else {
3512 if (mRequestMetadataQueue != nullptr) {
3513 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3514 }
3515 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3516 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3517 request->physcam_settings[j])),
3518 get_camera_metadata_size(request->physcam_settings[j]));
3519 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003520 }
Emilian Peev00420d22018-02-05 21:33:13 +00003521 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003522 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003523 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003524 }
3525 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3526 request->physcam_id[j];
3527 }
3528 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003529 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003530
3531 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003532 auto resultCallback =
3533 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3534 status = s;
3535 *numRequestProcessed = n;
3536 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003537 if (hidlSession_3_4 != nullptr) {
3538 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003539 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003540 } else {
3541 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003542 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003543 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003544 if (!err.isOk()) {
3545 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003546 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003547 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003548
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003549 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3550 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3551 __FUNCTION__, *numRequestProcessed, batchSize);
3552 status = common::V1_0::Status::INTERNAL_ERROR;
3553 }
3554
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003555 res = CameraProviderManager::mapToStatusT(status);
3556 if (res == OK) {
3557 if (mHidlSession->isRemote()) {
3558 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3559 // sent to camera HAL processes)
3560 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3561 } else {
3562 // In passthrough mode the FDs are now owned by HAL
3563 cleanupNativeHandles(&handlesCreated);
3564 }
3565 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003566 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003567 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003568 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003569 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003570}
3571
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003572status_t Camera3Device::HalInterface::flush() {
3573 ATRACE_NAME("CameraHal::flush");
3574 if (!valid()) return INVALID_OPERATION;
3575 status_t res = OK;
3576
Emilian Peev31abd0a2017-05-11 18:37:46 +01003577 auto err = mHidlSession->flush();
3578 if (!err.isOk()) {
3579 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3580 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003581 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003582 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003583 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003584
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003585 return res;
3586}
3587
Emilian Peev31abd0a2017-05-11 18:37:46 +01003588status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003589 ATRACE_NAME("CameraHal::dump");
3590 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003591
Emilian Peev31abd0a2017-05-11 18:37:46 +01003592 // Handled by CameraProviderManager::dump
3593
3594 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003595}
3596
3597status_t Camera3Device::HalInterface::close() {
3598 ATRACE_NAME("CameraHal::close()");
3599 if (!valid()) return INVALID_OPERATION;
3600 status_t res = OK;
3601
Emilian Peev31abd0a2017-05-11 18:37:46 +01003602 auto err = mHidlSession->close();
3603 // Interface will be dead shortly anyway, so don't log errors
3604 if (!err.isOk()) {
3605 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003606 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003607
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003608 return res;
3609}
3610
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003611void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3612 ATRACE_NAME("CameraHal::signalPipelineDrain");
3613 if (!valid() || mHidlSession_3_5 == nullptr) {
3614 ALOGE("%s called on invalid camera!", __FUNCTION__);
3615 return;
3616 }
3617
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003618 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003619 if (!err.isOk()) {
3620 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3621 return;
3622 }
3623}
3624
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003625status_t Camera3Device::HalInterface::switchToOffline(
3626 const std::vector<int32_t>& streamsToKeep,
3627 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003628 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3629 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003630 ATRACE_NAME("CameraHal::switchToOffline");
3631 if (!valid() || mHidlSession_3_6 == nullptr) {
3632 ALOGE("%s called on invalid camera!", __FUNCTION__);
3633 return INVALID_OPERATION;
3634 }
3635
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003636 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3637 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003638 return INVALID_OPERATION;
3639 }
3640
3641 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003642 auto resultCallback =
3643 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3644 status = s;
3645 *offlineSessionInfo = info;
3646 *offlineSession = session;
3647 };
3648 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3649
3650 if (!err.isOk()) {
3651 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3652 return DEAD_OBJECT;
3653 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003654
3655 status_t ret = CameraProviderManager::mapToStatusT(status);
3656 if (ret != OK) {
3657 return ret;
3658 }
3659
3660 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3661 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3662 // returns from switchToOffline.
3663
3664
3665 // Validate buffer caches
3666 std::vector<int32_t> streams;
3667 streams.reserve(offlineSessionInfo->offlineStreams.size());
3668 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3669 int32_t id = offlineStream.id;
3670 streams.push_back(id);
3671 // Verify buffer caches
3672 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3673 offlineStream.circulatingBufferIds.end());
3674 if (!verifyBufferIds(id, bufIds)) {
3675 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3676 return UNKNOWN_ERROR;
3677 }
3678 }
3679
3680 // Move buffer records
3681 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3682 bufferRecords->takeInflightBufferMap(mBufferRecords);
3683 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3684 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003685}
3686
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003687void Camera3Device::HalInterface::getInflightBufferKeys(
3688 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003689 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003690 return;
3691}
3692
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003693void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3694 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003695 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003696 return;
3697}
3698
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003699bool Camera3Device::HalInterface::verifyBufferIds(
3700 int32_t streamId, std::vector<uint64_t>& bufIds) {
3701 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003702}
3703
3704status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003705 int32_t frameNumber, int32_t streamId,
3706 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003707 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003708}
3709
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003710status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003711 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003712 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003713}
3714
3715// Find and pop a buffer_handle_t based on bufferId
3716status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003717 uint64_t bufferId,
3718 /*out*/ buffer_handle_t** buffer,
3719 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003720 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003721}
3722
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003723std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3724 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003725 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003726}
3727
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003728void Camera3Device::HalInterface::onBufferFreed(
3729 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003730 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3731 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3732 if (bufferId != BUFFER_ID_NO_BUFFER) {
3733 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003734 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003735}
3736
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003737void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003738 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3739 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3740 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003741 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3742 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003743}
3744
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003745/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003746 * RequestThread inner class methods
3747 */
3748
3749Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003750 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003751 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3752 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003753 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003754 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003755 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003756 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003757 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003758 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003759 mReconfigured(false),
3760 mDoPause(false),
3761 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003762 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003763 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003764 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003765 mCurrentAfTriggerId(0),
3766 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003767 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003768 mRepeatingLastFrameNumber(
3769 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003770 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003771 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003772 mRequestLatency(kRequestLatencyBinSize),
3773 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003774 mLatestSessionParams(sessionParamKeys.size()),
3775 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003776 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003777}
3778
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003779Camera3Device::RequestThread::~RequestThread() {}
3780
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003781void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003782 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003783 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003784 Mutex::Autolock l(mRequestLock);
3785 mListener = listener;
3786}
3787
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003788void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3789 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003790 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003791 Mutex::Autolock l(mRequestLock);
3792 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003793 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003794 // Prepare video stream for high speed recording.
3795 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003796 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003797}
3798
Jianing Wei90e59c92014-03-12 18:29:36 -07003799status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003800 List<sp<CaptureRequest> > &requests,
3801 /*out*/
3802 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003803 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003804 Mutex::Autolock l(mRequestLock);
3805 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3806 ++it) {
3807 mRequestQueue.push_back(*it);
3808 }
3809
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003810 if (lastFrameNumber != NULL) {
3811 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3812 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3813 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3814 *lastFrameNumber);
3815 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003816
Jianing Wei90e59c92014-03-12 18:29:36 -07003817 unpauseForNewRequests();
3818
3819 return OK;
3820}
3821
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003822
3823status_t Camera3Device::RequestThread::queueTrigger(
3824 RequestTrigger trigger[],
3825 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003826 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003827 Mutex::Autolock l(mTriggerMutex);
3828 status_t ret;
3829
3830 for (size_t i = 0; i < count; ++i) {
3831 ret = queueTriggerLocked(trigger[i]);
3832
3833 if (ret != OK) {
3834 return ret;
3835 }
3836 }
3837
3838 return OK;
3839}
3840
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003841const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3842 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003843 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003844 if (d != nullptr) return d->mId;
3845 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003846}
3847
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003848status_t Camera3Device::RequestThread::queueTriggerLocked(
3849 RequestTrigger trigger) {
3850
3851 uint32_t tag = trigger.metadataTag;
3852 ssize_t index = mTriggerMap.indexOfKey(tag);
3853
3854 switch (trigger.getTagType()) {
3855 case TYPE_BYTE:
3856 // fall-through
3857 case TYPE_INT32:
3858 break;
3859 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003860 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3861 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003862 return INVALID_OPERATION;
3863 }
3864
3865 /**
3866 * Collect only the latest trigger, since we only have 1 field
3867 * in the request settings per trigger tag, and can't send more than 1
3868 * trigger per request.
3869 */
3870 if (index != NAME_NOT_FOUND) {
3871 mTriggerMap.editValueAt(index) = trigger;
3872 } else {
3873 mTriggerMap.add(tag, trigger);
3874 }
3875
3876 return OK;
3877}
3878
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003879status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003880 const RequestList &requests,
3881 /*out*/
3882 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003883 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003884 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003885 if (lastFrameNumber != NULL) {
3886 *lastFrameNumber = mRepeatingLastFrameNumber;
3887 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003888 mRepeatingRequests.clear();
3889 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3890 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003891
3892 unpauseForNewRequests();
3893
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003894 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003895 return OK;
3896}
3897
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003898bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003899 if (mRepeatingRequests.empty()) {
3900 return false;
3901 }
3902 int32_t requestId = requestIn->mResultExtras.requestId;
3903 const RequestList &repeatRequests = mRepeatingRequests;
3904 // All repeating requests are guaranteed to have same id so only check first quest
3905 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3906 return (firstRequest->mResultExtras.requestId == requestId);
3907}
3908
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003909status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003910 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003911 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003912 return clearRepeatingRequestsLocked(lastFrameNumber);
3913
3914}
3915
3916status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003917 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003918 if (lastFrameNumber != NULL) {
3919 *lastFrameNumber = mRepeatingLastFrameNumber;
3920 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003921 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003922 return OK;
3923}
3924
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003925status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003926 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003927 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003928 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003929 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003930
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003931 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003932
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003933 // Send errors for all requests pending in the request queue, including
3934 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003935 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003936 if (listener != NULL) {
3937 for (RequestList::iterator it = mRequestQueue.begin();
3938 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003939 // Abort the input buffers for reprocess requests.
3940 if ((*it)->mInputStream != NULL) {
3941 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003942 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3943 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003944 if (res != OK) {
3945 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3946 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3947 } else {
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07003948 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003949 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3950 if (res != OK) {
3951 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3952 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3953 }
3954 }
3955 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003956 // Set the frame number this request would have had, if it
3957 // had been submitted; this frame number will not be reused.
3958 // The requestId and burstId fields were set when the request was
3959 // submitted originally (in convertMetadataListToRequestListLocked)
3960 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003961 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003962 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003963 }
3964 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003965 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003966
3967 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003968 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003969 if (lastFrameNumber != NULL) {
3970 *lastFrameNumber = mRepeatingLastFrameNumber;
3971 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003972 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003973 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003974 return OK;
3975}
3976
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003977status_t Camera3Device::RequestThread::flush() {
3978 ATRACE_CALL();
3979 Mutex::Autolock l(mFlushLock);
3980
Emilian Peev08dd2452017-04-06 16:55:14 +01003981 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003982}
3983
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003984void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003985 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003986 Mutex::Autolock l(mPauseLock);
3987 mDoPause = paused;
3988 mDoPauseSignal.signal();
3989}
3990
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003991status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3992 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003993 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003994 Mutex::Autolock l(mLatestRequestMutex);
3995 status_t res;
3996 while (mLatestRequestId != requestId) {
3997 nsecs_t startTime = systemTime();
3998
3999 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4000 if (res != OK) return res;
4001
4002 timeout -= (systemTime() - startTime);
4003 }
4004
4005 return OK;
4006}
4007
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004008void Camera3Device::RequestThread::requestExit() {
4009 // Call parent to set up shutdown
4010 Thread::requestExit();
4011 // The exit from any possible waits
4012 mDoPauseSignal.signal();
4013 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004014
4015 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4016 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004017}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004018
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004019void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004020 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004021 bool surfaceAbandoned = false;
4022 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004023 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004024 {
4025 Mutex::Autolock l(mRequestLock);
4026 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4027 // repeating requests.
4028 for (const auto& request : mRepeatingRequests) {
4029 for (const auto& s : request->mOutputStreams) {
4030 if (s->isAbandoned()) {
4031 surfaceAbandoned = true;
4032 clearRepeatingRequestsLocked(&lastFrameNumber);
4033 break;
4034 }
4035 }
4036 if (surfaceAbandoned) {
4037 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004038 }
4039 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004040 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004041 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004042
4043 if (listener != NULL && surfaceAbandoned) {
4044 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004045 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004046}
4047
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004048bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004049 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004050 status_t res;
4051 size_t batchSize = mNextRequests.size();
4052 std::vector<camera3_capture_request_t*> requests(batchSize);
4053 uint32_t numRequestProcessed = 0;
4054 for (size_t i = 0; i < batchSize; i++) {
4055 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004056 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004057 }
4058
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004059 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4060
4061 bool triggerRemoveFailed = false;
4062 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4063 for (size_t i = 0; i < numRequestProcessed; i++) {
4064 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4065 nextRequest.submitted = true;
4066
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004067 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004068
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004069 if (!triggerRemoveFailed) {
4070 // Remove any previously queued triggers (after unlock)
4071 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4072 if (removeTriggerRes != OK) {
4073 triggerRemoveFailed = true;
4074 triggerFailedRequest = nextRequest;
4075 }
4076 }
4077 }
4078
4079 if (triggerRemoveFailed) {
4080 SET_ERR("RequestThread: Unable to remove triggers "
4081 "(capture request %d, HAL device: %s (%d)",
4082 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4083 cleanUpFailedRequests(/*sendRequestError*/ false);
4084 return false;
4085 }
4086
4087 if (res != OK) {
4088 // Should only get a failure here for malformed requests or device-level
4089 // errors, so consider all errors fatal. Bad metadata failures should
4090 // come through notify.
4091 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4092 mNextRequests[numRequestProcessed].halRequest.frame_number,
4093 strerror(-res), res);
4094 cleanUpFailedRequests(/*sendRequestError*/ false);
4095 return false;
4096 }
4097 return true;
4098}
4099
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004100nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4101 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4102 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4103 find_camera_metadata_ro_entry(request,
4104 ANDROID_CONTROL_AE_MODE,
4105 &e);
4106 if (e.count == 0) return maxExpectedDuration;
4107
4108 switch (e.data.u8[0]) {
4109 case ANDROID_CONTROL_AE_MODE_OFF:
4110 find_camera_metadata_ro_entry(request,
4111 ANDROID_SENSOR_EXPOSURE_TIME,
4112 &e);
4113 if (e.count > 0) {
4114 maxExpectedDuration = e.data.i64[0];
4115 }
4116 find_camera_metadata_ro_entry(request,
4117 ANDROID_SENSOR_FRAME_DURATION,
4118 &e);
4119 if (e.count > 0) {
4120 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4121 }
4122 break;
4123 default:
4124 find_camera_metadata_ro_entry(request,
4125 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4126 &e);
4127 if (e.count > 1) {
4128 maxExpectedDuration = 1e9 / e.data.u8[0];
4129 }
4130 break;
4131 }
4132
4133 return maxExpectedDuration;
4134}
4135
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004136bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4137 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4138 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4139 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4140 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4141 return true;
4142 }
4143
4144 return false;
4145}
4146
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004147void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4148 // Update the latest request sent to HAL
4149 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4150 Mutex::Autolock al(mLatestRequestMutex);
4151
4152 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4153 mLatestRequest.acquire(cloned);
4154
4155 mLatestPhysicalRequest.clear();
4156 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
4157 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
4158 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
4159 CameraMetadata(cloned));
4160 }
4161
4162 sp<Camera3Device> parent = mParent.promote();
4163 if (parent != NULL) {
4164 parent->monitorMetadata(TagMonitor::REQUEST,
4165 nextRequest.halRequest.frame_number,
4166 0, mLatestRequest, mLatestPhysicalRequest);
4167 }
4168 }
4169
4170 if (nextRequest.halRequest.settings != NULL) {
4171 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4172 nextRequest.halRequest.settings);
4173 }
4174
4175 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4176}
4177
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004178bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4179 ATRACE_CALL();
4180 bool updatesDetected = false;
4181
Emilian Peev4ec17882019-01-24 17:16:58 -08004182 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004183 for (auto tag : mSessionParamKeys) {
4184 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004185 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004186
4187 if (entry.count > 0) {
4188 bool isDifferent = false;
4189 if (lastEntry.count > 0) {
4190 // Have a last value, compare to see if changed
4191 if (lastEntry.type == entry.type &&
4192 lastEntry.count == entry.count) {
4193 // Same type and count, compare values
4194 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4195 size_t entryBytes = bytesPerValue * lastEntry.count;
4196 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4197 if (cmp != 0) {
4198 isDifferent = true;
4199 }
4200 } else {
4201 // Count or type has changed
4202 isDifferent = true;
4203 }
4204 } else {
4205 // No last entry, so always consider to be different
4206 isDifferent = true;
4207 }
4208
4209 if (isDifferent) {
4210 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004211 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4212 updatesDetected = true;
4213 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004214 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004215 }
4216 } else if (lastEntry.count > 0) {
4217 // Value has been removed
4218 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004219 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004220 updatesDetected = true;
4221 }
4222 }
4223
Emilian Peev4ec17882019-01-24 17:16:58 -08004224 bool reconfigureRequired;
4225 if (updatesDetected) {
4226 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4227 updatedParams);
4228 mLatestSessionParams = updatedParams;
4229 } else {
4230 reconfigureRequired = false;
4231 }
4232
4233 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004234}
4235
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004236bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004237 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004238 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004239 // Any function called from threadLoop() must not hold mInterfaceLock since
4240 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4241 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004242
4243 // Handle paused state.
4244 if (waitIfPaused()) {
4245 return true;
4246 }
4247
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004248 // Wait for the next batch of requests.
4249 waitForNextRequestBatch();
4250 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004251 return true;
4252 }
4253
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004254 // Get the latest request ID, if any
4255 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004256 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004257 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004258 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004259 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004260 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004261 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4262 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004263 }
4264
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004265 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4266 // or a single request from streaming or burst. In either case the first element
4267 // should contain the latest camera settings that we need to check for any session
4268 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004269 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004270 res = OK;
4271
4272 //Input stream buffers are already acquired at this point so an input stream
4273 //will not be able to move to idle state unless we force it.
4274 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4275 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4276 if (res != OK) {
4277 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4278 cleanUpFailedRequests(/*sendRequestError*/ false);
4279 return false;
4280 }
4281 }
4282
4283 if (res == OK) {
4284 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4285 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004286 sp<Camera3Device> parent = mParent.promote();
4287 if (parent != nullptr) {
4288 parent->pauseStateNotify(true);
4289 }
4290
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004291 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4292
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004293 if (parent != nullptr) {
4294 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4295 }
4296
4297 statusTracker->markComponentActive(mStatusId);
4298 setPaused(false);
4299 }
4300
4301 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4302 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4303 if (res != OK) {
4304 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4305 cleanUpFailedRequests(/*sendRequestError*/ false);
4306 return false;
4307 }
4308 }
4309 }
4310 }
4311
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004312 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004313 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004314 if (res == TIMED_OUT) {
4315 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004316 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004317 // Check if any stream is abandoned.
4318 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004319 return true;
4320 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004321 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004322 return false;
4323 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004324
Zhijun Hecc27e112013-10-03 16:12:43 -07004325 // Inform waitUntilRequestProcessed thread of a new request ID
4326 {
4327 Mutex::Autolock al(mLatestRequestMutex);
4328
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004329 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004330 mLatestRequestSignal.signal();
4331 }
4332
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004333 // Submit a batch of requests to HAL.
4334 // Use flush lock only when submitting multilple requests in a batch.
4335 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4336 // which may take a long time to finish so synchronizing flush() and
4337 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4338 // For now, only synchronize for high speed recording and we should figure something out for
4339 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004340 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004341
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004342 if (useFlushLock) {
4343 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004344 }
4345
Zhijun Hef0645c12016-08-02 00:58:11 -07004346 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004347 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004348
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004349 sp<Camera3Device> parent = mParent.promote();
4350 if (parent != nullptr) {
4351 parent->mRequestBufferSM.onSubmittingRequest();
4352 }
4353
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004354 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004355 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004356 submitRequestSuccess = sendRequestsBatch();
4357
Shuzhen Wang686f6442017-06-20 16:16:04 -07004358 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4359 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004360
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004361 if (useFlushLock) {
4362 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004363 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004364
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004365 // Unset as current request
4366 {
4367 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004368 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004369 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004370 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004371
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004372 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004373}
4374
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004375status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004376 ATRACE_CALL();
4377
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004378 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004379 for (size_t i = 0; i < mNextRequests.size(); i++) {
4380 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004381 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4382 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4383 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4384
4385 // Prepare a request to HAL
4386 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4387
4388 // Insert any queued triggers (before metadata is locked)
4389 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004390 if (res < 0) {
4391 SET_ERR("RequestThread: Unable to insert triggers "
4392 "(capture request %d, HAL device: %s (%d)",
4393 halRequest->frame_number, strerror(-res), res);
4394 return INVALID_OPERATION;
4395 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004396
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004397 int triggerCount = res;
4398 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4399 mPrevTriggers = triggerCount;
4400
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004401 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
4402
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004403 // If the request is the same as last, or we had triggers last time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004404 bool newRequest =
4405 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004406 // Request settings are all the same within one batch, so only treat the first
4407 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004408 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004409 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004410 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004411 /**
4412 * HAL workaround:
4413 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4414 */
4415 res = addDummyTriggerIds(captureRequest);
4416 if (res != OK) {
4417 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4418 "(capture request %d, HAL device: %s (%d)",
4419 halRequest->frame_number, strerror(-res), res);
4420 return INVALID_OPERATION;
4421 }
4422
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004423 {
4424 // Correct metadata regions for distortion correction if enabled
4425 sp<Camera3Device> parent = mParent.promote();
4426 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004427 List<PhysicalCameraSettings>::iterator it;
4428 for (it = captureRequest->mSettingsList.begin();
4429 it != captureRequest->mSettingsList.end(); it++) {
4430 if (parent->mDistortionMappers.find(it->cameraId) ==
4431 parent->mDistortionMappers.end()) {
4432 continue;
4433 }
4434 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4435 &(it->metadata));
4436 if (res != OK) {
4437 SET_ERR("RequestThread: Unable to correct capture requests "
4438 "for lens distortion for request %d: %s (%d)",
4439 halRequest->frame_number, strerror(-res), res);
4440 return INVALID_OPERATION;
4441 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004442 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004443
4444 for (it = captureRequest->mSettingsList.begin();
4445 it != captureRequest->mSettingsList.end(); it++) {
4446 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4447 parent->mZoomRatioMappers.end()) {
4448 continue;
4449 }
4450
4451 camera_metadata_entry_t e = it->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
4452 if (e.count > 0 && e.data.f[0] != 1.0f) {
4453 cameraIdsWithZoom.insert(it->cameraId);
4454 }
4455
4456 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4457 &(it->metadata));
4458 if (res != OK) {
4459 SET_ERR("RequestThread: Unable to correct capture requests "
4460 "for zoom ratio for request %d: %s (%d)",
4461 halRequest->frame_number, strerror(-res), res);
4462 return INVALID_OPERATION;
4463 }
4464 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004465 if (captureRequest->mRotateAndCropAuto) {
4466 for (it = captureRequest->mSettingsList.begin();
4467 it != captureRequest->mSettingsList.end(); it++) {
4468 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4469 if (mapper != parent->mRotateAndCropMappers.end()) {
4470 res = mapper->second.updateCaptureRequest(&(it->metadata));
4471 if (res != OK) {
4472 SET_ERR("RequestThread: Unable to correct capture requests "
4473 "for rotate-and-crop for request %d: %s (%d)",
4474 halRequest->frame_number, strerror(-res), res);
4475 return INVALID_OPERATION;
4476 }
4477 }
4478 }
4479 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004480 }
4481 }
4482
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004483 /**
4484 * The request should be presorted so accesses in HAL
4485 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4486 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004487 captureRequest->mSettingsList.begin()->metadata.sort();
4488 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004489 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004490 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004491 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4492
4493 IF_ALOGV() {
4494 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4495 find_camera_metadata_ro_entry(
4496 halRequest->settings,
4497 ANDROID_CONTROL_AF_TRIGGER,
4498 &e
4499 );
4500 if (e.count > 0) {
4501 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4502 __FUNCTION__,
4503 halRequest->frame_number,
4504 e.data.u8[0]);
4505 }
4506 }
4507 } else {
4508 // leave request.settings NULL to indicate 'reuse latest given'
4509 ALOGVV("%s: Request settings are REUSED",
4510 __FUNCTION__);
4511 }
4512
Emilian Peevaebbe412018-01-15 13:53:24 +00004513 if (captureRequest->mSettingsList.size() > 1) {
4514 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4515 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004516 if (newRequest) {
4517 halRequest->physcam_settings =
4518 new const camera_metadata* [halRequest->num_physcam_settings];
4519 } else {
4520 halRequest->physcam_settings = nullptr;
4521 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004522 auto it = ++captureRequest->mSettingsList.begin();
4523 size_t i = 0;
4524 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4525 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004526 if (newRequest) {
4527 it->metadata.sort();
4528 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4529 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004530 }
4531 }
4532
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004533 uint32_t totalNumBuffers = 0;
4534
4535 // Fill in buffers
4536 if (captureRequest->mInputStream != NULL) {
4537 halRequest->input_buffer = &captureRequest->mInputBuffer;
4538 totalNumBuffers += 1;
4539 } else {
4540 halRequest->input_buffer = NULL;
4541 }
4542
4543 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4544 captureRequest->mOutputStreams.size());
4545 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004546 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004547
4548 sp<Camera3Device> parent = mParent.promote();
4549 if (parent == NULL) {
4550 // Should not happen, and nowhere to send errors to, so just log it
4551 CLOGE("RequestThread: Parent is gone");
4552 return INVALID_OPERATION;
4553 }
4554 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4555
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004556 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004557 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004558 sp<Camera3OutputStreamInterface> outputStream =
4559 captureRequest->mOutputStreams.editItemAt(j);
4560 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004561
4562 // Prepare video buffers for high speed recording on the first video request.
4563 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4564 // Only try to prepare video stream on the first video request.
4565 mPrepareVideoStream = false;
4566
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004567 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4568 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004569 while (res == NOT_ENOUGH_DATA) {
4570 res = outputStream->prepareNextBuffer();
4571 }
4572 if (res != OK) {
4573 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4574 __FUNCTION__, strerror(-res), res);
4575 outputStream->cancelPrepare();
4576 }
4577 }
4578
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004579 std::vector<size_t> uniqueSurfaceIds;
4580 res = outputStream->getUniqueSurfaceIds(
4581 captureRequest->mOutputSurfaces[streamId],
4582 &uniqueSurfaceIds);
4583 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4584 if (res != OK && res != INVALID_OPERATION) {
4585 ALOGE("%s: failed to query stream %d unique surface IDs",
4586 __FUNCTION__, streamId);
4587 return res;
4588 }
4589 if (res == OK) {
4590 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4591 }
4592
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004593 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004594 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004595 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004596 return TIMED_OUT;
4597 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004598 // HAL will request buffer through requestStreamBuffer API
4599 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
4600 buffer.stream = outputStream->asHalStream();
4601 buffer.buffer = nullptr;
4602 buffer.status = CAMERA3_BUFFER_STATUS_OK;
4603 buffer.acquire_fence = -1;
4604 buffer.release_fence = -1;
4605 } else {
4606 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4607 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004608 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004609 if (res != OK) {
4610 // Can't get output buffer from gralloc queue - this could be due to
4611 // abandoned queue or other consumer misbehavior, so not a fatal
4612 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004613 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004614 " %s (%d)", strerror(-res), res);
4615
4616 return TIMED_OUT;
4617 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004618 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004619
4620 {
4621 sp<Camera3Device> parent = mParent.promote();
4622 if (parent != nullptr) {
4623 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4624 for (const auto& settings : captureRequest->mSettingsList) {
4625 if ((streamCameraId.isEmpty() &&
4626 parent->getId() == settings.cameraId.c_str()) ||
4627 streamCameraId == settings.cameraId.c_str()) {
4628 outputStream->fireBufferRequestForFrameNumber(
4629 captureRequest->mResultExtras.frameNumber,
4630 settings.metadata);
4631 }
4632 }
4633 }
4634 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004635
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004636 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4637
4638 if (!physicalCameraId.isEmpty()) {
4639 // Physical stream isn't supported for input request.
4640 if (halRequest->input_buffer) {
4641 CLOGE("Physical stream is not supported for input request");
4642 return INVALID_OPERATION;
4643 }
4644 requestedPhysicalCameras.insert(physicalCameraId);
4645 }
4646 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004647 }
4648 totalNumBuffers += halRequest->num_output_buffers;
4649
4650 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004651 // If this request list is for constrained high speed recording (not
4652 // preview), and the current request is not the last one in the batch,
4653 // do not send callback to the app.
4654 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004655 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004656 hasCallback = false;
4657 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004658 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004659 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01004660 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4661 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4662 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4663 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4664 isStillCapture = true;
4665 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4666 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004667
4668 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
4669 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4670 isZslCapture = true;
4671 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004672 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004673 res = parent->registerInFlight(halRequest->frame_number,
4674 totalNumBuffers, captureRequest->mResultExtras,
4675 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004676 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004677 calculateMaxExpectedDuration(halRequest->settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004678 requestedPhysicalCameras, isStillCapture, isZslCapture,
4679 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004680 (mUseHalBufManager) ? uniqueSurfaceIdMap :
4681 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004682 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4683 ", burstId = %" PRId32 ".",
4684 __FUNCTION__,
4685 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4686 captureRequest->mResultExtras.burstId);
4687 if (res != OK) {
4688 SET_ERR("RequestThread: Unable to register new in-flight request:"
4689 " %s (%d)", strerror(-res), res);
4690 return INVALID_OPERATION;
4691 }
4692 }
4693
4694 return OK;
4695}
4696
Igor Murashkin1e479c02013-09-06 16:55:14 -07004697CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004698 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004699 Mutex::Autolock al(mLatestRequestMutex);
4700
4701 ALOGV("RequestThread::%s", __FUNCTION__);
4702
4703 return mLatestRequest;
4704}
4705
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004706bool Camera3Device::RequestThread::isStreamPending(
4707 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004708 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004709 Mutex::Autolock l(mRequestLock);
4710
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004711 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004712 if (!nextRequest.submitted) {
4713 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4714 if (stream == s) return true;
4715 }
4716 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004717 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004718 }
4719
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004720 for (const auto& request : mRequestQueue) {
4721 for (const auto& s : request->mOutputStreams) {
4722 if (stream == s) return true;
4723 }
4724 if (stream == request->mInputStream) return true;
4725 }
4726
4727 for (const auto& request : mRepeatingRequests) {
4728 for (const auto& s : request->mOutputStreams) {
4729 if (stream == s) return true;
4730 }
4731 if (stream == request->mInputStream) return true;
4732 }
4733
4734 return false;
4735}
Jianing Weicb0652e2014-03-12 18:29:36 -07004736
Emilian Peev40ead602017-09-26 15:46:36 +01004737bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4738 ATRACE_CALL();
4739 Mutex::Autolock l(mRequestLock);
4740
4741 for (const auto& nextRequest : mNextRequests) {
4742 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4743 if (s.first == streamId) {
4744 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4745 if (it != s.second.end()) {
4746 return true;
4747 }
4748 }
4749 }
4750 }
4751
4752 for (const auto& request : mRequestQueue) {
4753 for (const auto& s : request->mOutputSurfaces) {
4754 if (s.first == streamId) {
4755 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4756 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004757 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004758 }
4759 }
4760 }
4761 }
4762
4763 for (const auto& request : mRepeatingRequests) {
4764 for (const auto& s : request->mOutputSurfaces) {
4765 if (s.first == streamId) {
4766 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4767 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004768 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004769 }
4770 }
4771 }
4772 }
4773
4774 return false;
4775}
4776
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004777void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4778 if (!mUseHalBufManager) {
4779 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4780 return;
4781 }
4782
4783 Mutex::Autolock pl(mPauseLock);
4784 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004785 mInterface->signalPipelineDrain(streamIds);
4786 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004787 }
4788 // If request thread is still busy, wait until paused then notify HAL
4789 mNotifyPipelineDrain = true;
4790 mStreamIdsToBeDrained = streamIds;
4791}
4792
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004793void Camera3Device::RequestThread::clearPreviousRequest() {
4794 Mutex::Autolock l(mRequestLock);
4795 mPrevRequest.clear();
4796}
4797
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004798status_t Camera3Device::RequestThread::switchToOffline(
4799 const std::vector<int32_t>& streamsToKeep,
4800 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004801 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4802 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004803 Mutex::Autolock l(mRequestLock);
4804 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
4805
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004806 // Wait until request thread is fully stopped
4807 // TBD: check if request thread is being paused by other APIs (shouldn't be)
4808
4809 // We could also check for mRepeatingRequests.empty(), but the API interface
4810 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
4811 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004812 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4813 while (!queueEmpty) {
4814 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
4815 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004816 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004817 return res;
4818 } else if (res != OK) {
4819 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
4820 __FUNCTION__, strerror(-res), res);
4821 return res;
4822 }
4823 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4824 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004825
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004826 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004827 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004828}
4829
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004830status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4831 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4832 ATRACE_CALL();
4833 Mutex::Autolock l(mTriggerMutex);
4834 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4835 return BAD_VALUE;
4836 }
4837 mRotateAndCropOverride = rotateAndCropValue;
4838 return OK;
4839}
4840
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004841nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004842 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004843 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004844 return mExpectedInflightDuration > kMinInflightDuration ?
4845 mExpectedInflightDuration : kMinInflightDuration;
4846}
4847
Emilian Peevaebbe412018-01-15 13:53:24 +00004848void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4849 camera3_capture_request_t *halRequest) {
4850 if ((request == nullptr) || (halRequest == nullptr)) {
4851 ALOGE("%s: Invalid request!", __FUNCTION__);
4852 return;
4853 }
4854
4855 if (halRequest->num_physcam_settings > 0) {
4856 if (halRequest->physcam_id != nullptr) {
4857 delete [] halRequest->physcam_id;
4858 halRequest->physcam_id = nullptr;
4859 }
4860 if (halRequest->physcam_settings != nullptr) {
4861 auto it = ++(request->mSettingsList.begin());
4862 size_t i = 0;
4863 for (; it != request->mSettingsList.end(); it++, i++) {
4864 it->metadata.unlock(halRequest->physcam_settings[i]);
4865 }
4866 delete [] halRequest->physcam_settings;
4867 halRequest->physcam_settings = nullptr;
4868 }
4869 }
4870}
4871
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004872void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4873 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004874 return;
4875 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004876
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004877 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004878 // Skip the ones that have been submitted successfully.
4879 if (nextRequest.submitted) {
4880 continue;
4881 }
4882
4883 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4884 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4885 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4886
4887 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004888 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004889 }
4890
Emilian Peevaebbe412018-01-15 13:53:24 +00004891 cleanupPhysicalSettings(captureRequest, halRequest);
4892
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004893 if (captureRequest->mInputStream != NULL) {
4894 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4895 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4896 }
4897
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004898 // No output buffer can be returned when using HAL buffer manager
4899 if (!mUseHalBufManager) {
4900 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4901 //Buffers that failed processing could still have
4902 //valid acquire fence.
4903 int acquireFence = (*outputBuffers)[i].acquire_fence;
4904 if (0 <= acquireFence) {
4905 close(acquireFence);
4906 outputBuffers->editItemAt(i).acquire_fence = -1;
4907 }
4908 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4909 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
4910 /*timestampIncreasing*/true, std::vector<size_t> (),
4911 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004912 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004913 }
4914
4915 if (sendRequestError) {
4916 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004917 sp<NotificationListener> listener = mListener.promote();
4918 if (listener != NULL) {
4919 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004920 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004921 captureRequest->mResultExtras);
4922 }
4923 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004924
4925 // Remove yet-to-be submitted inflight request from inflightMap
4926 {
4927 sp<Camera3Device> parent = mParent.promote();
4928 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004929 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004930 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4931 if (idx >= 0) {
4932 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4933 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4934 parent->removeInFlightMapEntryLocked(idx);
4935 }
4936 }
4937 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004938 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004939
4940 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004941 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004942}
4943
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004944void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004945 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004946 // Optimized a bit for the simple steady-state case (single repeating
4947 // request), to avoid putting that request in the queue temporarily.
4948 Mutex::Autolock l(mRequestLock);
4949
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004950 assert(mNextRequests.empty());
4951
4952 NextRequest nextRequest;
4953 nextRequest.captureRequest = waitForNextRequestLocked();
4954 if (nextRequest.captureRequest == nullptr) {
4955 return;
4956 }
4957
4958 nextRequest.halRequest = camera3_capture_request_t();
4959 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004960 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004961
4962 // Wait for additional requests
4963 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4964
4965 for (size_t i = 1; i < batchSize; i++) {
4966 NextRequest additionalRequest;
4967 additionalRequest.captureRequest = waitForNextRequestLocked();
4968 if (additionalRequest.captureRequest == nullptr) {
4969 break;
4970 }
4971
4972 additionalRequest.halRequest = camera3_capture_request_t();
4973 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004974 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004975 }
4976
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004977 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004978 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004979 mNextRequests.size(), batchSize);
4980 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004981 }
4982
4983 return;
4984}
4985
4986sp<Camera3Device::CaptureRequest>
4987 Camera3Device::RequestThread::waitForNextRequestLocked() {
4988 status_t res;
4989 sp<CaptureRequest> nextRequest;
4990
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004991 while (mRequestQueue.empty()) {
4992 if (!mRepeatingRequests.empty()) {
4993 // Always atomically enqueue all requests in a repeating request
4994 // list. Guarantees a complete in-sequence set of captures to
4995 // application.
4996 const RequestList &requests = mRepeatingRequests;
4997 RequestList::const_iterator firstRequest =
4998 requests.begin();
4999 nextRequest = *firstRequest;
5000 mRequestQueue.insert(mRequestQueue.end(),
5001 ++firstRequest,
5002 requests.end());
5003 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005004
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005005 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005006
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005007 break;
5008 }
5009
5010 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5011
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005012 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5013 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005014 Mutex::Autolock pl(mPauseLock);
5015 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005016 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005017 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005018 if (mNotifyPipelineDrain) {
5019 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5020 mNotifyPipelineDrain = false;
5021 mStreamIdsToBeDrained.clear();
5022 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005023 // Let the tracker know
5024 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5025 if (statusTracker != 0) {
5026 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5027 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005028 sp<Camera3Device> parent = mParent.promote();
5029 if (parent != nullptr) {
5030 parent->mRequestBufferSM.onRequestThreadPaused();
5031 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005032 }
5033 // Stop waiting for now and let thread management happen
5034 return NULL;
5035 }
5036 }
5037
5038 if (nextRequest == NULL) {
5039 // Don't have a repeating request already in hand, so queue
5040 // must have an entry now.
5041 RequestList::iterator firstRequest =
5042 mRequestQueue.begin();
5043 nextRequest = *firstRequest;
5044 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005045 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5046 sp<NotificationListener> listener = mListener.promote();
5047 if (listener != NULL) {
5048 listener->notifyRequestQueueEmpty();
5049 }
5050 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005051 }
5052
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005053 // In case we've been unpaused by setPaused clearing mDoPause, need to
5054 // update internal pause state (capture/setRepeatingRequest unpause
5055 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005056 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005057 if (mPaused) {
5058 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5059 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5060 if (statusTracker != 0) {
5061 statusTracker->markComponentActive(mStatusId);
5062 }
5063 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005064 mPaused = false;
5065
5066 // Check if we've reconfigured since last time, and reset the preview
5067 // request if so. Can't use 'NULL request == repeat' across configure calls.
5068 if (mReconfigured) {
5069 mPrevRequest.clear();
5070 mReconfigured = false;
5071 }
5072
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005073 if (nextRequest != NULL) {
5074 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005075 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5076 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005077
5078 // Since RequestThread::clear() removes buffers from the input stream,
5079 // get the right buffer here before unlocking mRequestLock
5080 if (nextRequest->mInputStream != NULL) {
5081 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5082 if (res != OK) {
5083 // Can't get input buffer from gralloc queue - this could be due to
5084 // disconnected queue or other producer misbehavior, so not a fatal
5085 // error
5086 ALOGE("%s: Can't get input buffer, skipping request:"
5087 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005088
5089 sp<NotificationListener> listener = mListener.promote();
5090 if (listener != NULL) {
5091 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005092 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005093 nextRequest->mResultExtras);
5094 }
5095 return NULL;
5096 }
5097 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005098 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005099
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005100 return nextRequest;
5101}
5102
5103bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005104 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005105 status_t res;
5106 Mutex::Autolock l(mPauseLock);
5107 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005108 if (mPaused == false) {
5109 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005110 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005111 if (mNotifyPipelineDrain) {
5112 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5113 mNotifyPipelineDrain = false;
5114 mStreamIdsToBeDrained.clear();
5115 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005116 // Let the tracker know
5117 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5118 if (statusTracker != 0) {
5119 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5120 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005121 sp<Camera3Device> parent = mParent.promote();
5122 if (parent != nullptr) {
5123 parent->mRequestBufferSM.onRequestThreadPaused();
5124 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005125 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005126
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005127 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005128 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005129 return true;
5130 }
5131 }
5132 // We don't set mPaused to false here, because waitForNextRequest needs
5133 // to further manage the paused state in case of starvation.
5134 return false;
5135}
5136
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005137void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005138 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005139 // With work to do, mark thread as unpaused.
5140 // If paused by request (setPaused), don't resume, to avoid
5141 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005142 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005143 Mutex::Autolock p(mPauseLock);
5144 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005145 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5146 if (mPaused) {
5147 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5148 if (statusTracker != 0) {
5149 statusTracker->markComponentActive(mStatusId);
5150 }
5151 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005152 mPaused = false;
5153 }
5154}
5155
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005156void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5157 sp<Camera3Device> parent = mParent.promote();
5158 if (parent != NULL) {
5159 va_list args;
5160 va_start(args, fmt);
5161
5162 parent->setErrorStateV(fmt, args);
5163
5164 va_end(args);
5165 }
5166}
5167
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005168status_t Camera3Device::RequestThread::insertTriggers(
5169 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005170 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005171 Mutex::Autolock al(mTriggerMutex);
5172
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005173 sp<Camera3Device> parent = mParent.promote();
5174 if (parent == NULL) {
5175 CLOGE("RequestThread: Parent is gone");
5176 return DEAD_OBJECT;
5177 }
5178
Emilian Peevaebbe412018-01-15 13:53:24 +00005179 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005180 size_t count = mTriggerMap.size();
5181
5182 for (size_t i = 0; i < count; ++i) {
5183 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005184 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005185
5186 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5187 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5188 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005189 if (isAeTrigger) {
5190 request->mResultExtras.precaptureTriggerId = triggerId;
5191 mCurrentPreCaptureTriggerId = triggerId;
5192 } else {
5193 request->mResultExtras.afTriggerId = triggerId;
5194 mCurrentAfTriggerId = triggerId;
5195 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005196 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005197 }
5198
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005199 camera_metadata_entry entry = metadata.find(tag);
5200
5201 if (entry.count > 0) {
5202 /**
5203 * Already has an entry for this trigger in the request.
5204 * Rewrite it with our requested trigger value.
5205 */
5206 RequestTrigger oldTrigger = trigger;
5207
5208 oldTrigger.entryValue = entry.data.u8[0];
5209
5210 mTriggerReplacedMap.add(tag, oldTrigger);
5211 } else {
5212 /**
5213 * More typical, no trigger entry, so we just add it
5214 */
5215 mTriggerRemovedMap.add(tag, trigger);
5216 }
5217
5218 status_t res;
5219
5220 switch (trigger.getTagType()) {
5221 case TYPE_BYTE: {
5222 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5223 res = metadata.update(tag,
5224 &entryValue,
5225 /*count*/1);
5226 break;
5227 }
5228 case TYPE_INT32:
5229 res = metadata.update(tag,
5230 &trigger.entryValue,
5231 /*count*/1);
5232 break;
5233 default:
5234 ALOGE("%s: Type not supported: 0x%x",
5235 __FUNCTION__,
5236 trigger.getTagType());
5237 return INVALID_OPERATION;
5238 }
5239
5240 if (res != OK) {
5241 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5242 ", value %d", __FUNCTION__, trigger.getTagName(),
5243 trigger.entryValue);
5244 return res;
5245 }
5246
5247 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5248 trigger.getTagName(),
5249 trigger.entryValue);
5250 }
5251
5252 mTriggerMap.clear();
5253
5254 return count;
5255}
5256
5257status_t Camera3Device::RequestThread::removeTriggers(
5258 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005259 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005260 Mutex::Autolock al(mTriggerMutex);
5261
Emilian Peevaebbe412018-01-15 13:53:24 +00005262 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005263
5264 /**
5265 * Replace all old entries with their old values.
5266 */
5267 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5268 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5269
5270 status_t res;
5271
5272 uint32_t tag = trigger.metadataTag;
5273 switch (trigger.getTagType()) {
5274 case TYPE_BYTE: {
5275 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5276 res = metadata.update(tag,
5277 &entryValue,
5278 /*count*/1);
5279 break;
5280 }
5281 case TYPE_INT32:
5282 res = metadata.update(tag,
5283 &trigger.entryValue,
5284 /*count*/1);
5285 break;
5286 default:
5287 ALOGE("%s: Type not supported: 0x%x",
5288 __FUNCTION__,
5289 trigger.getTagType());
5290 return INVALID_OPERATION;
5291 }
5292
5293 if (res != OK) {
5294 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5295 ", trigger value %d", __FUNCTION__,
5296 trigger.getTagName(), trigger.entryValue);
5297 return res;
5298 }
5299 }
5300 mTriggerReplacedMap.clear();
5301
5302 /**
5303 * Remove all new entries.
5304 */
5305 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5306 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5307 status_t res = metadata.erase(trigger.metadataTag);
5308
5309 if (res != OK) {
5310 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5311 ", trigger value %d", __FUNCTION__,
5312 trigger.getTagName(), trigger.entryValue);
5313 return res;
5314 }
5315 }
5316 mTriggerRemovedMap.clear();
5317
5318 return OK;
5319}
5320
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005321status_t Camera3Device::RequestThread::addDummyTriggerIds(
5322 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005323 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005324 static const int32_t dummyTriggerId = 1;
5325 status_t res;
5326
Emilian Peevaebbe412018-01-15 13:53:24 +00005327 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005328
5329 // If AF trigger is active, insert a dummy AF trigger ID if none already
5330 // exists
5331 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5332 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5333 if (afTrigger.count > 0 &&
5334 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5335 afId.count == 0) {
5336 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5337 if (res != OK) return res;
5338 }
5339
5340 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5341 // if none already exists
5342 camera_metadata_entry pcTrigger =
5343 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5344 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5345 if (pcTrigger.count > 0 &&
5346 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5347 pcId.count == 0) {
5348 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5349 &dummyTriggerId, 1);
5350 if (res != OK) return res;
5351 }
5352
5353 return OK;
5354}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005355
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005356bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5357 const sp<CaptureRequest> &request) {
5358 ATRACE_CALL();
5359
5360 if (request->mRotateAndCropAuto) {
5361 Mutex::Autolock l(mTriggerMutex);
5362 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5363
5364 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5365 if (rotateAndCropEntry.count > 0) {
5366 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5367 return false;
5368 } else {
5369 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5370 return true;
5371 }
5372 } else {
5373 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5374 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5375 &rotateAndCrop_u8, 1);
5376 return true;
5377 }
5378 }
5379 return false;
5380}
5381
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005382/**
5383 * PreparerThread inner class methods
5384 */
5385
5386Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005387 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005388 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005389}
5390
5391Camera3Device::PreparerThread::~PreparerThread() {
5392 Thread::requestExitAndWait();
5393 if (mCurrentStream != nullptr) {
5394 mCurrentStream->cancelPrepare();
5395 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5396 mCurrentStream.clear();
5397 }
5398 clear();
5399}
5400
Ruben Brunkc78ac262015-08-13 17:58:46 -07005401status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005402 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005403 status_t res;
5404
5405 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005406 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005407
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005408 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005409 if (res == OK) {
5410 // No preparation needed, fire listener right off
5411 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005412 if (listener != NULL) {
5413 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005414 }
5415 return OK;
5416 } else if (res != NOT_ENOUGH_DATA) {
5417 return res;
5418 }
5419
5420 // Need to prepare, start up thread if necessary
5421 if (!mActive) {
5422 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5423 // isn't running
5424 Thread::requestExitAndWait();
5425 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5426 if (res != OK) {
5427 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005428 if (listener != NULL) {
5429 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005430 }
5431 return res;
5432 }
5433 mCancelNow = false;
5434 mActive = true;
5435 ALOGV("%s: Preparer stream started", __FUNCTION__);
5436 }
5437
5438 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005439 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005440 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5441
5442 return OK;
5443}
5444
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005445void Camera3Device::PreparerThread::pause() {
5446 ATRACE_CALL();
5447
5448 Mutex::Autolock l(mLock);
5449
5450 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5451 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5452 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5453 int currentMaxCount = mCurrentMaxCount;
5454 mPendingStreams.clear();
5455 mCancelNow = true;
5456 while (mActive) {
5457 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5458 if (res == TIMED_OUT) {
5459 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5460 return;
5461 } else if (res != OK) {
5462 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5463 return;
5464 }
5465 }
5466
5467 //Check whether the prepare thread was able to complete the current
5468 //stream. In case work is still pending emplace it along with the rest
5469 //of the streams in the pending list.
5470 if (currentStream != nullptr) {
5471 if (!mCurrentPrepareComplete) {
5472 pendingStreams.emplace(currentMaxCount, currentStream);
5473 }
5474 }
5475
5476 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5477 for (const auto& it : mPendingStreams) {
5478 it.second->cancelPrepare();
5479 }
5480}
5481
5482status_t Camera3Device::PreparerThread::resume() {
5483 ATRACE_CALL();
5484 status_t res;
5485
5486 Mutex::Autolock l(mLock);
5487 sp<NotificationListener> listener = mListener.promote();
5488
5489 if (mActive) {
5490 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5491 return NO_INIT;
5492 }
5493
5494 auto it = mPendingStreams.begin();
5495 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005496 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005497 if (res == OK) {
5498 if (listener != NULL) {
5499 listener->notifyPrepared(it->second->getId());
5500 }
5501 it = mPendingStreams.erase(it);
5502 } else if (res != NOT_ENOUGH_DATA) {
5503 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5504 res, strerror(-res));
5505 it = mPendingStreams.erase(it);
5506 } else {
5507 it++;
5508 }
5509 }
5510
5511 if (mPendingStreams.empty()) {
5512 return OK;
5513 }
5514
5515 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5516 if (res != OK) {
5517 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5518 __FUNCTION__, res, strerror(-res));
5519 return res;
5520 }
5521 mCancelNow = false;
5522 mActive = true;
5523 ALOGV("%s: Preparer stream started", __FUNCTION__);
5524
5525 return OK;
5526}
5527
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005528status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005529 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005530 Mutex::Autolock l(mLock);
5531
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005532 for (const auto& it : mPendingStreams) {
5533 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005534 }
5535 mPendingStreams.clear();
5536 mCancelNow = true;
5537
5538 return OK;
5539}
5540
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005541void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005542 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005543 Mutex::Autolock l(mLock);
5544 mListener = listener;
5545}
5546
5547bool Camera3Device::PreparerThread::threadLoop() {
5548 status_t res;
5549 {
5550 Mutex::Autolock l(mLock);
5551 if (mCurrentStream == nullptr) {
5552 // End thread if done with work
5553 if (mPendingStreams.empty()) {
5554 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5555 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5556 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5557 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005558 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005559 return false;
5560 }
5561
5562 // Get next stream to prepare
5563 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005564 mCurrentStream = it->second;
5565 mCurrentMaxCount = it->first;
5566 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005567 mPendingStreams.erase(it);
5568 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5569 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5570 } else if (mCancelNow) {
5571 mCurrentStream->cancelPrepare();
5572 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5573 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5574 mCurrentStream.clear();
5575 mCancelNow = false;
5576 return true;
5577 }
5578 }
5579
5580 res = mCurrentStream->prepareNextBuffer();
5581 if (res == NOT_ENOUGH_DATA) return true;
5582 if (res != OK) {
5583 // Something bad happened; try to recover by cancelling prepare and
5584 // signalling listener anyway
5585 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5586 mCurrentStream->getId(), res, strerror(-res));
5587 mCurrentStream->cancelPrepare();
5588 }
5589
5590 // This stream has finished, notify listener
5591 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005592 sp<NotificationListener> listener = mListener.promote();
5593 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005594 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5595 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005596 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005597 }
5598
5599 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5600 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005601 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005602
5603 return true;
5604}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005605
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005606status_t Camera3Device::RequestBufferStateMachine::initialize(
5607 sp<camera3::StatusTracker> statusTracker) {
5608 if (statusTracker == nullptr) {
5609 ALOGE("%s: statusTracker is null", __FUNCTION__);
5610 return BAD_VALUE;
5611 }
5612
5613 std::lock_guard<std::mutex> lock(mLock);
5614 mStatusTracker = statusTracker;
5615 mRequestBufferStatusId = statusTracker->addComponent();
5616 return OK;
5617}
5618
5619bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5620 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005621 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005622 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005623 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005624 return true;
5625 }
5626 return false;
5627}
5628
5629void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5630 std::lock_guard<std::mutex> lock(mLock);
5631 if (!mRequestBufferOngoing) {
5632 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5633 return;
5634 }
5635 mRequestBufferOngoing = false;
5636 if (mStatus == RB_STATUS_PENDING_STOP) {
5637 checkSwitchToStopLocked();
5638 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005639 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005640}
5641
5642void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5643 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005644 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005645 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005646 return;
5647}
5648
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005649void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005650 std::lock_guard<std::mutex> lock(mLock);
5651 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005652 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5653 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005654 mInflightMapEmpty = false;
5655 if (mStatus == RB_STATUS_STOPPED) {
5656 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005657 }
5658 return;
5659}
5660
5661void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5662 std::lock_guard<std::mutex> lock(mLock);
5663 mRequestThreadPaused = true;
5664 if (mStatus == RB_STATUS_PENDING_STOP) {
5665 checkSwitchToStopLocked();
5666 }
5667 return;
5668}
5669
5670void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5671 std::lock_guard<std::mutex> lock(mLock);
5672 mInflightMapEmpty = true;
5673 if (mStatus == RB_STATUS_PENDING_STOP) {
5674 checkSwitchToStopLocked();
5675 }
5676 return;
5677}
5678
5679void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5680 std::lock_guard<std::mutex> lock(mLock);
5681 if (!checkSwitchToStopLocked()) {
5682 mStatus = RB_STATUS_PENDING_STOP;
5683 }
5684 return;
5685}
5686
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005687bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5688 std::lock_guard<std::mutex> lock(mLock);
5689 if (mRequestBufferOngoing) {
5690 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5691 __FUNCTION__);
5692 return false;
5693 }
5694 mSwitchedToOffline = true;
5695 mInflightMapEmpty = true;
5696 mRequestThreadPaused = true;
5697 mStatus = RB_STATUS_STOPPED;
5698 return true;
5699}
5700
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005701void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5702 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5703 if (statusTracker != nullptr) {
5704 if (active) {
5705 statusTracker->markComponentActive(mRequestBufferStatusId);
5706 } else {
5707 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5708 }
5709 }
5710}
5711
5712bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5713 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5714 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005715 return true;
5716 }
5717 return false;
5718}
5719
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005720bool Camera3Device::startRequestBuffer() {
5721 return mRequestBufferSM.startRequestBuffer();
5722}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005723
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005724void Camera3Device::endRequestBuffer() {
5725 mRequestBufferSM.endRequestBuffer();
5726}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005727
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005728nsecs_t Camera3Device::getWaitDuration() {
5729 return kBaseGetBufferWait + getExpectedInFlightDuration();
5730}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005731
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005732void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5733 mInterface->getInflightBufferKeys(out);
5734}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005735
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005736void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5737 mInterface->getInflightRequestBufferKeys(out);
5738}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005739
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005740std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5741 std::vector<sp<Camera3StreamInterface>> ret;
5742 bool hasInputStream = mInputStream != nullptr;
5743 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5744 if (hasInputStream) {
5745 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005746 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005747 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5748 ret.push_back(mOutputStreams[i]);
5749 }
5750 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5751 ret.push_back(mDeletedStreams[i]);
5752 }
5753 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005754}
5755
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005756status_t Camera3Device::switchToOffline(
5757 const std::vector<int32_t>& streamsToKeep,
5758 /*out*/ sp<CameraOfflineSessionBase>* session) {
5759 ATRACE_CALL();
5760 if (session == nullptr) {
5761 ALOGE("%s: session must not be null", __FUNCTION__);
5762 return BAD_VALUE;
5763 }
5764
5765 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005766
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005767 bool hasInputStream = mInputStream != nullptr;
5768 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
5769 bool inputStreamSupportsOffline = hasInputStream ?
5770 mInputStream->getOfflineProcessingSupport() : false;
5771 auto outputStreamIds = mOutputStreams.getStreamIds();
5772 auto streamIds = outputStreamIds;
5773 if (hasInputStream) {
5774 streamIds.push_back(mInputStream->getId());
5775 }
5776
5777 // Check all streams in streamsToKeep supports offline mode
5778 for (auto id : streamsToKeep) {
5779 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5780 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
5781 return BAD_VALUE;
5782 } else if (id == inputStreamId) {
5783 if (!inputStreamSupportsOffline) {
5784 ALOGE("%s: input stream %d cannot be switched to offline",
5785 __FUNCTION__, id);
5786 return BAD_VALUE;
5787 }
5788 } else {
5789 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
5790 if (!stream->getOfflineProcessingSupport()) {
5791 ALOGE("%s: output stream %d cannot be switched to offline",
5792 __FUNCTION__, id);
5793 return BAD_VALUE;
5794 }
5795 }
5796 }
5797
5798 // TODO: block surface sharing and surface group streams until we can support them
5799
5800 // Stop repeating request, wait until all remaining requests are submitted, then call into
5801 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005802 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
5803 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005804 camera3::BufferRecords bufferRecords;
5805 status_t ret = mRequestThread->switchToOffline(
5806 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005807
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005808 if (ret != OK) {
5809 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
5810 return ret;
5811 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005812
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005813 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
5814 if (!succ) {
5815 SET_ERR("HAL must not be calling requestStreamBuffers call");
5816 // TODO: block ALL callbacks from HAL till app configured new streams?
5817 return UNKNOWN_ERROR;
5818 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005819
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005820 // Verify offlineSessionInfo
5821 std::vector<int32_t> offlineStreamIds;
5822 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
5823 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5824 // verify stream IDs
5825 int32_t id = offlineStream.id;
5826 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5827 SET_ERR("stream ID %d not found!", id);
5828 return UNKNOWN_ERROR;
5829 }
5830
5831 // When not using HAL buf manager, only allow streams requested by app to be preserved
5832 if (!mUseHalBufManager) {
5833 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
5834 SET_ERR("stream ID %d must not be switched to offline!", id);
5835 return UNKNOWN_ERROR;
5836 }
5837 }
5838
5839 offlineStreamIds.push_back(id);
5840 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
5841 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
5842 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
5843 // Verify number of outstanding buffers
5844 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
5845 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
5846 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
5847 return UNKNOWN_ERROR;
5848 }
5849 }
5850
5851 // Verify all streams to be deleted don't have any outstanding buffers
5852 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5853 inputStreamId) == offlineStreamIds.end()) {
5854 if (mInputStream->hasOutstandingBuffers()) {
5855 SET_ERR("Input stream %d still has %zu outstanding buffer!",
5856 inputStreamId, mInputStream->getOutstandingBuffersCount());
5857 return UNKNOWN_ERROR;
5858 }
5859 }
5860
5861 for (const auto& outStreamId : outputStreamIds) {
5862 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5863 outStreamId) == offlineStreamIds.end()) {
5864 auto outStream = mOutputStreams.get(outStreamId);
5865 if (outStream->hasOutstandingBuffers()) {
5866 SET_ERR("Output stream %d still has %zu outstanding buffer!",
5867 outStreamId, outStream->getOutstandingBuffersCount());
5868 return UNKNOWN_ERROR;
5869 }
5870 }
5871 }
5872
5873 InFlightRequestMap offlineReqs;
5874 // Verify inflight requests and their pending buffers
5875 {
5876 std::lock_guard<std::mutex> l(mInFlightLock);
5877 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
5878 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
5879 if (idx == NAME_NOT_FOUND) {
5880 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
5881 return UNKNOWN_ERROR;
5882 }
5883
5884 const auto& inflightReq = mInFlightMap.valueAt(idx);
5885 // TODO: check specific stream IDs
5886 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
5887 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
5888 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
5889 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
5890 return UNKNOWN_ERROR;
5891 }
5892 offlineReqs.add(offlineReq.frameNumber, inflightReq);
5893 }
5894 }
5895
5896 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005897 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005898 camera3::StreamSet offlineStreamSet;
5899 sp<camera3::Camera3Stream> inputStream;
5900 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5901 int32_t id = offlineStream.id;
5902 if (mInputStream != nullptr && id == mInputStream->getId()) {
5903 inputStream = mInputStream;
5904 } else {
5905 offlineStreamSet.add(id, mOutputStreams.get(id));
5906 }
5907 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005908
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005909 // TODO: check if we need to lock before copying states
5910 // though technically no other thread should be talking to Camera3Device at this point
5911 Camera3OfflineStates offlineStates(
5912 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wang730a7912020-05-07 11:59:02 -07005913 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
5914 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
5915 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
5916 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
5917 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
5918 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
5919 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005920
5921 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
5922 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
5923
5924 // Delete all streams that has been transferred to offline session
5925 Mutex::Autolock l(mLock);
5926 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5927 int32_t id = offlineStream.id;
5928 if (mInputStream != nullptr && id == mInputStream->getId()) {
5929 mInputStream.clear();
5930 } else {
5931 mOutputStreams.remove(id);
5932 }
5933 }
5934
5935 // disconnect all other streams and switch to UNCONFIGURED state
5936 if (mInputStream != nullptr) {
5937 ret = mInputStream->disconnect();
5938 if (ret != OK) {
5939 SET_ERR_L("disconnect input stream failed!");
5940 return UNKNOWN_ERROR;
5941 }
5942 }
5943
5944 for (auto streamId : mOutputStreams.getStreamIds()) {
5945 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
5946 ret = stream->disconnect();
5947 if (ret != OK) {
5948 SET_ERR_L("disconnect output stream %d failed!", streamId);
5949 return UNKNOWN_ERROR;
5950 }
5951 }
5952
5953 mInputStream.clear();
5954 mOutputStreams.clear();
5955 mNeedConfig = true;
5956 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
5957 mOperatingMode = NO_MODE;
5958 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005959 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005960
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005961 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005962 // TO be done by CameraDeviceClient/Camera3OfflineSession
5963 // register the offline client to camera service
5964 // Setup result passthing threads etc
5965 // Initialize offline session so HAL can start sending callback to it (result Fmq)
5966 // TODO: check how many onIdle callback will be sent
5967 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005968}
5969
Emilian Peevcc0b7952020-01-07 13:54:47 -08005970void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5971 ATRACE_CALL();
5972
5973 if (offlineStreamIds == nullptr) {
5974 return;
5975 }
5976
5977 Mutex::Autolock il(mInterfaceLock);
5978
5979 auto streamIds = mOutputStreams.getStreamIds();
5980 bool hasInputStream = mInputStream != nullptr;
5981 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5982 offlineStreamIds->push_back(mInputStream->getId());
5983 }
5984
5985 for (const auto & streamId : streamIds) {
5986 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5987 // Streams that use the camera buffer manager are currently not supported in
5988 // offline mode
5989 if (stream->getOfflineProcessingSupport() &&
5990 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5991 offlineStreamIds->push_back(streamId);
5992 }
5993 }
5994}
5995
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005996status_t Camera3Device::setRotateAndCropAutoBehavior(
5997 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5998 ATRACE_CALL();
5999 Mutex::Autolock il(mInterfaceLock);
6000 Mutex::Autolock l(mLock);
6001 if (mRequestThread == nullptr) {
6002 return INVALID_OPERATION;
6003 }
6004 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
6005}
6006
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006007}; // namespace android