blob: a898df9fb1613be769d08f1b533301a13fcca0e3 [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"
Greg Kaiser51b882c2020-06-10 05:41:44 +0000759 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800760 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Greg Kaiser51b882c2020-06-10 05:41:44 +0000761 r.numBuffersLeft);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700762 }
763 }
764 write(fd, lines.string(), lines.size());
765
Shuzhen Wang686f6442017-06-20 16:16:04 -0700766 if (mRequestThread != NULL) {
767 mRequestThread->dumpCaptureRequestLatency(fd,
768 " ProcessCaptureRequest latency histogram:");
769 }
770
Igor Murashkin1e479c02013-09-06 16:55:14 -0700771 {
772 lines = String8(" Last request sent:\n");
773 write(fd, lines.string(), lines.size());
774
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700775 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700776 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
777 }
778
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800779 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800780 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800781 "TEMPLATE_PREVIEW",
782 "TEMPLATE_STILL_CAPTURE",
783 "TEMPLATE_VIDEO_RECORD",
784 "TEMPLATE_VIDEO_SNAPSHOT",
785 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800786 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800787 };
788
789 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800790 camera_metadata_t *templateRequest = nullptr;
791 mInterface->constructDefaultRequestSettings(
792 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800793 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800794 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800795 lines.append(" Not supported\n");
796 write(fd, lines.string(), lines.size());
797 } else {
798 write(fd, lines.string(), lines.size());
799 dump_indented_camera_metadata(templateRequest,
800 fd, /*verbosity*/2, /*indentation*/8);
801 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800802 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800803 }
804 }
805
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700806 mTagMonitor.dumpMonitoredMetadata(fd);
807
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800808 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800809 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800810 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800811 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800812 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800813
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700814 if (gotLock) mLock.unlock();
815 if (gotInterfaceLock) mInterfaceLock.unlock();
816
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800817 return OK;
818}
819
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800820const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800821 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800822 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
823 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700824 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800825 mStatus == STATUS_ERROR ?
826 "when in error state" : "before init");
827 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700828 if (physicalId.isEmpty()) {
829 return mDeviceInfo;
830 } else {
831 std::string id(physicalId.c_str());
832 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
833 return mPhysicalDeviceInfoMap.at(id);
834 } else {
835 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
836 return mDeviceInfo;
837 }
838 }
839}
840
841const CameraMetadata& Camera3Device::info() const {
842 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800843 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800844}
845
Jianing Wei90e59c92014-03-12 18:29:36 -0700846status_t Camera3Device::checkStatusOkToCaptureLocked() {
847 switch (mStatus) {
848 case STATUS_ERROR:
849 CLOGE("Device has encountered a serious error");
850 return INVALID_OPERATION;
851 case STATUS_UNINITIALIZED:
852 CLOGE("Device not initialized");
853 return INVALID_OPERATION;
854 case STATUS_UNCONFIGURED:
855 case STATUS_CONFIGURED:
856 case STATUS_ACTIVE:
857 // OK
858 break;
859 default:
860 SET_ERR_L("Unexpected status: %d", mStatus);
861 return INVALID_OPERATION;
862 }
863 return OK;
864}
865
866status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000867 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700868 const std::list<const SurfaceMap> &surfaceMaps,
869 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700870 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700871 if (requestList == NULL) {
872 CLOGE("requestList cannot be NULL.");
873 return BAD_VALUE;
874 }
875
Jianing Weicb0652e2014-03-12 18:29:36 -0700876 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000877 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700878 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
879 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
880 ++metadataIt, ++surfaceMapIt) {
881 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700882 if (newRequest == 0) {
883 CLOGE("Can't create capture request");
884 return BAD_VALUE;
885 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700886
Shuzhen Wang9d066012016-09-30 11:30:20 -0700887 newRequest->mRepeating = repeating;
888
Jianing Weicb0652e2014-03-12 18:29:36 -0700889 // Setup burst Id and request Id
890 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800891 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
892 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700893 CLOGE("RequestID does not exist in metadata");
894 return BAD_VALUE;
895 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800896 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700897
Jianing Wei90e59c92014-03-12 18:29:36 -0700898 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700899
900 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700901 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700902 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
903 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
904 return BAD_VALUE;
905 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700906
907 // Setup batch size if this is a high speed video recording request.
908 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
909 auto firstRequest = requestList->begin();
910 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
911 if (outputStream->isVideoStream()) {
912 (*firstRequest)->mBatchSize = requestList->size();
913 break;
914 }
915 }
916 }
917
Jianing Wei90e59c92014-03-12 18:29:36 -0700918 return OK;
919}
920
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800921status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800922 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800923
Emilian Peevaebbe412018-01-15 13:53:24 +0000924 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700925 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000926 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700927
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800928 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700929}
930
Emilian Peevaebbe412018-01-15 13:53:24 +0000931void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700932 std::list<const SurfaceMap>& surfaceMaps,
933 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000934 PhysicalCameraSettingsList requestList;
935 requestList.push_back({std::string(getId().string()), request});
936 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700937
938 SurfaceMap surfaceMap;
939 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
940 // With no surface list passed in, stream and surface will have 1-to-1
941 // mapping. So the surface index is 0 for each stream in the surfaceMap.
942 for (size_t i = 0; i < streams.count; i++) {
943 surfaceMap[streams.data.i32[i]].push_back(0);
944 }
945 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800946}
947
Jianing Wei90e59c92014-03-12 18:29:36 -0700948status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000949 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700950 const std::list<const SurfaceMap> &surfaceMaps,
951 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700952 /*out*/
953 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700954 ATRACE_CALL();
955 Mutex::Autolock il(mInterfaceLock);
956 Mutex::Autolock l(mLock);
957
958 status_t res = checkStatusOkToCaptureLocked();
959 if (res != OK) {
960 // error logged by previous call
961 return res;
962 }
963
964 RequestList requestList;
965
Shuzhen Wang0129d522016-10-30 22:43:41 -0700966 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
967 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700968 if (res != OK) {
969 // error logged by previous call
970 return res;
971 }
972
973 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700974 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700975 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700976 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700977 }
978
979 if (res == OK) {
980 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
981 if (res != OK) {
982 SET_ERR_L("Can't transition to active in %f seconds!",
983 kActiveTimeout/1e9);
984 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800985 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700986 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700987 } else {
988 CLOGE("Cannot queue request. Impossible.");
989 return BAD_VALUE;
990 }
991
992 return res;
993}
994
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700995hardware::Return<void> Camera3Device::requestStreamBuffers(
996 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
997 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -0800998 RequestBufferStates states {
999 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams,
1000 *this, *mInterface, *this};
1001 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001002 return hardware::Void();
1003}
1004
1005hardware::Return<void> Camera3Device::returnStreamBuffers(
1006 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001007 ReturnBufferStates states {
1008 mId, mUseHalBufManager, mOutputStreams, *mInterface};
1009 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001010 return hardware::Void();
1011}
1012
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001013hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001014 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001015 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001016 // Ideally we should grab mLock, but that can lead to deadlock, and
1017 // it's not super important to get up to date value of mStatus for this
1018 // warning print, hence skipping the lock here
1019 if (mStatus == STATUS_ERROR) {
1020 // Per API contract, HAL should act as closed after device error
1021 // But mStatus can be set to error by framework as well, so just log
1022 // a warning here.
1023 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001024 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001025
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001026 sp<NotificationListener> listener;
1027 {
1028 std::lock_guard<std::mutex> l(mOutputLock);
1029 listener = mListener.promote();
1030 }
1031
Yifan Honga640c5a2017-04-12 16:30:31 -07001032 if (mProcessCaptureResultLock.tryLock() != OK) {
1033 // This should never happen; it indicates a wrong client implementation
1034 // that doesn't follow the contract. But, we can be tolerant here.
1035 ALOGE("%s: callback overlapped! waiting 1s...",
1036 __FUNCTION__);
1037 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1038 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1039 __FUNCTION__);
1040 // really don't know what to do, so bail out.
1041 return hardware::Void();
1042 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001043 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001044 CaptureOutputStates states {
1045 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001046 mInFlightLock, mLastCompletedRegularFrameNumber,
1047 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1048 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001049 mNextShutterFrameNumber,
1050 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1051 mNextResultFrameNumber,
1052 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1053 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1054 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001055 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1056 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001057 };
1058
Yifan Honga640c5a2017-04-12 16:30:31 -07001059 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001060 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001061 }
1062 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001063 return hardware::Void();
1064}
1065
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001066// Only one processCaptureResult should be called at a time, so
1067// the locks won't block. The locks are present here simply to enforce this.
1068hardware::Return<void> Camera3Device::processCaptureResult(
1069 const hardware::hidl_vec<
1070 hardware::camera::device::V3_2::CaptureResult>& results) {
1071 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1072
1073 // Ideally we should grab mLock, but that can lead to deadlock, and
1074 // it's not super important to get up to date value of mStatus for this
1075 // warning print, hence skipping the lock here
1076 if (mStatus == STATUS_ERROR) {
1077 // Per API contract, HAL should act as closed after device error
1078 // But mStatus can be set to error by framework as well, so just log
1079 // a warning here.
1080 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1081 }
1082
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001083 sp<NotificationListener> listener;
1084 {
1085 std::lock_guard<std::mutex> l(mOutputLock);
1086 listener = mListener.promote();
1087 }
1088
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001089 if (mProcessCaptureResultLock.tryLock() != OK) {
1090 // This should never happen; it indicates a wrong client implementation
1091 // that doesn't follow the contract. But, we can be tolerant here.
1092 ALOGE("%s: callback overlapped! waiting 1s...",
1093 __FUNCTION__);
1094 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1095 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1096 __FUNCTION__);
1097 // really don't know what to do, so bail out.
1098 return hardware::Void();
1099 }
1100 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001101
1102 CaptureOutputStates states {
1103 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001104 mInFlightLock, mLastCompletedRegularFrameNumber,
1105 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1106 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001107 mNextShutterFrameNumber,
1108 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1109 mNextResultFrameNumber,
1110 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1111 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1112 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001113 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1114 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001115 };
1116
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001117 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001118 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001119 }
1120 mProcessCaptureResultLock.unlock();
1121 return hardware::Void();
1122}
1123
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001124hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001125 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001126 // Ideally we should grab mLock, but that can lead to deadlock, and
1127 // it's not super important to get up to date value of mStatus for this
1128 // warning print, hence skipping the lock here
1129 if (mStatus == STATUS_ERROR) {
1130 // Per API contract, HAL should act as closed after device error
1131 // But mStatus can be set to error by framework as well, so just log
1132 // a warning here.
1133 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001134 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001135
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001136 sp<NotificationListener> listener;
1137 {
1138 std::lock_guard<std::mutex> l(mOutputLock);
1139 listener = mListener.promote();
1140 }
1141
1142 CaptureOutputStates states {
1143 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001144 mInFlightLock, mLastCompletedRegularFrameNumber,
1145 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1146 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001147 mNextShutterFrameNumber,
1148 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1149 mNextResultFrameNumber,
1150 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1151 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1152 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001153 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1154 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001155 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001156 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001157 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001158 }
1159 return hardware::Void();
1160}
1161
Emilian Peevaebbe412018-01-15 13:53:24 +00001162status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001163 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001164 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001165 ATRACE_CALL();
1166
Emilian Peevaebbe412018-01-15 13:53:24 +00001167 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001168}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001169
Jianing Weicb0652e2014-03-12 18:29:36 -07001170status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1171 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001172 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001173
Emilian Peevaebbe412018-01-15 13:53:24 +00001174 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001175 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001176 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001177
Emilian Peevaebbe412018-01-15 13:53:24 +00001178 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001179 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001180}
1181
Emilian Peevaebbe412018-01-15 13:53:24 +00001182status_t Camera3Device::setStreamingRequestList(
1183 const List<const PhysicalCameraSettingsList> &requestsList,
1184 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001185 ATRACE_CALL();
1186
Emilian Peevaebbe412018-01-15 13:53:24 +00001187 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001188}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001189
1190sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001191 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001192 status_t res;
1193
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001194 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001195 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1196 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001197 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1198 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001199 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001200 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001201 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001202 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001203 } else if (mStatus == STATUS_UNCONFIGURED) {
1204 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001205 CLOGE("No streams configured");
1206 return NULL;
1207 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001208 }
1209
Shuzhen Wang0129d522016-10-30 22:43:41 -07001210 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001211 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001212}
1213
Jianing Weicb0652e2014-03-12 18:29:36 -07001214status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001215 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001216 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001218
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 switch (mStatus) {
1220 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001221 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222 return INVALID_OPERATION;
1223 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001224 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001226 case STATUS_UNCONFIGURED:
1227 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001228 case STATUS_ACTIVE:
1229 // OK
1230 break;
1231 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001232 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 return INVALID_OPERATION;
1234 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001235 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001236
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001237 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001238}
1239
1240status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1241 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001242 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001243
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001244 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001245}
1246
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001247status_t Camera3Device::createInputStream(
1248 uint32_t width, uint32_t height, int format, int *id) {
1249 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001250 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001251 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001252 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001253 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1254 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001255
1256 status_t res;
1257 bool wasActive = false;
1258
1259 switch (mStatus) {
1260 case STATUS_ERROR:
1261 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1262 return INVALID_OPERATION;
1263 case STATUS_UNINITIALIZED:
1264 ALOGE("%s: Device not initialized", __FUNCTION__);
1265 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001266 case STATUS_UNCONFIGURED:
1267 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001268 // OK
1269 break;
1270 case STATUS_ACTIVE:
1271 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001272 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001273 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001274 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001275 return res;
1276 }
1277 wasActive = true;
1278 break;
1279 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001280 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001281 return INVALID_OPERATION;
1282 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001283 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001284
1285 if (mInputStream != 0) {
1286 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1287 return INVALID_OPERATION;
1288 }
1289
1290 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1291 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001292 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001293
1294 mInputStream = newStream;
1295
1296 *id = mNextStreamId++;
1297
1298 // Continue captures if active at start
1299 if (wasActive) {
1300 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001301 // Reuse current operating mode and session parameters for new stream config
1302 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001303 if (res != OK) {
1304 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1305 __FUNCTION__, mNextStreamId, strerror(-res), res);
1306 return res;
1307 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001308 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001309 }
1310
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001311 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001312 return OK;
1313}
1314
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001315status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001316 uint32_t width, uint32_t height, int format,
1317 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001318 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001319 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001320 ATRACE_CALL();
1321
1322 if (consumer == nullptr) {
1323 ALOGE("%s: consumer must not be null", __FUNCTION__);
1324 return BAD_VALUE;
1325 }
1326
1327 std::vector<sp<Surface>> consumers;
1328 consumers.push_back(consumer);
1329
1330 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001331 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1332 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001333}
1334
1335status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1336 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1337 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001338 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001339 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001340 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001341
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001342 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001343 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001344 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001345 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001346 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1347 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1348 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001349
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001350 status_t res;
1351 bool wasActive = false;
1352
1353 switch (mStatus) {
1354 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001355 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001356 return INVALID_OPERATION;
1357 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001358 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001359 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001360 case STATUS_UNCONFIGURED:
1361 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001362 // OK
1363 break;
1364 case STATUS_ACTIVE:
1365 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001366 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001367 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001368 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001369 return res;
1370 }
1371 wasActive = true;
1372 break;
1373 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001374 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001375 return INVALID_OPERATION;
1376 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001377 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001378
1379 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001380
Shuzhen Wang0129d522016-10-30 22:43:41 -07001381 if (consumers.size() == 0 && !hasDeferredConsumer) {
1382 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1383 return BAD_VALUE;
1384 }
Zhijun He5d677d12016-05-29 16:52:39 -07001385
Shuzhen Wang0129d522016-10-30 22:43:41 -07001386 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001387 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1388 return BAD_VALUE;
1389 }
1390
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001391 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001392 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001393 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001394 blobBufferSize = getPointCloudBufferSize();
1395 if (blobBufferSize <= 0) {
1396 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1397 return BAD_VALUE;
1398 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001399 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1400 blobBufferSize = width * height;
1401 } else {
1402 blobBufferSize = getJpegBufferSize(width, height);
1403 if (blobBufferSize <= 0) {
1404 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1405 return BAD_VALUE;
1406 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001407 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001408 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001409 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001410 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001411 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1412 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1413 if (rawOpaqueBufferSize <= 0) {
1414 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1415 return BAD_VALUE;
1416 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001417 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001418 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001419 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001420 } else if (isShared) {
1421 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1422 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001423 mTimestampOffset, physicalCameraId, streamSetId,
1424 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001425 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001426 newStream = new Camera3OutputStream(mNextStreamId,
1427 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001428 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001429 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001430 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001431 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001432 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001433 }
Emilian Peev40ead602017-09-26 15:46:36 +01001434
1435 size_t consumerCount = consumers.size();
1436 for (size_t i = 0; i < consumerCount; i++) {
1437 int id = newStream->getSurfaceId(consumers[i]);
1438 if (id < 0) {
1439 SET_ERR_L("Invalid surface id");
1440 return BAD_VALUE;
1441 }
1442 if (surfaceIds != nullptr) {
1443 surfaceIds->push_back(id);
1444 }
1445 }
1446
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001447 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001448
Emilian Peev08dd2452017-04-06 16:55:14 +01001449 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001450
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001451 res = mOutputStreams.add(mNextStreamId, newStream);
1452 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001453 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001454 return res;
1455 }
1456
1457 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001458 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459
1460 // Continue captures if active at start
1461 if (wasActive) {
1462 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001463 // Reuse current operating mode and session parameters for new stream config
1464 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001465 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001466 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1467 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001468 return res;
1469 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001470 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001471 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001472 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001473 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001474}
1475
Emilian Peev710c1422017-08-30 11:19:38 +01001476status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001477 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001478 if (nullptr == streamInfo) {
1479 return BAD_VALUE;
1480 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001481 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001482 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001483
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 switch (mStatus) {
1485 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001486 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001487 return INVALID_OPERATION;
1488 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001489 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001491 case STATUS_UNCONFIGURED:
1492 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001493 case STATUS_ACTIVE:
1494 // OK
1495 break;
1496 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001497 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 return INVALID_OPERATION;
1499 }
1500
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001501 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1502 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001503 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001504 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 }
1506
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001507 streamInfo->width = stream->getWidth();
1508 streamInfo->height = stream->getHeight();
1509 streamInfo->format = stream->getFormat();
1510 streamInfo->dataSpace = stream->getDataSpace();
1511 streamInfo->formatOverridden = stream->isFormatOverridden();
1512 streamInfo->originalFormat = stream->getOriginalFormat();
1513 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1514 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001515 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001516}
1517
1518status_t Camera3Device::setStreamTransform(int id,
1519 int transform) {
1520 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001521 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001522 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001523
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001524 switch (mStatus) {
1525 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001526 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001527 return INVALID_OPERATION;
1528 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001529 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001531 case STATUS_UNCONFIGURED:
1532 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001533 case STATUS_ACTIVE:
1534 // OK
1535 break;
1536 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001537 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 return INVALID_OPERATION;
1539 }
1540
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001541 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1542 if (stream == nullptr) {
1543 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001544 return BAD_VALUE;
1545 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001546 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001547}
1548
1549status_t Camera3Device::deleteStream(int id) {
1550 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001551 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 Mutex::Autolock l(mLock);
1553 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001554
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001555 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001556
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001557 // CameraDevice semantics require device to already be idle before
1558 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001559 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001560 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001561 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001562 }
1563
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001564 if (mStatus == STATUS_ERROR) {
1565 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1566 __FUNCTION__, mId.string());
1567 return -EBUSY;
1568 }
1569
Igor Murashkin2fba5842013-04-22 14:03:54 -07001570 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001571 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 if (mInputStream != NULL && id == mInputStream->getId()) {
1573 deletedStream = mInputStream;
1574 mInputStream.clear();
1575 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001576 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001577 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001578 return BAD_VALUE;
1579 }
Zhijun He5f446352014-01-22 09:49:33 -08001580 }
1581
1582 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001583 if (stream != nullptr) {
1584 deletedStream = stream;
1585 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001586 }
1587
1588 // Free up the stream endpoint so that it can be used by some other stream
1589 res = deletedStream->disconnect();
1590 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001591 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001592 // fall through since we want to still list the stream as deleted.
1593 }
1594 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001595 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001596
1597 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001598}
1599
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001600status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001601 ATRACE_CALL();
1602 ALOGV("%s: E", __FUNCTION__);
1603
1604 Mutex::Autolock il(mInterfaceLock);
1605 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001606
Emilian Peev811d2952018-05-25 11:08:40 +01001607 // In case the client doesn't include any session parameter, try a
1608 // speculative configuration using the values from the last cached
1609 // default request.
1610 if (sessionParams.isEmpty() &&
1611 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1612 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1613 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1614 mLastTemplateId);
1615 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1616 operatingMode);
1617 }
1618
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001619 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1620}
1621
1622status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1623 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001624 //Filter out any incoming session parameters
1625 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001626 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1627 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001628 CameraMetadata filteredParams(availableSessionKeys.count);
1629 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1630 filteredParams.getAndLock());
1631 set_camera_metadata_vendor_id(meta, mVendorTagId);
1632 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001633 if (availableSessionKeys.count > 0) {
1634 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1635 camera_metadata_ro_entry entry = params.find(
1636 availableSessionKeys.data.i32[i]);
1637 if (entry.count > 0) {
1638 filteredParams.update(entry);
1639 }
1640 }
1641 }
1642
1643 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001644}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001645
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001646status_t Camera3Device::getInputBufferProducer(
1647 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001648 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001649 Mutex::Autolock il(mInterfaceLock);
1650 Mutex::Autolock l(mLock);
1651
1652 if (producer == NULL) {
1653 return BAD_VALUE;
1654 } else if (mInputStream == NULL) {
1655 return INVALID_OPERATION;
1656 }
1657
1658 return mInputStream->getInputBufferProducer(producer);
1659}
1660
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001661status_t Camera3Device::createDefaultRequest(int templateId,
1662 CameraMetadata *request) {
1663 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001664 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001665
1666 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1667 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001668 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001669 return BAD_VALUE;
1670 }
1671
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001672 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001673
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001674 {
1675 Mutex::Autolock l(mLock);
1676 switch (mStatus) {
1677 case STATUS_ERROR:
1678 CLOGE("Device has encountered a serious error");
1679 return INVALID_OPERATION;
1680 case STATUS_UNINITIALIZED:
1681 CLOGE("Device is not initialized!");
1682 return INVALID_OPERATION;
1683 case STATUS_UNCONFIGURED:
1684 case STATUS_CONFIGURED:
1685 case STATUS_ACTIVE:
1686 // OK
1687 break;
1688 default:
1689 SET_ERR_L("Unexpected status: %d", mStatus);
1690 return INVALID_OPERATION;
1691 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001692
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001693 if (!mRequestTemplateCache[templateId].isEmpty()) {
1694 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001695 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001696 return OK;
1697 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001698 }
1699
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001700 camera_metadata_t *rawRequest;
1701 status_t res = mInterface->constructDefaultRequestSettings(
1702 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001703
1704 {
1705 Mutex::Autolock l(mLock);
1706 if (res == BAD_VALUE) {
1707 ALOGI("%s: template %d is not supported on this camera device",
1708 __FUNCTION__, templateId);
1709 return res;
1710 } else if (res != OK) {
1711 CLOGE("Unable to construct request template %d: %s (%d)",
1712 templateId, strerror(-res), res);
1713 return res;
1714 }
1715
1716 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1717 mRequestTemplateCache[templateId].acquire(rawRequest);
1718
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001719 // Override the template request with zoomRatioMapper
1720 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1721 &mRequestTemplateCache[templateId]);
1722 if (res != OK) {
1723 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1724 templateId, strerror(-res), res);
1725 return res;
1726 }
1727
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001728 // Fill in JPEG_QUALITY if not available
1729 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1730 static const uint8_t kDefaultJpegQuality = 95;
1731 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1732 &kDefaultJpegQuality, 1);
1733 }
1734
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001735 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001736 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001737 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001738 return OK;
1739}
1740
1741status_t Camera3Device::waitUntilDrained() {
1742 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001743 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001744 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001745 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001746
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001747 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001748}
1749
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001750status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001751 switch (mStatus) {
1752 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001753 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001754 ALOGV("%s: Already idle", __FUNCTION__);
1755 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001756 case STATUS_CONFIGURED:
1757 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001758 case STATUS_ERROR:
1759 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001760 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001761 break;
1762 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001763 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001764 return INVALID_OPERATION;
1765 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001766 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1767 maxExpectedDuration);
1768 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001769 if (res != OK) {
1770 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1771 res);
1772 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001773 return res;
1774}
1775
Ruben Brunk183f0562015-08-12 12:55:02 -07001776
1777void Camera3Device::internalUpdateStatusLocked(Status status) {
1778 mStatus = status;
1779 mRecentStatusUpdates.add(mStatus);
1780 mStatusChanged.broadcast();
1781}
1782
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001783// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001784status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001785 if (mRequestThread.get() != nullptr) {
1786 mRequestThread->setPaused(true);
1787 } else {
1788 return NO_INIT;
1789 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001790
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001791 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1792 maxExpectedDuration);
1793 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001794 if (res != OK) {
1795 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001796 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001797 }
1798
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001799 return res;
1800}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001801
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001802// Resume after internalPauseAndWaitLocked
1803status_t Camera3Device::internalResumeLocked() {
1804 status_t res;
1805
1806 mRequestThread->setPaused(false);
1807
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001808 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1809 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001810 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1811 if (res != OK) {
1812 SET_ERR_L("Can't transition to active in %f seconds!",
1813 kActiveTimeout/1e9);
1814 }
1815 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001816 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001817}
1818
Ruben Brunk183f0562015-08-12 12:55:02 -07001819status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001820 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001821
1822 size_t startIndex = 0;
1823 if (mStatusWaiters == 0) {
1824 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1825 // this status list
1826 mRecentStatusUpdates.clear();
1827 } else {
1828 // If other threads are waiting on updates to this status list, set the position of the
1829 // first element that this list will check rather than clearing the list.
1830 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001831 }
1832
Ruben Brunk183f0562015-08-12 12:55:02 -07001833 mStatusWaiters++;
1834
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001835 if (!active && mUseHalBufManager) {
1836 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001837 if (mStatus == STATUS_ACTIVE) {
1838 mRequestThread->signalPipelineDrain(streamIds);
1839 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001840 mRequestBufferSM.onWaitUntilIdle();
1841 }
1842
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001843 bool stateSeen = false;
1844 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001845 if (active == (mStatus == STATUS_ACTIVE)) {
1846 // Desired state is current
1847 break;
1848 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001849
1850 res = mStatusChanged.waitRelative(mLock, timeout);
1851 if (res != OK) break;
1852
Ruben Brunk183f0562015-08-12 12:55:02 -07001853 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1854 // transitions.
1855 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1856 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1857 __FUNCTION__);
1858
1859 // Encountered desired state since we began waiting
1860 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001861 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1862 stateSeen = true;
1863 break;
1864 }
1865 }
1866 } while (!stateSeen);
1867
Ruben Brunk183f0562015-08-12 12:55:02 -07001868 mStatusWaiters--;
1869
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001870 return res;
1871}
1872
1873
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001874status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001875 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001876 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001877
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001878 if (listener != NULL && mListener != NULL) {
1879 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1880 }
1881 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001882 mRequestThread->setNotificationListener(listener);
1883 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001884
1885 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001886}
1887
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001888bool Camera3Device::willNotify3A() {
1889 return false;
1890}
1891
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001892status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001893 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001894 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001895
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001896 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001897 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1898 if (st == std::cv_status::timeout) {
1899 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001900 }
1901 }
1902 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001903}
1904
Jianing Weicb0652e2014-03-12 18:29:36 -07001905status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001906 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001907 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001908
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001909 if (mResultQueue.empty()) {
1910 return NOT_ENOUGH_DATA;
1911 }
1912
Jianing Weicb0652e2014-03-12 18:29:36 -07001913 if (frame == NULL) {
1914 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1915 return BAD_VALUE;
1916 }
1917
1918 CaptureResult &result = *(mResultQueue.begin());
1919 frame->mResultExtras = result.mResultExtras;
1920 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001921 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001922 mResultQueue.erase(mResultQueue.begin());
1923
1924 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001925}
1926
1927status_t Camera3Device::triggerAutofocus(uint32_t id) {
1928 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001929 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001930
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001931 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1932 // Mix-in this trigger into the next request and only the next request.
1933 RequestTrigger trigger[] = {
1934 {
1935 ANDROID_CONTROL_AF_TRIGGER,
1936 ANDROID_CONTROL_AF_TRIGGER_START
1937 },
1938 {
1939 ANDROID_CONTROL_AF_TRIGGER_ID,
1940 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001941 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001942 };
1943
1944 return mRequestThread->queueTrigger(trigger,
1945 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001946}
1947
1948status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1949 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001950 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001951
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001952 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1953 // Mix-in this trigger into the next request and only the next request.
1954 RequestTrigger trigger[] = {
1955 {
1956 ANDROID_CONTROL_AF_TRIGGER,
1957 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1958 },
1959 {
1960 ANDROID_CONTROL_AF_TRIGGER_ID,
1961 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001962 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001963 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001964
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001965 return mRequestThread->queueTrigger(trigger,
1966 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001967}
1968
1969status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1970 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001971 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001972
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001973 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1974 // Mix-in this trigger into the next request and only the next request.
1975 RequestTrigger trigger[] = {
1976 {
1977 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1978 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1979 },
1980 {
1981 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1982 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001983 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001984 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001985
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001986 return mRequestThread->queueTrigger(trigger,
1987 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001988}
1989
Jianing Weicb0652e2014-03-12 18:29:36 -07001990status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001991 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001992 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001993 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001994
Zhijun He7ef20392014-04-21 16:04:17 -07001995 {
1996 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001997
1998 // b/116514106 "disconnect()" can get called twice for the same device. The
1999 // camera device will not be initialized during the second run.
2000 if (mStatus == STATUS_UNINITIALIZED) {
2001 return OK;
2002 }
2003
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002004 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002005 }
2006
Emilian Peev08dd2452017-04-06 16:55:14 +01002007 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002008}
2009
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002010status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002011 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2012}
2013
2014status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002015 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002016 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002017 Mutex::Autolock il(mInterfaceLock);
2018 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002019
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002020 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2021 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002022 CLOGE("Stream %d does not exist", streamId);
2023 return BAD_VALUE;
2024 }
2025
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002026 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002027 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002028 return BAD_VALUE;
2029 }
2030
2031 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002032 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002033 return BAD_VALUE;
2034 }
2035
Ruben Brunkc78ac262015-08-13 17:58:46 -07002036 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002037}
2038
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002039status_t Camera3Device::tearDown(int streamId) {
2040 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002041 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002042 Mutex::Autolock il(mInterfaceLock);
2043 Mutex::Autolock l(mLock);
2044
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002045 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2046 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002047 CLOGE("Stream %d does not exist", streamId);
2048 return BAD_VALUE;
2049 }
2050
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002051 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2052 CLOGE("Stream %d is a target of a in-progress request", streamId);
2053 return BAD_VALUE;
2054 }
2055
2056 return stream->tearDown();
2057}
2058
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002059status_t Camera3Device::addBufferListenerForStream(int streamId,
2060 wp<Camera3StreamBufferListener> listener) {
2061 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002062 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002063 Mutex::Autolock il(mInterfaceLock);
2064 Mutex::Autolock l(mLock);
2065
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002066 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2067 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002068 CLOGE("Stream %d does not exist", streamId);
2069 return BAD_VALUE;
2070 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002071 stream->addBufferListener(listener);
2072
2073 return OK;
2074}
2075
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002076/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002077 * Methods called by subclasses
2078 */
2079
2080void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002081 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002082 {
2083 // Need mLock to safely update state and synchronize to current
2084 // state of methods in flight.
2085 Mutex::Autolock l(mLock);
2086 // We can get various system-idle notices from the status tracker
2087 // while starting up. Only care about them if we've actually sent
2088 // in some requests recently.
2089 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2090 return;
2091 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002092 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2093 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002094 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002095
2096 // Skip notifying listener if we're doing some user-transparent
2097 // state changes
2098 if (mPauseStateNotify) return;
2099 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002100
2101 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002102 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002103 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002104 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002105 }
2106 if (idle && listener != NULL) {
2107 listener->notifyIdle();
2108 }
2109}
2110
Shuzhen Wang758c2152017-01-10 18:26:18 -08002111status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002112 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002113 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002114 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2115 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002116
2117 if (surfaceIds == nullptr) {
2118 return BAD_VALUE;
2119 }
2120
Zhijun He5d677d12016-05-29 16:52:39 -07002121 Mutex::Autolock il(mInterfaceLock);
2122 Mutex::Autolock l(mLock);
2123
Shuzhen Wang758c2152017-01-10 18:26:18 -08002124 if (consumers.size() == 0) {
2125 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002126 return BAD_VALUE;
2127 }
2128
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002129 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2130 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002131 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002132 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002133 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002134
2135 // isConsumerConfigurationDeferred will be off after setConsumers
2136 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002137 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002138 if (res != OK) {
2139 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2140 return res;
2141 }
2142
Emilian Peev40ead602017-09-26 15:46:36 +01002143 for (auto &consumer : consumers) {
2144 int id = stream->getSurfaceId(consumer);
2145 if (id < 0) {
2146 CLOGE("Invalid surface id!");
2147 return BAD_VALUE;
2148 }
2149 surfaceIds->push_back(id);
2150 }
2151
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002152 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002153 if (!stream->isConfiguring()) {
2154 CLOGE("Stream %d was already fully configured.", streamId);
2155 return INVALID_OPERATION;
2156 }
Zhijun He5d677d12016-05-29 16:52:39 -07002157
Shuzhen Wang0129d522016-10-30 22:43:41 -07002158 res = stream->finishConfiguration();
2159 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002160 // If finishConfiguration fails due to abandoned surface, do not set
2161 // device to error state.
2162 bool isSurfaceAbandoned =
2163 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2164 if (!isSurfaceAbandoned) {
2165 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2166 stream->getId(), strerror(-res), res);
2167 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002168 return res;
2169 }
Zhijun He5d677d12016-05-29 16:52:39 -07002170 }
2171
2172 return OK;
2173}
2174
Emilian Peev40ead602017-09-26 15:46:36 +01002175status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2176 const std::vector<OutputStreamInfo> &outputInfo,
2177 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2178 Mutex::Autolock il(mInterfaceLock);
2179 Mutex::Autolock l(mLock);
2180
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002181 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2182 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002183 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002184 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002185 }
2186
2187 for (const auto &it : removedSurfaceIds) {
2188 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2189 CLOGE("Shared surface still part of a pending request!");
2190 return -EBUSY;
2191 }
2192 }
2193
Emilian Peev40ead602017-09-26 15:46:36 +01002194 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2195 if (res != OK) {
2196 CLOGE("Stream %d failed to update stream (error %d %s) ",
2197 streamId, res, strerror(-res));
2198 if (res == UNKNOWN_ERROR) {
2199 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2200 __FUNCTION__);
2201 }
2202 return res;
2203 }
2204
2205 return res;
2206}
2207
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002208status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2209 Mutex::Autolock il(mInterfaceLock);
2210 Mutex::Autolock l(mLock);
2211
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002212 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2213 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002214 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2215 return BAD_VALUE;
2216 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002217 return stream->dropBuffers(dropping);
2218}
2219
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002220/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002221 * Camera3Device private methods
2222 */
2223
2224sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002225 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002226 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002227
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002228 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002229 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002230
2231 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002232 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002233 if (inputStreams.count > 0) {
2234 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002235 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002236 CLOGE("Request references unknown input stream %d",
2237 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002238 return NULL;
2239 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002240
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002241 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002242 SET_ERR_L("%s: input stream %d is not configured!",
2243 __FUNCTION__, mInputStream->getId());
2244 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002245 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002246 // Check if stream prepare is blocking requests.
2247 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002248 CLOGE("Request references an input stream that's being prepared!");
2249 return NULL;
2250 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002251
2252 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002253 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002254 }
2255
2256 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002257 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002258 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002259 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002260 return NULL;
2261 }
2262
2263 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002264 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2265 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002266 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002267 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002268 return NULL;
2269 }
Zhijun He5d677d12016-05-29 16:52:39 -07002270 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002271 auto iter = surfaceMap.find(streams.data.i32[i]);
2272 if (iter != surfaceMap.end()) {
2273 const std::vector<size_t>& surfaces = iter->second;
2274 for (const auto& surface : surfaces) {
2275 if (stream->isConsumerConfigurationDeferred(surface)) {
2276 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2277 "due to deferred consumer", stream->getId(), surface);
2278 return NULL;
2279 }
2280 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002281 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002282 }
2283
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002284 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002285 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2286 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002287 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002288 // Check if stream prepare is blocking requests.
2289 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002290 CLOGE("Request references an output stream that's being prepared!");
2291 return NULL;
2292 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002293
2294 newRequest->mOutputStreams.push(stream);
2295 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002296 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002297 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002298
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002299 auto rotateAndCropEntry =
2300 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2301 if (rotateAndCropEntry.count > 0 &&
2302 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2303 newRequest->mRotateAndCropAuto = true;
2304 } else {
2305 newRequest->mRotateAndCropAuto = false;
2306 }
2307
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002308 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002309}
2310
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002311void Camera3Device::cancelStreamsConfigurationLocked() {
2312 int res = OK;
2313 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2314 res = mInputStream->cancelConfiguration();
2315 if (res != OK) {
2316 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2317 mInputStream->getId(), strerror(-res), res);
2318 }
2319 }
2320
2321 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002322 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002323 if (outputStream->isConfiguring()) {
2324 res = outputStream->cancelConfiguration();
2325 if (res != OK) {
2326 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2327 outputStream->getId(), strerror(-res), res);
2328 }
2329 }
2330 }
2331
2332 // Return state to that at start of call, so that future configures
2333 // properly clean things up
2334 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2335 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002336
2337 res = mPreparerThread->resume();
2338 if (res != OK) {
2339 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2340 }
2341}
2342
Emilian Peev0d0191e2020-04-21 17:01:18 -07002343bool Camera3Device::checkAbandonedStreamsLocked() {
2344 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2345 return true;
2346 }
2347
2348 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2349 auto stream = mOutputStreams[i];
2350 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2351 return true;
2352 }
2353 }
2354
2355 return false;
2356}
2357
Emilian Peev3bead5f2020-05-28 17:29:08 -07002358bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002359 ATRACE_CALL();
2360 bool ret = false;
2361
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002362 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002363 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2364
2365 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002366 if (checkAbandonedStreamsLocked()) {
2367 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2368 __FUNCTION__);
2369 return true;
2370 }
2371
Emilian Peev3bead5f2020-05-28 17:29:08 -07002372 status_t rc = NO_ERROR;
2373 bool markClientActive = false;
2374 if (mStatus == STATUS_ACTIVE) {
2375 markClientActive = true;
2376 mPauseStateNotify = true;
2377 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2378
2379 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2380 }
2381
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002382 if (rc == NO_ERROR) {
2383 mNeedConfig = true;
2384 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2385 if (rc == NO_ERROR) {
2386 ret = true;
2387 mPauseStateNotify = false;
2388 //Moving to active state while holding 'mLock' is important.
2389 //There could be pending calls to 'create-/deleteStream' which
2390 //will trigger another stream configuration while the already
2391 //present streams end up with outstanding buffers that will
2392 //not get drained.
2393 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002394 } else if (rc == DEAD_OBJECT) {
2395 // DEAD_OBJECT can be returned if either the consumer surface is
2396 // abandoned, or the HAL has died.
2397 // - If the HAL has died, configureStreamsLocked call will set
2398 // device to error state,
2399 // - If surface is abandoned, we should not set device to error
2400 // state.
2401 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002402 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002403 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002404 }
2405 } else {
2406 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2407 }
2408
Emilian Peev3bead5f2020-05-28 17:29:08 -07002409 if (markClientActive) {
2410 mStatusTracker->markComponentActive(clientStatusId);
2411 }
2412
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002413 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002414}
2415
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002416status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002417 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002418 ATRACE_CALL();
2419 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002420
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002421 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002422 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002423 return INVALID_OPERATION;
2424 }
2425
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002426 if (operatingMode < 0) {
2427 CLOGE("Invalid operating mode: %d", operatingMode);
2428 return BAD_VALUE;
2429 }
2430
2431 bool isConstrainedHighSpeed =
2432 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2433 operatingMode;
2434
2435 if (mOperatingMode != operatingMode) {
2436 mNeedConfig = true;
2437 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2438 mOperatingMode = operatingMode;
2439 }
2440
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002441 // In case called from configureStreams, abort queued input buffers not belonging to
2442 // any pending requests.
2443 if (mInputStream != NULL && notifyRequestThread) {
2444 while (true) {
2445 camera3_stream_buffer_t inputBuffer;
2446 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2447 /*respectHalLimit*/ false);
2448 if (res != OK) {
2449 // Exhausted acquiring all input buffers.
2450 break;
2451 }
2452
2453 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2454 res = mInputStream->returnInputBuffer(inputBuffer);
2455 if (res != OK) {
2456 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2457 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2458 }
2459 }
2460 }
2461
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002462 if (!mNeedConfig) {
2463 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2464 return OK;
2465 }
2466
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002467 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2468 // adding a dummy stream instead.
2469 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2470 if (mOutputStreams.size() == 0) {
2471 addDummyStreamLocked();
2472 } else {
2473 tryRemoveDummyStreamLocked();
2474 }
2475
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002476 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002477 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002478
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002479 mPreparerThread->pause();
2480
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002481 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002482 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002483 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2484
2485 Vector<camera3_stream_t*> streams;
2486 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002487 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002488
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002489
2490 if (mInputStream != NULL) {
2491 camera3_stream_t *inputStream;
2492 inputStream = mInputStream->startConfiguration();
2493 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002494 CLOGE("Can't start input stream configuration");
2495 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002496 return INVALID_OPERATION;
2497 }
2498 streams.add(inputStream);
2499 }
2500
2501 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002502
2503 // Don't configure bidi streams twice, nor add them twice to the list
2504 if (mOutputStreams[i].get() ==
2505 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2506
2507 config.num_streams--;
2508 continue;
2509 }
2510
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002511 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002512 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002513 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002514 CLOGE("Can't start output stream configuration");
2515 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002516 return INVALID_OPERATION;
2517 }
2518 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002519
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002520 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002521 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2522 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002523 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2524 bufferSizes[k] = static_cast<uint32_t>(
2525 getJpegBufferSize(outputStream->width, outputStream->height));
2526 } else if (outputStream->data_space ==
2527 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2528 bufferSizes[k] = outputStream->width * outputStream->height;
2529 } else {
2530 ALOGW("%s: Blob dataSpace %d not supported",
2531 __FUNCTION__, outputStream->data_space);
2532 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002533 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002534 }
2535
2536 config.streams = streams.editArray();
2537
2538 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002539 // max_buffers, usage, and priv fields, as well as data_space and format
2540 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002541
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002542 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002543 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002544 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002545
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002546 if (res == BAD_VALUE) {
2547 // HAL rejected this set of streams as unsupported, clean up config
2548 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002549 CLOGE("Set of requested inputs/outputs not supported by HAL");
2550 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002551 return BAD_VALUE;
2552 } else if (res != OK) {
2553 // Some other kind of error from configure_streams - this is not
2554 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002555 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2556 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002557 return res;
2558 }
2559
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002560 // Finish all stream configuration immediately.
2561 // TODO: Try to relax this later back to lazy completion, which should be
2562 // faster
2563
Igor Murashkin073f8572013-05-02 14:59:28 -07002564 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002565 bool streamReConfigured = false;
2566 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002567 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002568 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002569 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002570 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002571 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2572 return DEAD_OBJECT;
2573 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002574 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002575 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002576 if (streamReConfigured) {
2577 mInterface->onStreamReConfigured(mInputStream->getId());
2578 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002579 }
2580
2581 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002582 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002583 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002584 bool streamReConfigured = false;
2585 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002586 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002587 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002588 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002589 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002590 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2591 return DEAD_OBJECT;
2592 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002593 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002594 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002595 if (streamReConfigured) {
2596 mInterface->onStreamReConfigured(outputStream->getId());
2597 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002598 }
2599 }
2600
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002601 // Request thread needs to know to avoid using repeat-last-settings protocol
2602 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002603 if (notifyRequestThread) {
2604 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2605 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002606
Zhijun He90f7c372016-08-16 16:19:43 -07002607 char value[PROPERTY_VALUE_MAX];
2608 property_get("camera.fifo.disable", value, "0");
2609 int32_t disableFifo = atoi(value);
2610 if (disableFifo != 1) {
2611 // Boost priority of request thread to SCHED_FIFO.
2612 pid_t requestThreadTid = mRequestThread->getTid();
2613 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002614 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002615 if (res != OK) {
2616 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2617 strerror(-res), res);
2618 } else {
2619 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2620 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002621 }
2622
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002623 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002624 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2625 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2626 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2627 sessionParams.unlock(newSessionParams);
2628 mSessionParams.unlock(currentSessionParams);
2629 if (updateSessionParams) {
2630 mSessionParams = sessionParams;
2631 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002632
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002633 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002634
Ruben Brunk183f0562015-08-12 12:55:02 -07002635 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2636 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002637
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002638 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002639
Zhijun He0a210512014-07-24 13:45:15 -07002640 // tear down the deleted streams after configure streams.
2641 mDeletedStreams.clear();
2642
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002643 auto rc = mPreparerThread->resume();
2644 if (rc != OK) {
2645 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2646 return rc;
2647 }
2648
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002649 if (mDummyStreamId == NO_STREAM) {
2650 mRequestBufferSM.onStreamsConfigured();
2651 }
2652
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002653 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002654}
2655
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002656status_t Camera3Device::addDummyStreamLocked() {
2657 ATRACE_CALL();
2658 status_t res;
2659
2660 if (mDummyStreamId != NO_STREAM) {
2661 // Should never be adding a second dummy stream when one is already
2662 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002663 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2664 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002665 return INVALID_OPERATION;
2666 }
2667
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002668 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002669
2670 sp<Camera3OutputStreamInterface> dummyStream =
2671 new Camera3DummyStream(mNextStreamId);
2672
2673 res = mOutputStreams.add(mNextStreamId, dummyStream);
2674 if (res < 0) {
2675 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2676 return res;
2677 }
2678
2679 mDummyStreamId = mNextStreamId;
2680 mNextStreamId++;
2681
2682 return OK;
2683}
2684
2685status_t Camera3Device::tryRemoveDummyStreamLocked() {
2686 ATRACE_CALL();
2687 status_t res;
2688
2689 if (mDummyStreamId == NO_STREAM) return OK;
2690 if (mOutputStreams.size() == 1) return OK;
2691
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002692 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002693
2694 // Ok, have a dummy stream and there's at least one other output stream,
2695 // so remove the dummy
2696
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002697 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2698 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002699 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2700 return INVALID_OPERATION;
2701 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002702 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002703
2704 // Free up the stream endpoint so that it can be used by some other stream
2705 res = deletedStream->disconnect();
2706 if (res != OK) {
2707 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2708 // fall through since we want to still list the stream as deleted.
2709 }
2710 mDeletedStreams.add(deletedStream);
2711 mDummyStreamId = NO_STREAM;
2712
2713 return res;
2714}
2715
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002716void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002717 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002718 Mutex::Autolock l(mLock);
2719 va_list args;
2720 va_start(args, fmt);
2721
2722 setErrorStateLockedV(fmt, args);
2723
2724 va_end(args);
2725}
2726
2727void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002728 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002729 Mutex::Autolock l(mLock);
2730 setErrorStateLockedV(fmt, args);
2731}
2732
2733void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2734 va_list args;
2735 va_start(args, fmt);
2736
2737 setErrorStateLockedV(fmt, args);
2738
2739 va_end(args);
2740}
2741
2742void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002743 // Print out all error messages to log
2744 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002745 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002746
2747 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002748 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002749
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002750 mErrorCause = errorCause;
2751
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002752 if (mRequestThread != nullptr) {
2753 mRequestThread->setPaused(true);
2754 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002755 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002756
2757 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002758 sp<NotificationListener> listener = mListener.promote();
2759 if (listener != NULL) {
2760 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002761 CaptureResultExtras());
2762 }
2763
2764 // Save stack trace. View by dumping it later.
2765 CameraTraces::saveTrace();
2766 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002767}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002768
2769/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002770 * In-flight request management
2771 */
2772
Jianing Weicb0652e2014-03-12 18:29:36 -07002773status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002774 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002775 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002776 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002777 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08002778 const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002779 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002780 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002781
2782 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002783 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002784 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002785 rotateAndCropAuto, cameraIdsWithZoom, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002786 if (res < 0) return res;
2787
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002788 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002789 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2790 // avoid a deadlock during reprocess requests.
2791 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002792 if (mStatusTracker != nullptr) {
2793 mStatusTracker->markComponentActive(mInFlightStatusId);
2794 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002795 }
2796
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002797 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002798 return OK;
2799}
2800
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002801void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002802 // Indicate idle inFlightMap to the status tracker
2803 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002804 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002805 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2806 // avoid a deadlock during reprocess requests.
2807 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002808 if (mStatusTracker != nullptr) {
2809 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2810 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002811 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002812 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002813}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002814
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002815void Camera3Device::checkInflightMapLengthLocked() {
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002816 // Sanity check - if we have too many in-flight frames with long total inflight duration,
2817 // something has likely gone wrong. This might still be legit only if application send in
2818 // a long burst of long exposure requests.
2819 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2820 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2821 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2822 mInFlightMap.size(), mExpectedInflightDuration);
2823 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2824 kInFlightWarnLimitHighSpeed) {
2825 CLOGW("In-flight list too large for high speed configuration: %zu,"
2826 "total inflight duration %" PRIu64,
2827 mInFlightMap.size(), mExpectedInflightDuration);
2828 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002829 }
2830}
2831
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002832void Camera3Device::onInflightMapFlushedLocked() {
2833 mExpectedInflightDuration = 0;
2834}
2835
2836void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2837 ATRACE_CALL();
2838 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2839 mInFlightMap.removeItemsAt(idx, 1);
2840
2841 onInflightEntryRemovedLocked(duration);
2842}
2843
2844
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002845void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002846 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002847 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002848 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002849 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002850 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002851 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002852
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002853 FlushInflightReqStates states {
2854 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
2855 listener, *this, *mInterface, *this};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002856
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002857 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002858}
2859
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002860CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002861 ALOGV("%s", __FUNCTION__);
2862
Igor Murashkin1e479c02013-09-06 16:55:14 -07002863 CameraMetadata retVal;
2864
2865 if (mRequestThread != NULL) {
2866 retVal = mRequestThread->getLatestRequest();
2867 }
2868
Igor Murashkin1e479c02013-09-06 16:55:14 -07002869 return retVal;
2870}
2871
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002872void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002873 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2874 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2875
2876 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2877 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002878}
2879
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002880/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002881 * HalInterface inner class methods
2882 */
2883
Yifan Hongf79b5542017-04-11 14:44:25 -07002884Camera3Device::HalInterface::HalInterface(
2885 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002886 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002887 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002888 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002889 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08002890 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002891 mIsReconfigurationQuerySupported(true),
2892 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002893 // Check with hardware service manager if we can downcast these interfaces
2894 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002895 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
2896 if (castResult_3_6.isOk()) {
2897 mHidlSession_3_6 = castResult_3_6;
2898 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002899 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
2900 if (castResult_3_5.isOk()) {
2901 mHidlSession_3_5 = castResult_3_5;
2902 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002903 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
2904 if (castResult_3_4.isOk()) {
2905 mHidlSession_3_4 = castResult_3_4;
2906 }
2907 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
2908 if (castResult_3_3.isOk()) {
2909 mHidlSession_3_3 = castResult_3_3;
2910 }
2911}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002912
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002913Camera3Device::HalInterface::HalInterface() :
2914 mUseHalBufManager(false),
2915 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002916
2917Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002918 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002919 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002920 mUseHalBufManager(other.mUseHalBufManager),
2921 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002922
2923bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01002924 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002925}
2926
2927void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002928 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00002929 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00002930 mHidlSession_3_4.clear();
2931 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002932 mHidlSession.clear();
2933}
2934
2935status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2936 camera3_request_template_t templateId,
2937 /*out*/ camera_metadata_t **requestTemplate) {
2938 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
2939 if (!valid()) return INVALID_OPERATION;
2940 status_t res = OK;
2941
Emilian Peev31abd0a2017-05-11 18:37:46 +01002942 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002943
2944 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01002945 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002946 status = s;
2947 if (status == common::V1_0::Status::OK) {
2948 const camera_metadata *r =
2949 reinterpret_cast<const camera_metadata_t*>(request.data());
2950 size_t expectedSize = request.size();
2951 int ret = validate_camera_metadata_structure(r, &expectedSize);
2952 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
2953 *requestTemplate = clone_camera_metadata(r);
2954 if (*requestTemplate == nullptr) {
2955 ALOGE("%s: Unable to clone camera metadata received from HAL",
2956 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01002957 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002958 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002959 } else {
2960 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
2961 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01002962 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002963 }
2964 };
2965 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08002966 RequestTemplate id;
2967 switch (templateId) {
2968 case CAMERA3_TEMPLATE_PREVIEW:
2969 id = RequestTemplate::PREVIEW;
2970 break;
2971 case CAMERA3_TEMPLATE_STILL_CAPTURE:
2972 id = RequestTemplate::STILL_CAPTURE;
2973 break;
2974 case CAMERA3_TEMPLATE_VIDEO_RECORD:
2975 id = RequestTemplate::VIDEO_RECORD;
2976 break;
2977 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
2978 id = RequestTemplate::VIDEO_SNAPSHOT;
2979 break;
2980 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
2981 id = RequestTemplate::ZERO_SHUTTER_LAG;
2982 break;
2983 case CAMERA3_TEMPLATE_MANUAL:
2984 id = RequestTemplate::MANUAL;
2985 break;
2986 default:
2987 // Unknown template ID, or this HAL is too old to support it
2988 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002989 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08002990 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002991
Emilian Peev31abd0a2017-05-11 18:37:46 +01002992 if (!err.isOk()) {
2993 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
2994 res = DEAD_OBJECT;
2995 } else {
2996 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002997 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01002998
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002999 return res;
3000}
3001
Emilian Peev4ec17882019-01-24 17:16:58 -08003002bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3003 CameraMetadata& newSessionParams) {
3004 // We do reconfiguration by default;
3005 bool ret = true;
3006 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3007 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3008 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3009 oldSessionParams.getAndLock());
3010 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3011 newSessionParams.getAndLock());
3012 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3013 get_camera_metadata_size(oldSessioMeta));
3014 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3015 get_camera_metadata_size(newSessioMeta));
3016 hardware::camera::common::V1_0::Status callStatus;
3017 bool required;
3018 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3019 bool requiredFlag) {
3020 callStatus = s;
3021 required = requiredFlag;
3022 };
3023 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3024 oldSessionParams.unlock(oldSessioMeta);
3025 newSessionParams.unlock(newSessioMeta);
3026 if (err.isOk()) {
3027 switch (callStatus) {
3028 case hardware::camera::common::V1_0::Status::OK:
3029 ret = required;
3030 break;
3031 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3032 mIsReconfigurationQuerySupported = false;
3033 ret = true;
3034 break;
3035 default:
3036 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3037 ret = true;
3038 }
3039 } else {
3040 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3041 ret = true;
3042 }
3043 }
3044
3045 return ret;
3046}
3047
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003048status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003049 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003050 ATRACE_NAME("CameraHal::configureStreams");
3051 if (!valid()) return INVALID_OPERATION;
3052 status_t res = OK;
3053
Emilian Peev31abd0a2017-05-11 18:37:46 +01003054 // Convert stream config to HIDL
3055 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003056 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3057 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3058 requestedConfiguration3_2.streams.resize(config->num_streams);
3059 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003060 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003061 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3062 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003063 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003064
Emilian Peev31abd0a2017-05-11 18:37:46 +01003065 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3066 cam3stream->setBufferFreedListener(this);
3067 int streamId = cam3stream->getId();
3068 StreamType streamType;
3069 switch (src->stream_type) {
3070 case CAMERA3_STREAM_OUTPUT:
3071 streamType = StreamType::OUTPUT;
3072 break;
3073 case CAMERA3_STREAM_INPUT:
3074 streamType = StreamType::INPUT;
3075 break;
3076 default:
3077 ALOGE("%s: Stream %d: Unsupported stream type %d",
3078 __FUNCTION__, streamId, config->streams[i]->stream_type);
3079 return BAD_VALUE;
3080 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003081 dst3_2.id = streamId;
3082 dst3_2.streamType = streamType;
3083 dst3_2.width = src->width;
3084 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003085 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003086 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003087 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3088 // to HAL are original, not the overriden ones.
3089 if (mHidlSession_3_5 != nullptr) {
3090 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3091 cam3stream->getOriginalFormat() : src->format);
3092 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3093 cam3stream->getOriginalDataSpace() : src->data_space);
3094 } else {
3095 dst3_2.format = mapToPixelFormat(src->format);
3096 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3097 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003098 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003099 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003100 if (src->physical_camera_id != nullptr) {
3101 dst3_4.physicalCameraId = src->physical_camera_id;
3102 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003103
3104 activeStreams.insert(streamId);
3105 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003106 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003107 }
3108 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003109 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003110
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003111 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003112 res = mapToStreamConfigurationMode(
3113 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003114 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003115 if (res != OK) {
3116 return res;
3117 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003118 requestedConfiguration3_2.operationMode = operationMode;
3119 requestedConfiguration3_4.operationMode = operationMode;
3120 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003121 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3122 get_camera_metadata_size(sessionParams));
3123
Emilian Peev31abd0a2017-05-11 18:37:46 +01003124 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003125 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003126 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003127 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003128 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003129
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003130 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003131 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3132 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003133 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003134 };
3135
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003136 auto configStream36Cb = [&status, &finalConfiguration3_6]
3137 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3138 finalConfiguration3_6 = halConfiguration;
3139 status = s;
3140 };
3141
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003142 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3143 (hardware::Return<void>& err) -> status_t {
3144 if (!err.isOk()) {
3145 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3146 return DEAD_OBJECT;
3147 }
3148 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3149 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3150 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3151 }
3152 return OK;
3153 };
3154
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003155 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3156 (hardware::Return<void>& err) -> status_t {
3157 if (!err.isOk()) {
3158 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3159 return DEAD_OBJECT;
3160 }
3161 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3162 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3163 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3164 }
3165 return OK;
3166 };
3167
Shuzhen Wang92653952019-05-07 15:11:43 -07003168 // See which version of HAL we have
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003169 if (mHidlSession_3_6 != nullptr) {
3170 ALOGV("%s: v3.6 device found", __FUNCTION__);
3171 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3172 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3173 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3174 auto err = mHidlSession_3_6->configureStreams_3_6(
3175 requestedConfiguration3_5, configStream36Cb);
3176 res = postprocConfigStream36(err);
3177 if (res != OK) {
3178 return res;
3179 }
3180 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003181 ALOGV("%s: v3.5 device found", __FUNCTION__);
3182 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3183 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3184 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3185 auto err = mHidlSession_3_5->configureStreams_3_5(
3186 requestedConfiguration3_5, configStream34Cb);
3187 res = postprocConfigStream34(err);
3188 if (res != OK) {
3189 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003190 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003191 } else if (mHidlSession_3_4 != nullptr) {
3192 // We do; use v3.4 for the call
3193 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003194 auto err = mHidlSession_3_4->configureStreams_3_4(
3195 requestedConfiguration3_4, configStream34Cb);
3196 res = postprocConfigStream34(err);
3197 if (res != OK) {
3198 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003199 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003200 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003201 // We do; use v3.3 for the call
3202 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003203 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003204 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003205 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003206 finalConfiguration = halConfiguration;
3207 status = s;
3208 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003209 if (!err.isOk()) {
3210 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3211 return DEAD_OBJECT;
3212 }
3213 } else {
3214 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3215 ALOGV("%s: v3.2 device found", __FUNCTION__);
3216 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003217 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003218 [&status, &finalConfiguration_3_2]
3219 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3220 finalConfiguration_3_2 = halConfiguration;
3221 status = s;
3222 });
3223 if (!err.isOk()) {
3224 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3225 return DEAD_OBJECT;
3226 }
3227 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3228 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3229 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3230 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003231 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003232 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003233 }
3234
3235 if (status != common::V1_0::Status::OK ) {
3236 return CameraProviderManager::mapToStatusT(status);
3237 }
3238
3239 // And convert output stream configuration from HIDL
3240
3241 for (size_t i = 0; i < config->num_streams; i++) {
3242 camera3_stream_t *dst = config->streams[i];
3243 int streamId = Camera3Stream::cast(dst)->getId();
3244
3245 // Start scan at i, with the assumption that the stream order matches
3246 size_t realIdx = i;
3247 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003248 size_t halStreamCount = finalConfiguration.streams.size();
3249 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003250 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003251 found = true;
3252 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003253 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003254 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003255 }
3256 if (!found) {
3257 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3258 __FUNCTION__, streamId);
3259 return INVALID_OPERATION;
3260 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003261 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003262 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003263
Emilian Peev710c1422017-08-30 11:19:38 +01003264 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003265 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3266 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3267
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003268 if (mHidlSession_3_6 != nullptr) {
3269 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3270 }
3271
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003272 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003273 dstStream->setFormatOverride(false);
3274 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003275 if (dst->format != overrideFormat) {
3276 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3277 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003278 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003279 if (dst->data_space != overrideDataSpace) {
3280 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3281 streamId, dst->format);
3282 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003283 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003284 bool needFormatOverride =
3285 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3286 bool needDataspaceOverride =
3287 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003288 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003289 dstStream->setFormatOverride(needFormatOverride);
3290 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003291 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003292 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003293 }
3294
Emilian Peev31abd0a2017-05-11 18:37:46 +01003295 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003296 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003297 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003298 __FUNCTION__, streamId);
3299 return INVALID_OPERATION;
3300 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003301 dstStream->setUsage(
3302 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003303 } else {
3304 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003305 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003306 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3307 __FUNCTION__, streamId);
3308 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003309 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003310 dstStream->setUsage(
3311 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003312 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003313 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003314 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003315
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003316 return res;
3317}
3318
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003319status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003320 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003321 /*out*/std::vector<native_handle_t*>* handlesCreated,
3322 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003323 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003324 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3325 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3326 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003327 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003328 }
3329
3330 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003331
3332 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003333
3334 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003335 if (request->input_buffer != nullptr) {
3336 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3337 buffer_handle_t buf = *(request->input_buffer->buffer);
3338 auto pair = getBufferId(buf, streamId);
3339 bool isNewBuffer = pair.first;
3340 uint64_t bufferId = pair.second;
3341 captureRequest->inputBuffer.streamId = streamId;
3342 captureRequest->inputBuffer.bufferId = bufferId;
3343 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3344 captureRequest->inputBuffer.status = BufferStatus::OK;
3345 native_handle_t *acquireFence = nullptr;
3346 if (request->input_buffer->acquire_fence != -1) {
3347 acquireFence = native_handle_create(1,0);
3348 acquireFence->data[0] = request->input_buffer->acquire_fence;
3349 handlesCreated->push_back(acquireFence);
3350 }
3351 captureRequest->inputBuffer.acquireFence = acquireFence;
3352 captureRequest->inputBuffer.releaseFence = nullptr;
3353
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003354 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003355 request->input_buffer->buffer);
3356 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003357 } else {
3358 captureRequest->inputBuffer.streamId = -1;
3359 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3360 }
3361
3362 captureRequest->outputBuffers.resize(request->num_output_buffers);
3363 for (size_t i = 0; i < request->num_output_buffers; i++) {
3364 const camera3_stream_buffer_t *src = request->output_buffers + i;
3365 StreamBuffer &dst = captureRequest->outputBuffers[i];
3366 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003367 if (src->buffer != nullptr) {
3368 buffer_handle_t buf = *(src->buffer);
3369 auto pair = getBufferId(buf, streamId);
3370 bool isNewBuffer = pair.first;
3371 dst.bufferId = pair.second;
3372 dst.buffer = isNewBuffer ? buf : nullptr;
3373 native_handle_t *acquireFence = nullptr;
3374 if (src->acquire_fence != -1) {
3375 acquireFence = native_handle_create(1,0);
3376 acquireFence->data[0] = src->acquire_fence;
3377 handlesCreated->push_back(acquireFence);
3378 }
3379 dst.acquireFence = acquireFence;
3380 } else if (mUseHalBufManager) {
3381 // HAL buffer management path
3382 dst.bufferId = BUFFER_ID_NO_BUFFER;
3383 dst.buffer = nullptr;
3384 dst.acquireFence = nullptr;
3385 } else {
3386 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3387 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003388 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003389 dst.streamId = streamId;
3390 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003391 dst.releaseFence = nullptr;
3392
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003393 // Output buffers are empty when using HAL buffer manager
3394 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003395 mBufferRecords.pushInflightBuffer(
3396 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003397 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003398 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003399 }
3400 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003401 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003402}
3403
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003404void Camera3Device::HalInterface::cleanupNativeHandles(
3405 std::vector<native_handle_t*> *handles, bool closeFd) {
3406 if (handles == nullptr) {
3407 return;
3408 }
3409 if (closeFd) {
3410 for (auto& handle : *handles) {
3411 native_handle_close(handle);
3412 }
3413 }
3414 for (auto& handle : *handles) {
3415 native_handle_delete(handle);
3416 }
3417 handles->clear();
3418 return;
3419}
3420
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003421status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3422 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3423 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3424 if (!valid()) return INVALID_OPERATION;
3425
Emilian Peevaebbe412018-01-15 13:53:24 +00003426 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3427 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3428 if (castResult_3_4.isOk()) {
3429 hidlSession_3_4 = castResult_3_4;
3430 }
3431
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003432 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003433 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003434 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003435 if (hidlSession_3_4 != nullptr) {
3436 captureRequests_3_4.resize(batchSize);
3437 } else {
3438 captureRequests.resize(batchSize);
3439 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003440 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003441 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003442
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003443 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003444 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003445 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003446 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003447 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003448 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003449 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3450 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003451 }
3452 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003453 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003454 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003455 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003456 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003457 }
3458
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003459 std::vector<device::V3_2::BufferCache> cachesToRemove;
3460 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003461 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003462 for (auto& pair : mFreedBuffers) {
3463 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003464 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003465 cachesToRemove.push_back({pair.first, pair.second});
3466 }
3467 }
3468 mFreedBuffers.clear();
3469 }
3470
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003471 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3472 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003473
3474 // Write metadata to FMQ.
3475 for (size_t i = 0; i < batchSize; i++) {
3476 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003477 device::V3_2::CaptureRequest* captureRequest;
3478 if (hidlSession_3_4 != nullptr) {
3479 captureRequest = &captureRequests_3_4[i].v3_2;
3480 } else {
3481 captureRequest = &captureRequests[i];
3482 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003483
3484 if (request->settings != nullptr) {
3485 size_t settingsSize = get_camera_metadata_size(request->settings);
3486 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3487 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3488 captureRequest->settings.resize(0);
3489 captureRequest->fmqSettingsSize = settingsSize;
3490 } else {
3491 if (mRequestMetadataQueue != nullptr) {
3492 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3493 }
3494 captureRequest->settings.setToExternal(
3495 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3496 get_camera_metadata_size(request->settings));
3497 captureRequest->fmqSettingsSize = 0u;
3498 }
3499 } else {
3500 // A null request settings maps to a size-0 CameraMetadata
3501 captureRequest->settings.resize(0);
3502 captureRequest->fmqSettingsSize = 0u;
3503 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003504
3505 if (hidlSession_3_4 != nullptr) {
3506 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3507 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003508 if (request->physcam_settings != nullptr) {
3509 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3510 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3511 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3512 settingsSize)) {
3513 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3514 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3515 settingsSize;
3516 } else {
3517 if (mRequestMetadataQueue != nullptr) {
3518 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3519 }
3520 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3521 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3522 request->physcam_settings[j])),
3523 get_camera_metadata_size(request->physcam_settings[j]));
3524 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003525 }
Emilian Peev00420d22018-02-05 21:33:13 +00003526 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003527 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003528 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003529 }
3530 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3531 request->physcam_id[j];
3532 }
3533 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003534 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003535
3536 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003537 auto resultCallback =
3538 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3539 status = s;
3540 *numRequestProcessed = n;
3541 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003542 if (hidlSession_3_4 != nullptr) {
3543 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003544 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003545 } else {
3546 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003547 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003548 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003549 if (!err.isOk()) {
3550 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003551 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003552 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003553
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003554 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3555 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3556 __FUNCTION__, *numRequestProcessed, batchSize);
3557 status = common::V1_0::Status::INTERNAL_ERROR;
3558 }
3559
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003560 res = CameraProviderManager::mapToStatusT(status);
3561 if (res == OK) {
3562 if (mHidlSession->isRemote()) {
3563 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3564 // sent to camera HAL processes)
3565 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3566 } else {
3567 // In passthrough mode the FDs are now owned by HAL
3568 cleanupNativeHandles(&handlesCreated);
3569 }
3570 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003571 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003572 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003573 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003574 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003575}
3576
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003577status_t Camera3Device::HalInterface::flush() {
3578 ATRACE_NAME("CameraHal::flush");
3579 if (!valid()) return INVALID_OPERATION;
3580 status_t res = OK;
3581
Emilian Peev31abd0a2017-05-11 18:37:46 +01003582 auto err = mHidlSession->flush();
3583 if (!err.isOk()) {
3584 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3585 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003586 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003587 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003588 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003589
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003590 return res;
3591}
3592
Emilian Peev31abd0a2017-05-11 18:37:46 +01003593status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003594 ATRACE_NAME("CameraHal::dump");
3595 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003596
Emilian Peev31abd0a2017-05-11 18:37:46 +01003597 // Handled by CameraProviderManager::dump
3598
3599 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003600}
3601
3602status_t Camera3Device::HalInterface::close() {
3603 ATRACE_NAME("CameraHal::close()");
3604 if (!valid()) return INVALID_OPERATION;
3605 status_t res = OK;
3606
Emilian Peev31abd0a2017-05-11 18:37:46 +01003607 auto err = mHidlSession->close();
3608 // Interface will be dead shortly anyway, so don't log errors
3609 if (!err.isOk()) {
3610 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003611 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003612
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003613 return res;
3614}
3615
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003616void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3617 ATRACE_NAME("CameraHal::signalPipelineDrain");
3618 if (!valid() || mHidlSession_3_5 == nullptr) {
3619 ALOGE("%s called on invalid camera!", __FUNCTION__);
3620 return;
3621 }
3622
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003623 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003624 if (!err.isOk()) {
3625 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3626 return;
3627 }
3628}
3629
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003630status_t Camera3Device::HalInterface::switchToOffline(
3631 const std::vector<int32_t>& streamsToKeep,
3632 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003633 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3634 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003635 ATRACE_NAME("CameraHal::switchToOffline");
3636 if (!valid() || mHidlSession_3_6 == nullptr) {
3637 ALOGE("%s called on invalid camera!", __FUNCTION__);
3638 return INVALID_OPERATION;
3639 }
3640
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003641 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3642 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003643 return INVALID_OPERATION;
3644 }
3645
3646 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003647 auto resultCallback =
3648 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3649 status = s;
3650 *offlineSessionInfo = info;
3651 *offlineSession = session;
3652 };
3653 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3654
3655 if (!err.isOk()) {
3656 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3657 return DEAD_OBJECT;
3658 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003659
3660 status_t ret = CameraProviderManager::mapToStatusT(status);
3661 if (ret != OK) {
3662 return ret;
3663 }
3664
3665 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3666 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3667 // returns from switchToOffline.
3668
3669
3670 // Validate buffer caches
3671 std::vector<int32_t> streams;
3672 streams.reserve(offlineSessionInfo->offlineStreams.size());
3673 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3674 int32_t id = offlineStream.id;
3675 streams.push_back(id);
3676 // Verify buffer caches
3677 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3678 offlineStream.circulatingBufferIds.end());
3679 if (!verifyBufferIds(id, bufIds)) {
3680 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3681 return UNKNOWN_ERROR;
3682 }
3683 }
3684
3685 // Move buffer records
3686 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3687 bufferRecords->takeInflightBufferMap(mBufferRecords);
3688 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3689 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003690}
3691
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003692void Camera3Device::HalInterface::getInflightBufferKeys(
3693 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003694 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003695 return;
3696}
3697
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003698void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3699 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003700 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003701 return;
3702}
3703
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003704bool Camera3Device::HalInterface::verifyBufferIds(
3705 int32_t streamId, std::vector<uint64_t>& bufIds) {
3706 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003707}
3708
3709status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003710 int32_t frameNumber, int32_t streamId,
3711 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003712 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003713}
3714
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003715status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003716 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003717 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003718}
3719
3720// Find and pop a buffer_handle_t based on bufferId
3721status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003722 uint64_t bufferId,
3723 /*out*/ buffer_handle_t** buffer,
3724 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003725 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003726}
3727
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003728std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3729 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003730 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003731}
3732
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003733void Camera3Device::HalInterface::onBufferFreed(
3734 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003735 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3736 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3737 if (bufferId != BUFFER_ID_NO_BUFFER) {
3738 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003739 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003740}
3741
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003742void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003743 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3744 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3745 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003746 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3747 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003748}
3749
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003750/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003751 * RequestThread inner class methods
3752 */
3753
3754Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003755 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003756 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3757 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003758 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003759 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003760 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003761 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003762 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003763 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003764 mReconfigured(false),
3765 mDoPause(false),
3766 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003767 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003768 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003769 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003770 mCurrentAfTriggerId(0),
3771 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003772 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003773 mRepeatingLastFrameNumber(
3774 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003775 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003776 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003777 mRequestLatency(kRequestLatencyBinSize),
3778 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003779 mLatestSessionParams(sessionParamKeys.size()),
3780 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003781 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003782}
3783
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003784Camera3Device::RequestThread::~RequestThread() {}
3785
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003786void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003787 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003788 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003789 Mutex::Autolock l(mRequestLock);
3790 mListener = listener;
3791}
3792
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003793void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3794 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003795 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003796 Mutex::Autolock l(mRequestLock);
3797 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003798 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003799 // Prepare video stream for high speed recording.
3800 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003801 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003802}
3803
Jianing Wei90e59c92014-03-12 18:29:36 -07003804status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003805 List<sp<CaptureRequest> > &requests,
3806 /*out*/
3807 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003808 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003809 Mutex::Autolock l(mRequestLock);
3810 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3811 ++it) {
3812 mRequestQueue.push_back(*it);
3813 }
3814
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003815 if (lastFrameNumber != NULL) {
3816 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3817 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3818 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3819 *lastFrameNumber);
3820 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003821
Jianing Wei90e59c92014-03-12 18:29:36 -07003822 unpauseForNewRequests();
3823
3824 return OK;
3825}
3826
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003827
3828status_t Camera3Device::RequestThread::queueTrigger(
3829 RequestTrigger trigger[],
3830 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003831 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003832 Mutex::Autolock l(mTriggerMutex);
3833 status_t ret;
3834
3835 for (size_t i = 0; i < count; ++i) {
3836 ret = queueTriggerLocked(trigger[i]);
3837
3838 if (ret != OK) {
3839 return ret;
3840 }
3841 }
3842
3843 return OK;
3844}
3845
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003846const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3847 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003848 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003849 if (d != nullptr) return d->mId;
3850 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003851}
3852
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003853status_t Camera3Device::RequestThread::queueTriggerLocked(
3854 RequestTrigger trigger) {
3855
3856 uint32_t tag = trigger.metadataTag;
3857 ssize_t index = mTriggerMap.indexOfKey(tag);
3858
3859 switch (trigger.getTagType()) {
3860 case TYPE_BYTE:
3861 // fall-through
3862 case TYPE_INT32:
3863 break;
3864 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003865 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3866 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003867 return INVALID_OPERATION;
3868 }
3869
3870 /**
3871 * Collect only the latest trigger, since we only have 1 field
3872 * in the request settings per trigger tag, and can't send more than 1
3873 * trigger per request.
3874 */
3875 if (index != NAME_NOT_FOUND) {
3876 mTriggerMap.editValueAt(index) = trigger;
3877 } else {
3878 mTriggerMap.add(tag, trigger);
3879 }
3880
3881 return OK;
3882}
3883
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003884status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003885 const RequestList &requests,
3886 /*out*/
3887 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003888 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003889 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003890 if (lastFrameNumber != NULL) {
3891 *lastFrameNumber = mRepeatingLastFrameNumber;
3892 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003893 mRepeatingRequests.clear();
3894 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3895 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003896
3897 unpauseForNewRequests();
3898
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003899 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003900 return OK;
3901}
3902
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003903bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003904 if (mRepeatingRequests.empty()) {
3905 return false;
3906 }
3907 int32_t requestId = requestIn->mResultExtras.requestId;
3908 const RequestList &repeatRequests = mRepeatingRequests;
3909 // All repeating requests are guaranteed to have same id so only check first quest
3910 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3911 return (firstRequest->mResultExtras.requestId == requestId);
3912}
3913
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003914status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003915 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003916 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003917 return clearRepeatingRequestsLocked(lastFrameNumber);
3918
3919}
3920
3921status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003922 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003923 if (lastFrameNumber != NULL) {
3924 *lastFrameNumber = mRepeatingLastFrameNumber;
3925 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003926 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003927 return OK;
3928}
3929
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003930status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003931 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003932 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003933 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003934 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003935
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003936 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003937
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003938 // Send errors for all requests pending in the request queue, including
3939 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003940 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003941 if (listener != NULL) {
3942 for (RequestList::iterator it = mRequestQueue.begin();
3943 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003944 // Abort the input buffers for reprocess requests.
3945 if ((*it)->mInputStream != NULL) {
3946 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003947 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3948 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003949 if (res != OK) {
3950 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3951 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3952 } else {
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07003953 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003954 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3955 if (res != OK) {
3956 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3957 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3958 }
3959 }
3960 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003961 // Set the frame number this request would have had, if it
3962 // had been submitted; this frame number will not be reused.
3963 // The requestId and burstId fields were set when the request was
3964 // submitted originally (in convertMetadataListToRequestListLocked)
3965 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003966 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003967 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003968 }
3969 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003970 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003971
3972 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003973 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003974 if (lastFrameNumber != NULL) {
3975 *lastFrameNumber = mRepeatingLastFrameNumber;
3976 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003977 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003978 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003979 return OK;
3980}
3981
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003982status_t Camera3Device::RequestThread::flush() {
3983 ATRACE_CALL();
3984 Mutex::Autolock l(mFlushLock);
3985
Emilian Peev08dd2452017-04-06 16:55:14 +01003986 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003987}
3988
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003989void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003990 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003991 Mutex::Autolock l(mPauseLock);
3992 mDoPause = paused;
3993 mDoPauseSignal.signal();
3994}
3995
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003996status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3997 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003998 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003999 Mutex::Autolock l(mLatestRequestMutex);
4000 status_t res;
4001 while (mLatestRequestId != requestId) {
4002 nsecs_t startTime = systemTime();
4003
4004 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4005 if (res != OK) return res;
4006
4007 timeout -= (systemTime() - startTime);
4008 }
4009
4010 return OK;
4011}
4012
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004013void Camera3Device::RequestThread::requestExit() {
4014 // Call parent to set up shutdown
4015 Thread::requestExit();
4016 // The exit from any possible waits
4017 mDoPauseSignal.signal();
4018 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004019
4020 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4021 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004022}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004023
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004024void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004025 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004026 bool surfaceAbandoned = false;
4027 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004028 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004029 {
4030 Mutex::Autolock l(mRequestLock);
4031 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4032 // repeating requests.
4033 for (const auto& request : mRepeatingRequests) {
4034 for (const auto& s : request->mOutputStreams) {
4035 if (s->isAbandoned()) {
4036 surfaceAbandoned = true;
4037 clearRepeatingRequestsLocked(&lastFrameNumber);
4038 break;
4039 }
4040 }
4041 if (surfaceAbandoned) {
4042 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004043 }
4044 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004045 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004046 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004047
4048 if (listener != NULL && surfaceAbandoned) {
4049 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004050 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004051}
4052
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004053bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004054 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004055 status_t res;
4056 size_t batchSize = mNextRequests.size();
4057 std::vector<camera3_capture_request_t*> requests(batchSize);
4058 uint32_t numRequestProcessed = 0;
4059 for (size_t i = 0; i < batchSize; i++) {
4060 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004061 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004062 }
4063
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004064 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4065
4066 bool triggerRemoveFailed = false;
4067 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4068 for (size_t i = 0; i < numRequestProcessed; i++) {
4069 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4070 nextRequest.submitted = true;
4071
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004072 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004073
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004074 if (!triggerRemoveFailed) {
4075 // Remove any previously queued triggers (after unlock)
4076 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4077 if (removeTriggerRes != OK) {
4078 triggerRemoveFailed = true;
4079 triggerFailedRequest = nextRequest;
4080 }
4081 }
4082 }
4083
4084 if (triggerRemoveFailed) {
4085 SET_ERR("RequestThread: Unable to remove triggers "
4086 "(capture request %d, HAL device: %s (%d)",
4087 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4088 cleanUpFailedRequests(/*sendRequestError*/ false);
4089 return false;
4090 }
4091
4092 if (res != OK) {
4093 // Should only get a failure here for malformed requests or device-level
4094 // errors, so consider all errors fatal. Bad metadata failures should
4095 // come through notify.
4096 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4097 mNextRequests[numRequestProcessed].halRequest.frame_number,
4098 strerror(-res), res);
4099 cleanUpFailedRequests(/*sendRequestError*/ false);
4100 return false;
4101 }
4102 return true;
4103}
4104
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004105nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4106 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4107 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4108 find_camera_metadata_ro_entry(request,
4109 ANDROID_CONTROL_AE_MODE,
4110 &e);
4111 if (e.count == 0) return maxExpectedDuration;
4112
4113 switch (e.data.u8[0]) {
4114 case ANDROID_CONTROL_AE_MODE_OFF:
4115 find_camera_metadata_ro_entry(request,
4116 ANDROID_SENSOR_EXPOSURE_TIME,
4117 &e);
4118 if (e.count > 0) {
4119 maxExpectedDuration = e.data.i64[0];
4120 }
4121 find_camera_metadata_ro_entry(request,
4122 ANDROID_SENSOR_FRAME_DURATION,
4123 &e);
4124 if (e.count > 0) {
4125 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4126 }
4127 break;
4128 default:
4129 find_camera_metadata_ro_entry(request,
4130 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4131 &e);
4132 if (e.count > 1) {
4133 maxExpectedDuration = 1e9 / e.data.u8[0];
4134 }
4135 break;
4136 }
4137
4138 return maxExpectedDuration;
4139}
4140
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004141bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4142 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4143 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4144 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4145 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4146 return true;
4147 }
4148
4149 return false;
4150}
4151
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004152void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4153 // Update the latest request sent to HAL
4154 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4155 Mutex::Autolock al(mLatestRequestMutex);
4156
4157 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4158 mLatestRequest.acquire(cloned);
4159
4160 mLatestPhysicalRequest.clear();
4161 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
4162 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
4163 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
4164 CameraMetadata(cloned));
4165 }
4166
4167 sp<Camera3Device> parent = mParent.promote();
4168 if (parent != NULL) {
4169 parent->monitorMetadata(TagMonitor::REQUEST,
4170 nextRequest.halRequest.frame_number,
4171 0, mLatestRequest, mLatestPhysicalRequest);
4172 }
4173 }
4174
4175 if (nextRequest.halRequest.settings != NULL) {
4176 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4177 nextRequest.halRequest.settings);
4178 }
4179
4180 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4181}
4182
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004183bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4184 ATRACE_CALL();
4185 bool updatesDetected = false;
4186
Emilian Peev4ec17882019-01-24 17:16:58 -08004187 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004188 for (auto tag : mSessionParamKeys) {
4189 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004190 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004191
4192 if (entry.count > 0) {
4193 bool isDifferent = false;
4194 if (lastEntry.count > 0) {
4195 // Have a last value, compare to see if changed
4196 if (lastEntry.type == entry.type &&
4197 lastEntry.count == entry.count) {
4198 // Same type and count, compare values
4199 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4200 size_t entryBytes = bytesPerValue * lastEntry.count;
4201 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4202 if (cmp != 0) {
4203 isDifferent = true;
4204 }
4205 } else {
4206 // Count or type has changed
4207 isDifferent = true;
4208 }
4209 } else {
4210 // No last entry, so always consider to be different
4211 isDifferent = true;
4212 }
4213
4214 if (isDifferent) {
4215 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004216 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4217 updatesDetected = true;
4218 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004219 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004220 }
4221 } else if (lastEntry.count > 0) {
4222 // Value has been removed
4223 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004224 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004225 updatesDetected = true;
4226 }
4227 }
4228
Emilian Peev4ec17882019-01-24 17:16:58 -08004229 bool reconfigureRequired;
4230 if (updatesDetected) {
4231 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4232 updatedParams);
4233 mLatestSessionParams = updatedParams;
4234 } else {
4235 reconfigureRequired = false;
4236 }
4237
4238 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004239}
4240
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004241bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004242 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004243 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004244 // Any function called from threadLoop() must not hold mInterfaceLock since
4245 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4246 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004247
4248 // Handle paused state.
4249 if (waitIfPaused()) {
4250 return true;
4251 }
4252
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004253 // Wait for the next batch of requests.
4254 waitForNextRequestBatch();
4255 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004256 return true;
4257 }
4258
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004259 // Get the latest request ID, if any
4260 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004261 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004262 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004263 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004264 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004265 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004266 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4267 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004268 }
4269
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004270 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4271 // or a single request from streaming or burst. In either case the first element
4272 // should contain the latest camera settings that we need to check for any session
4273 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004274 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004275 res = OK;
4276
4277 //Input stream buffers are already acquired at this point so an input stream
4278 //will not be able to move to idle state unless we force it.
4279 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4280 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4281 if (res != OK) {
4282 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4283 cleanUpFailedRequests(/*sendRequestError*/ false);
4284 return false;
4285 }
4286 }
4287
4288 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004289 sp<Camera3Device> parent = mParent.promote();
4290 if (parent != nullptr) {
4291 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004292 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004293 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004294
4295 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4296 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4297 if (res != OK) {
4298 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4299 cleanUpFailedRequests(/*sendRequestError*/ false);
4300 return false;
4301 }
4302 }
4303 }
4304 }
4305
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004306 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004307 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004308 if (res == TIMED_OUT) {
4309 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004310 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004311 // Check if any stream is abandoned.
4312 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004313 return true;
4314 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004315 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004316 return false;
4317 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004318
Zhijun Hecc27e112013-10-03 16:12:43 -07004319 // Inform waitUntilRequestProcessed thread of a new request ID
4320 {
4321 Mutex::Autolock al(mLatestRequestMutex);
4322
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004323 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004324 mLatestRequestSignal.signal();
4325 }
4326
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004327 // Submit a batch of requests to HAL.
4328 // Use flush lock only when submitting multilple requests in a batch.
4329 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4330 // which may take a long time to finish so synchronizing flush() and
4331 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4332 // For now, only synchronize for high speed recording and we should figure something out for
4333 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004334 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004335
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004336 if (useFlushLock) {
4337 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004338 }
4339
Zhijun Hef0645c12016-08-02 00:58:11 -07004340 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004341 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004342
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004343 sp<Camera3Device> parent = mParent.promote();
4344 if (parent != nullptr) {
4345 parent->mRequestBufferSM.onSubmittingRequest();
4346 }
4347
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004348 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004349 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004350 submitRequestSuccess = sendRequestsBatch();
4351
Shuzhen Wang686f6442017-06-20 16:16:04 -07004352 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4353 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004354
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004355 if (useFlushLock) {
4356 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004357 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004358
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004359 // Unset as current request
4360 {
4361 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004362 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004363 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004364 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004365
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004366 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004367}
4368
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004369status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004370 ATRACE_CALL();
4371
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004372 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004373 for (size_t i = 0; i < mNextRequests.size(); i++) {
4374 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004375 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4376 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4377 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4378
4379 // Prepare a request to HAL
4380 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4381
4382 // Insert any queued triggers (before metadata is locked)
4383 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004384 if (res < 0) {
4385 SET_ERR("RequestThread: Unable to insert triggers "
4386 "(capture request %d, HAL device: %s (%d)",
4387 halRequest->frame_number, strerror(-res), res);
4388 return INVALID_OPERATION;
4389 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004390
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004391 int triggerCount = res;
4392 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4393 mPrevTriggers = triggerCount;
4394
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004395 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
4396
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004397 // If the request is the same as last, or we had triggers last time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004398 bool newRequest =
4399 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004400 // Request settings are all the same within one batch, so only treat the first
4401 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004402 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004403 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004404 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004405 /**
4406 * HAL workaround:
4407 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4408 */
4409 res = addDummyTriggerIds(captureRequest);
4410 if (res != OK) {
4411 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4412 "(capture request %d, HAL device: %s (%d)",
4413 halRequest->frame_number, strerror(-res), res);
4414 return INVALID_OPERATION;
4415 }
4416
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004417 {
4418 // Correct metadata regions for distortion correction if enabled
4419 sp<Camera3Device> parent = mParent.promote();
4420 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004421 List<PhysicalCameraSettings>::iterator it;
4422 for (it = captureRequest->mSettingsList.begin();
4423 it != captureRequest->mSettingsList.end(); it++) {
4424 if (parent->mDistortionMappers.find(it->cameraId) ==
4425 parent->mDistortionMappers.end()) {
4426 continue;
4427 }
4428 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4429 &(it->metadata));
4430 if (res != OK) {
4431 SET_ERR("RequestThread: Unable to correct capture requests "
4432 "for lens distortion for request %d: %s (%d)",
4433 halRequest->frame_number, strerror(-res), res);
4434 return INVALID_OPERATION;
4435 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004436 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004437
4438 for (it = captureRequest->mSettingsList.begin();
4439 it != captureRequest->mSettingsList.end(); it++) {
4440 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4441 parent->mZoomRatioMappers.end()) {
4442 continue;
4443 }
4444
4445 camera_metadata_entry_t e = it->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
4446 if (e.count > 0 && e.data.f[0] != 1.0f) {
4447 cameraIdsWithZoom.insert(it->cameraId);
4448 }
4449
4450 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4451 &(it->metadata));
4452 if (res != OK) {
4453 SET_ERR("RequestThread: Unable to correct capture requests "
4454 "for zoom ratio for request %d: %s (%d)",
4455 halRequest->frame_number, strerror(-res), res);
4456 return INVALID_OPERATION;
4457 }
4458 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004459 if (captureRequest->mRotateAndCropAuto) {
4460 for (it = captureRequest->mSettingsList.begin();
4461 it != captureRequest->mSettingsList.end(); it++) {
4462 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4463 if (mapper != parent->mRotateAndCropMappers.end()) {
4464 res = mapper->second.updateCaptureRequest(&(it->metadata));
4465 if (res != OK) {
4466 SET_ERR("RequestThread: Unable to correct capture requests "
4467 "for rotate-and-crop for request %d: %s (%d)",
4468 halRequest->frame_number, strerror(-res), res);
4469 return INVALID_OPERATION;
4470 }
4471 }
4472 }
4473 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004474 }
4475 }
4476
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004477 /**
4478 * The request should be presorted so accesses in HAL
4479 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4480 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004481 captureRequest->mSettingsList.begin()->metadata.sort();
4482 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004483 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004484 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004485 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4486
4487 IF_ALOGV() {
4488 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4489 find_camera_metadata_ro_entry(
4490 halRequest->settings,
4491 ANDROID_CONTROL_AF_TRIGGER,
4492 &e
4493 );
4494 if (e.count > 0) {
4495 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4496 __FUNCTION__,
4497 halRequest->frame_number,
4498 e.data.u8[0]);
4499 }
4500 }
4501 } else {
4502 // leave request.settings NULL to indicate 'reuse latest given'
4503 ALOGVV("%s: Request settings are REUSED",
4504 __FUNCTION__);
4505 }
4506
Emilian Peevaebbe412018-01-15 13:53:24 +00004507 if (captureRequest->mSettingsList.size() > 1) {
4508 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4509 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004510 if (newRequest) {
4511 halRequest->physcam_settings =
4512 new const camera_metadata* [halRequest->num_physcam_settings];
4513 } else {
4514 halRequest->physcam_settings = nullptr;
4515 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004516 auto it = ++captureRequest->mSettingsList.begin();
4517 size_t i = 0;
4518 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4519 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004520 if (newRequest) {
4521 it->metadata.sort();
4522 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4523 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004524 }
4525 }
4526
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004527 uint32_t totalNumBuffers = 0;
4528
4529 // Fill in buffers
4530 if (captureRequest->mInputStream != NULL) {
4531 halRequest->input_buffer = &captureRequest->mInputBuffer;
4532 totalNumBuffers += 1;
4533 } else {
4534 halRequest->input_buffer = NULL;
4535 }
4536
4537 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4538 captureRequest->mOutputStreams.size());
4539 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004540 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004541
4542 sp<Camera3Device> parent = mParent.promote();
4543 if (parent == NULL) {
4544 // Should not happen, and nowhere to send errors to, so just log it
4545 CLOGE("RequestThread: Parent is gone");
4546 return INVALID_OPERATION;
4547 }
4548 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4549
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004550 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004551 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004552 sp<Camera3OutputStreamInterface> outputStream =
4553 captureRequest->mOutputStreams.editItemAt(j);
4554 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004555
4556 // Prepare video buffers for high speed recording on the first video request.
4557 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4558 // Only try to prepare video stream on the first video request.
4559 mPrepareVideoStream = false;
4560
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004561 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4562 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004563 while (res == NOT_ENOUGH_DATA) {
4564 res = outputStream->prepareNextBuffer();
4565 }
4566 if (res != OK) {
4567 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4568 __FUNCTION__, strerror(-res), res);
4569 outputStream->cancelPrepare();
4570 }
4571 }
4572
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004573 std::vector<size_t> uniqueSurfaceIds;
4574 res = outputStream->getUniqueSurfaceIds(
4575 captureRequest->mOutputSurfaces[streamId],
4576 &uniqueSurfaceIds);
4577 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4578 if (res != OK && res != INVALID_OPERATION) {
4579 ALOGE("%s: failed to query stream %d unique surface IDs",
4580 __FUNCTION__, streamId);
4581 return res;
4582 }
4583 if (res == OK) {
4584 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4585 }
4586
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004587 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004588 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004589 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004590 return TIMED_OUT;
4591 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004592 // HAL will request buffer through requestStreamBuffer API
4593 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
4594 buffer.stream = outputStream->asHalStream();
4595 buffer.buffer = nullptr;
4596 buffer.status = CAMERA3_BUFFER_STATUS_OK;
4597 buffer.acquire_fence = -1;
4598 buffer.release_fence = -1;
4599 } else {
4600 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4601 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004602 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004603 if (res != OK) {
4604 // Can't get output buffer from gralloc queue - this could be due to
4605 // abandoned queue or other consumer misbehavior, so not a fatal
4606 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004607 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004608 " %s (%d)", strerror(-res), res);
4609
4610 return TIMED_OUT;
4611 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004612 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004613
4614 {
4615 sp<Camera3Device> parent = mParent.promote();
4616 if (parent != nullptr) {
4617 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4618 for (const auto& settings : captureRequest->mSettingsList) {
4619 if ((streamCameraId.isEmpty() &&
4620 parent->getId() == settings.cameraId.c_str()) ||
4621 streamCameraId == settings.cameraId.c_str()) {
4622 outputStream->fireBufferRequestForFrameNumber(
4623 captureRequest->mResultExtras.frameNumber,
4624 settings.metadata);
4625 }
4626 }
4627 }
4628 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004629
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004630 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4631
4632 if (!physicalCameraId.isEmpty()) {
4633 // Physical stream isn't supported for input request.
4634 if (halRequest->input_buffer) {
4635 CLOGE("Physical stream is not supported for input request");
4636 return INVALID_OPERATION;
4637 }
4638 requestedPhysicalCameras.insert(physicalCameraId);
4639 }
4640 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004641 }
4642 totalNumBuffers += halRequest->num_output_buffers;
4643
4644 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004645 // If this request list is for constrained high speed recording (not
4646 // preview), and the current request is not the last one in the batch,
4647 // do not send callback to the app.
4648 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004649 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004650 hasCallback = false;
4651 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004652 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004653 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01004654 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4655 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4656 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4657 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4658 isStillCapture = true;
4659 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4660 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004661
4662 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
4663 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4664 isZslCapture = true;
4665 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004666 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004667 res = parent->registerInFlight(halRequest->frame_number,
4668 totalNumBuffers, captureRequest->mResultExtras,
4669 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004670 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004671 calculateMaxExpectedDuration(halRequest->settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004672 requestedPhysicalCameras, isStillCapture, isZslCapture,
4673 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004674 (mUseHalBufManager) ? uniqueSurfaceIdMap :
4675 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004676 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4677 ", burstId = %" PRId32 ".",
4678 __FUNCTION__,
4679 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4680 captureRequest->mResultExtras.burstId);
4681 if (res != OK) {
4682 SET_ERR("RequestThread: Unable to register new in-flight request:"
4683 " %s (%d)", strerror(-res), res);
4684 return INVALID_OPERATION;
4685 }
4686 }
4687
4688 return OK;
4689}
4690
Igor Murashkin1e479c02013-09-06 16:55:14 -07004691CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004692 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004693 Mutex::Autolock al(mLatestRequestMutex);
4694
4695 ALOGV("RequestThread::%s", __FUNCTION__);
4696
4697 return mLatestRequest;
4698}
4699
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004700bool Camera3Device::RequestThread::isStreamPending(
4701 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004702 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004703 Mutex::Autolock l(mRequestLock);
4704
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004705 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004706 if (!nextRequest.submitted) {
4707 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4708 if (stream == s) return true;
4709 }
4710 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004711 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004712 }
4713
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004714 for (const auto& request : mRequestQueue) {
4715 for (const auto& s : request->mOutputStreams) {
4716 if (stream == s) return true;
4717 }
4718 if (stream == request->mInputStream) return true;
4719 }
4720
4721 for (const auto& request : mRepeatingRequests) {
4722 for (const auto& s : request->mOutputStreams) {
4723 if (stream == s) return true;
4724 }
4725 if (stream == request->mInputStream) return true;
4726 }
4727
4728 return false;
4729}
Jianing Weicb0652e2014-03-12 18:29:36 -07004730
Emilian Peev40ead602017-09-26 15:46:36 +01004731bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4732 ATRACE_CALL();
4733 Mutex::Autolock l(mRequestLock);
4734
4735 for (const auto& nextRequest : mNextRequests) {
4736 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4737 if (s.first == streamId) {
4738 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4739 if (it != s.second.end()) {
4740 return true;
4741 }
4742 }
4743 }
4744 }
4745
4746 for (const auto& request : mRequestQueue) {
4747 for (const auto& s : request->mOutputSurfaces) {
4748 if (s.first == streamId) {
4749 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4750 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004751 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004752 }
4753 }
4754 }
4755 }
4756
4757 for (const auto& request : mRepeatingRequests) {
4758 for (const auto& s : request->mOutputSurfaces) {
4759 if (s.first == streamId) {
4760 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4761 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004762 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004763 }
4764 }
4765 }
4766 }
4767
4768 return false;
4769}
4770
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004771void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4772 if (!mUseHalBufManager) {
4773 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4774 return;
4775 }
4776
4777 Mutex::Autolock pl(mPauseLock);
4778 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004779 mInterface->signalPipelineDrain(streamIds);
4780 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004781 }
4782 // If request thread is still busy, wait until paused then notify HAL
4783 mNotifyPipelineDrain = true;
4784 mStreamIdsToBeDrained = streamIds;
4785}
4786
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004787void Camera3Device::RequestThread::clearPreviousRequest() {
4788 Mutex::Autolock l(mRequestLock);
4789 mPrevRequest.clear();
4790}
4791
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004792status_t Camera3Device::RequestThread::switchToOffline(
4793 const std::vector<int32_t>& streamsToKeep,
4794 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004795 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4796 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004797 Mutex::Autolock l(mRequestLock);
4798 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
4799
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004800 // Wait until request thread is fully stopped
4801 // TBD: check if request thread is being paused by other APIs (shouldn't be)
4802
4803 // We could also check for mRepeatingRequests.empty(), but the API interface
4804 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
4805 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004806 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4807 while (!queueEmpty) {
4808 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
4809 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004810 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004811 return res;
4812 } else if (res != OK) {
4813 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
4814 __FUNCTION__, strerror(-res), res);
4815 return res;
4816 }
4817 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4818 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004819
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004820 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004821 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004822}
4823
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004824status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4825 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4826 ATRACE_CALL();
4827 Mutex::Autolock l(mTriggerMutex);
4828 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4829 return BAD_VALUE;
4830 }
4831 mRotateAndCropOverride = rotateAndCropValue;
4832 return OK;
4833}
4834
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004835nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004836 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004837 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004838 return mExpectedInflightDuration > kMinInflightDuration ?
4839 mExpectedInflightDuration : kMinInflightDuration;
4840}
4841
Emilian Peevaebbe412018-01-15 13:53:24 +00004842void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4843 camera3_capture_request_t *halRequest) {
4844 if ((request == nullptr) || (halRequest == nullptr)) {
4845 ALOGE("%s: Invalid request!", __FUNCTION__);
4846 return;
4847 }
4848
4849 if (halRequest->num_physcam_settings > 0) {
4850 if (halRequest->physcam_id != nullptr) {
4851 delete [] halRequest->physcam_id;
4852 halRequest->physcam_id = nullptr;
4853 }
4854 if (halRequest->physcam_settings != nullptr) {
4855 auto it = ++(request->mSettingsList.begin());
4856 size_t i = 0;
4857 for (; it != request->mSettingsList.end(); it++, i++) {
4858 it->metadata.unlock(halRequest->physcam_settings[i]);
4859 }
4860 delete [] halRequest->physcam_settings;
4861 halRequest->physcam_settings = nullptr;
4862 }
4863 }
4864}
4865
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004866void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4867 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004868 return;
4869 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004870
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004871 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004872 // Skip the ones that have been submitted successfully.
4873 if (nextRequest.submitted) {
4874 continue;
4875 }
4876
4877 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4878 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4879 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4880
4881 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004882 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004883 }
4884
Emilian Peevaebbe412018-01-15 13:53:24 +00004885 cleanupPhysicalSettings(captureRequest, halRequest);
4886
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004887 if (captureRequest->mInputStream != NULL) {
4888 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4889 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4890 }
4891
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004892 // No output buffer can be returned when using HAL buffer manager
4893 if (!mUseHalBufManager) {
4894 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4895 //Buffers that failed processing could still have
4896 //valid acquire fence.
4897 int acquireFence = (*outputBuffers)[i].acquire_fence;
4898 if (0 <= acquireFence) {
4899 close(acquireFence);
4900 outputBuffers->editItemAt(i).acquire_fence = -1;
4901 }
4902 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4903 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
4904 /*timestampIncreasing*/true, std::vector<size_t> (),
4905 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004906 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004907 }
4908
4909 if (sendRequestError) {
4910 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004911 sp<NotificationListener> listener = mListener.promote();
4912 if (listener != NULL) {
4913 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004914 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004915 captureRequest->mResultExtras);
4916 }
4917 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004918
4919 // Remove yet-to-be submitted inflight request from inflightMap
4920 {
4921 sp<Camera3Device> parent = mParent.promote();
4922 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004923 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004924 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4925 if (idx >= 0) {
4926 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4927 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4928 parent->removeInFlightMapEntryLocked(idx);
4929 }
4930 }
4931 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004932 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004933
4934 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004935 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004936}
4937
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004938void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004939 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004940 // Optimized a bit for the simple steady-state case (single repeating
4941 // request), to avoid putting that request in the queue temporarily.
4942 Mutex::Autolock l(mRequestLock);
4943
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004944 assert(mNextRequests.empty());
4945
4946 NextRequest nextRequest;
4947 nextRequest.captureRequest = waitForNextRequestLocked();
4948 if (nextRequest.captureRequest == nullptr) {
4949 return;
4950 }
4951
4952 nextRequest.halRequest = camera3_capture_request_t();
4953 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004954 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004955
4956 // Wait for additional requests
4957 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4958
4959 for (size_t i = 1; i < batchSize; i++) {
4960 NextRequest additionalRequest;
4961 additionalRequest.captureRequest = waitForNextRequestLocked();
4962 if (additionalRequest.captureRequest == nullptr) {
4963 break;
4964 }
4965
4966 additionalRequest.halRequest = camera3_capture_request_t();
4967 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004968 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004969 }
4970
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004971 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004972 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004973 mNextRequests.size(), batchSize);
4974 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004975 }
4976
4977 return;
4978}
4979
4980sp<Camera3Device::CaptureRequest>
4981 Camera3Device::RequestThread::waitForNextRequestLocked() {
4982 status_t res;
4983 sp<CaptureRequest> nextRequest;
4984
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004985 while (mRequestQueue.empty()) {
4986 if (!mRepeatingRequests.empty()) {
4987 // Always atomically enqueue all requests in a repeating request
4988 // list. Guarantees a complete in-sequence set of captures to
4989 // application.
4990 const RequestList &requests = mRepeatingRequests;
4991 RequestList::const_iterator firstRequest =
4992 requests.begin();
4993 nextRequest = *firstRequest;
4994 mRequestQueue.insert(mRequestQueue.end(),
4995 ++firstRequest,
4996 requests.end());
4997 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004998
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004999 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005000
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005001 break;
5002 }
5003
5004 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5005
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005006 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5007 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005008 Mutex::Autolock pl(mPauseLock);
5009 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005010 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005011 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005012 if (mNotifyPipelineDrain) {
5013 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5014 mNotifyPipelineDrain = false;
5015 mStreamIdsToBeDrained.clear();
5016 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005017 // Let the tracker know
5018 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5019 if (statusTracker != 0) {
5020 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5021 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005022 sp<Camera3Device> parent = mParent.promote();
5023 if (parent != nullptr) {
5024 parent->mRequestBufferSM.onRequestThreadPaused();
5025 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005026 }
5027 // Stop waiting for now and let thread management happen
5028 return NULL;
5029 }
5030 }
5031
5032 if (nextRequest == NULL) {
5033 // Don't have a repeating request already in hand, so queue
5034 // must have an entry now.
5035 RequestList::iterator firstRequest =
5036 mRequestQueue.begin();
5037 nextRequest = *firstRequest;
5038 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005039 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5040 sp<NotificationListener> listener = mListener.promote();
5041 if (listener != NULL) {
5042 listener->notifyRequestQueueEmpty();
5043 }
5044 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005045 }
5046
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005047 // In case we've been unpaused by setPaused clearing mDoPause, need to
5048 // update internal pause state (capture/setRepeatingRequest unpause
5049 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005050 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005051 if (mPaused) {
5052 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5053 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5054 if (statusTracker != 0) {
5055 statusTracker->markComponentActive(mStatusId);
5056 }
5057 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005058 mPaused = false;
5059
5060 // Check if we've reconfigured since last time, and reset the preview
5061 // request if so. Can't use 'NULL request == repeat' across configure calls.
5062 if (mReconfigured) {
5063 mPrevRequest.clear();
5064 mReconfigured = false;
5065 }
5066
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005067 if (nextRequest != NULL) {
5068 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005069 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5070 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005071
5072 // Since RequestThread::clear() removes buffers from the input stream,
5073 // get the right buffer here before unlocking mRequestLock
5074 if (nextRequest->mInputStream != NULL) {
5075 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5076 if (res != OK) {
5077 // Can't get input buffer from gralloc queue - this could be due to
5078 // disconnected queue or other producer misbehavior, so not a fatal
5079 // error
5080 ALOGE("%s: Can't get input buffer, skipping request:"
5081 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005082
5083 sp<NotificationListener> listener = mListener.promote();
5084 if (listener != NULL) {
5085 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005086 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005087 nextRequest->mResultExtras);
5088 }
5089 return NULL;
5090 }
5091 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005092 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005093
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005094 return nextRequest;
5095}
5096
5097bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005098 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005099 status_t res;
5100 Mutex::Autolock l(mPauseLock);
5101 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005102 if (mPaused == false) {
5103 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005104 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005105 if (mNotifyPipelineDrain) {
5106 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5107 mNotifyPipelineDrain = false;
5108 mStreamIdsToBeDrained.clear();
5109 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005110 // Let the tracker know
5111 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5112 if (statusTracker != 0) {
5113 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5114 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005115 sp<Camera3Device> parent = mParent.promote();
5116 if (parent != nullptr) {
5117 parent->mRequestBufferSM.onRequestThreadPaused();
5118 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005119 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005120
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005121 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005122 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005123 return true;
5124 }
5125 }
5126 // We don't set mPaused to false here, because waitForNextRequest needs
5127 // to further manage the paused state in case of starvation.
5128 return false;
5129}
5130
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005131void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005132 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005133 // With work to do, mark thread as unpaused.
5134 // If paused by request (setPaused), don't resume, to avoid
5135 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005136 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005137 Mutex::Autolock p(mPauseLock);
5138 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005139 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5140 if (mPaused) {
5141 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5142 if (statusTracker != 0) {
5143 statusTracker->markComponentActive(mStatusId);
5144 }
5145 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005146 mPaused = false;
5147 }
5148}
5149
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005150void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5151 sp<Camera3Device> parent = mParent.promote();
5152 if (parent != NULL) {
5153 va_list args;
5154 va_start(args, fmt);
5155
5156 parent->setErrorStateV(fmt, args);
5157
5158 va_end(args);
5159 }
5160}
5161
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005162status_t Camera3Device::RequestThread::insertTriggers(
5163 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005164 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005165 Mutex::Autolock al(mTriggerMutex);
5166
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005167 sp<Camera3Device> parent = mParent.promote();
5168 if (parent == NULL) {
5169 CLOGE("RequestThread: Parent is gone");
5170 return DEAD_OBJECT;
5171 }
5172
Emilian Peevaebbe412018-01-15 13:53:24 +00005173 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005174 size_t count = mTriggerMap.size();
5175
5176 for (size_t i = 0; i < count; ++i) {
5177 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005178 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005179
5180 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5181 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5182 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005183 if (isAeTrigger) {
5184 request->mResultExtras.precaptureTriggerId = triggerId;
5185 mCurrentPreCaptureTriggerId = triggerId;
5186 } else {
5187 request->mResultExtras.afTriggerId = triggerId;
5188 mCurrentAfTriggerId = triggerId;
5189 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005190 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005191 }
5192
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005193 camera_metadata_entry entry = metadata.find(tag);
5194
5195 if (entry.count > 0) {
5196 /**
5197 * Already has an entry for this trigger in the request.
5198 * Rewrite it with our requested trigger value.
5199 */
5200 RequestTrigger oldTrigger = trigger;
5201
5202 oldTrigger.entryValue = entry.data.u8[0];
5203
5204 mTriggerReplacedMap.add(tag, oldTrigger);
5205 } else {
5206 /**
5207 * More typical, no trigger entry, so we just add it
5208 */
5209 mTriggerRemovedMap.add(tag, trigger);
5210 }
5211
5212 status_t res;
5213
5214 switch (trigger.getTagType()) {
5215 case TYPE_BYTE: {
5216 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5217 res = metadata.update(tag,
5218 &entryValue,
5219 /*count*/1);
5220 break;
5221 }
5222 case TYPE_INT32:
5223 res = metadata.update(tag,
5224 &trigger.entryValue,
5225 /*count*/1);
5226 break;
5227 default:
5228 ALOGE("%s: Type not supported: 0x%x",
5229 __FUNCTION__,
5230 trigger.getTagType());
5231 return INVALID_OPERATION;
5232 }
5233
5234 if (res != OK) {
5235 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5236 ", value %d", __FUNCTION__, trigger.getTagName(),
5237 trigger.entryValue);
5238 return res;
5239 }
5240
5241 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5242 trigger.getTagName(),
5243 trigger.entryValue);
5244 }
5245
5246 mTriggerMap.clear();
5247
5248 return count;
5249}
5250
5251status_t Camera3Device::RequestThread::removeTriggers(
5252 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005253 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005254 Mutex::Autolock al(mTriggerMutex);
5255
Emilian Peevaebbe412018-01-15 13:53:24 +00005256 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005257
5258 /**
5259 * Replace all old entries with their old values.
5260 */
5261 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5262 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5263
5264 status_t res;
5265
5266 uint32_t tag = trigger.metadataTag;
5267 switch (trigger.getTagType()) {
5268 case TYPE_BYTE: {
5269 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5270 res = metadata.update(tag,
5271 &entryValue,
5272 /*count*/1);
5273 break;
5274 }
5275 case TYPE_INT32:
5276 res = metadata.update(tag,
5277 &trigger.entryValue,
5278 /*count*/1);
5279 break;
5280 default:
5281 ALOGE("%s: Type not supported: 0x%x",
5282 __FUNCTION__,
5283 trigger.getTagType());
5284 return INVALID_OPERATION;
5285 }
5286
5287 if (res != OK) {
5288 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5289 ", trigger value %d", __FUNCTION__,
5290 trigger.getTagName(), trigger.entryValue);
5291 return res;
5292 }
5293 }
5294 mTriggerReplacedMap.clear();
5295
5296 /**
5297 * Remove all new entries.
5298 */
5299 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5300 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5301 status_t res = metadata.erase(trigger.metadataTag);
5302
5303 if (res != OK) {
5304 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5305 ", trigger value %d", __FUNCTION__,
5306 trigger.getTagName(), trigger.entryValue);
5307 return res;
5308 }
5309 }
5310 mTriggerRemovedMap.clear();
5311
5312 return OK;
5313}
5314
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005315status_t Camera3Device::RequestThread::addDummyTriggerIds(
5316 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005317 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005318 static const int32_t dummyTriggerId = 1;
5319 status_t res;
5320
Emilian Peevaebbe412018-01-15 13:53:24 +00005321 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005322
5323 // If AF trigger is active, insert a dummy AF trigger ID if none already
5324 // exists
5325 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5326 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5327 if (afTrigger.count > 0 &&
5328 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5329 afId.count == 0) {
5330 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5331 if (res != OK) return res;
5332 }
5333
5334 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5335 // if none already exists
5336 camera_metadata_entry pcTrigger =
5337 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5338 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5339 if (pcTrigger.count > 0 &&
5340 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5341 pcId.count == 0) {
5342 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5343 &dummyTriggerId, 1);
5344 if (res != OK) return res;
5345 }
5346
5347 return OK;
5348}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005349
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005350bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5351 const sp<CaptureRequest> &request) {
5352 ATRACE_CALL();
5353
5354 if (request->mRotateAndCropAuto) {
5355 Mutex::Autolock l(mTriggerMutex);
5356 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5357
5358 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5359 if (rotateAndCropEntry.count > 0) {
5360 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5361 return false;
5362 } else {
5363 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5364 return true;
5365 }
5366 } else {
5367 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5368 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5369 &rotateAndCrop_u8, 1);
5370 return true;
5371 }
5372 }
5373 return false;
5374}
5375
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005376/**
5377 * PreparerThread inner class methods
5378 */
5379
5380Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005381 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005382 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005383}
5384
5385Camera3Device::PreparerThread::~PreparerThread() {
5386 Thread::requestExitAndWait();
5387 if (mCurrentStream != nullptr) {
5388 mCurrentStream->cancelPrepare();
5389 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5390 mCurrentStream.clear();
5391 }
5392 clear();
5393}
5394
Ruben Brunkc78ac262015-08-13 17:58:46 -07005395status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005396 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005397 status_t res;
5398
5399 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005400 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005401
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005402 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005403 if (res == OK) {
5404 // No preparation needed, fire listener right off
5405 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005406 if (listener != NULL) {
5407 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005408 }
5409 return OK;
5410 } else if (res != NOT_ENOUGH_DATA) {
5411 return res;
5412 }
5413
5414 // Need to prepare, start up thread if necessary
5415 if (!mActive) {
5416 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5417 // isn't running
5418 Thread::requestExitAndWait();
5419 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5420 if (res != OK) {
5421 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005422 if (listener != NULL) {
5423 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005424 }
5425 return res;
5426 }
5427 mCancelNow = false;
5428 mActive = true;
5429 ALOGV("%s: Preparer stream started", __FUNCTION__);
5430 }
5431
5432 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005433 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005434 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5435
5436 return OK;
5437}
5438
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005439void Camera3Device::PreparerThread::pause() {
5440 ATRACE_CALL();
5441
5442 Mutex::Autolock l(mLock);
5443
5444 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5445 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5446 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5447 int currentMaxCount = mCurrentMaxCount;
5448 mPendingStreams.clear();
5449 mCancelNow = true;
5450 while (mActive) {
5451 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5452 if (res == TIMED_OUT) {
5453 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5454 return;
5455 } else if (res != OK) {
5456 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5457 return;
5458 }
5459 }
5460
5461 //Check whether the prepare thread was able to complete the current
5462 //stream. In case work is still pending emplace it along with the rest
5463 //of the streams in the pending list.
5464 if (currentStream != nullptr) {
5465 if (!mCurrentPrepareComplete) {
5466 pendingStreams.emplace(currentMaxCount, currentStream);
5467 }
5468 }
5469
5470 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5471 for (const auto& it : mPendingStreams) {
5472 it.second->cancelPrepare();
5473 }
5474}
5475
5476status_t Camera3Device::PreparerThread::resume() {
5477 ATRACE_CALL();
5478 status_t res;
5479
5480 Mutex::Autolock l(mLock);
5481 sp<NotificationListener> listener = mListener.promote();
5482
5483 if (mActive) {
5484 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5485 return NO_INIT;
5486 }
5487
5488 auto it = mPendingStreams.begin();
5489 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005490 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005491 if (res == OK) {
5492 if (listener != NULL) {
5493 listener->notifyPrepared(it->second->getId());
5494 }
5495 it = mPendingStreams.erase(it);
5496 } else if (res != NOT_ENOUGH_DATA) {
5497 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5498 res, strerror(-res));
5499 it = mPendingStreams.erase(it);
5500 } else {
5501 it++;
5502 }
5503 }
5504
5505 if (mPendingStreams.empty()) {
5506 return OK;
5507 }
5508
5509 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5510 if (res != OK) {
5511 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5512 __FUNCTION__, res, strerror(-res));
5513 return res;
5514 }
5515 mCancelNow = false;
5516 mActive = true;
5517 ALOGV("%s: Preparer stream started", __FUNCTION__);
5518
5519 return OK;
5520}
5521
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005522status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005523 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005524 Mutex::Autolock l(mLock);
5525
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005526 for (const auto& it : mPendingStreams) {
5527 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005528 }
5529 mPendingStreams.clear();
5530 mCancelNow = true;
5531
5532 return OK;
5533}
5534
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005535void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005536 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005537 Mutex::Autolock l(mLock);
5538 mListener = listener;
5539}
5540
5541bool Camera3Device::PreparerThread::threadLoop() {
5542 status_t res;
5543 {
5544 Mutex::Autolock l(mLock);
5545 if (mCurrentStream == nullptr) {
5546 // End thread if done with work
5547 if (mPendingStreams.empty()) {
5548 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5549 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5550 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5551 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005552 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005553 return false;
5554 }
5555
5556 // Get next stream to prepare
5557 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005558 mCurrentStream = it->second;
5559 mCurrentMaxCount = it->first;
5560 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005561 mPendingStreams.erase(it);
5562 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5563 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5564 } else if (mCancelNow) {
5565 mCurrentStream->cancelPrepare();
5566 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5567 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5568 mCurrentStream.clear();
5569 mCancelNow = false;
5570 return true;
5571 }
5572 }
5573
5574 res = mCurrentStream->prepareNextBuffer();
5575 if (res == NOT_ENOUGH_DATA) return true;
5576 if (res != OK) {
5577 // Something bad happened; try to recover by cancelling prepare and
5578 // signalling listener anyway
5579 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5580 mCurrentStream->getId(), res, strerror(-res));
5581 mCurrentStream->cancelPrepare();
5582 }
5583
5584 // This stream has finished, notify listener
5585 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005586 sp<NotificationListener> listener = mListener.promote();
5587 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005588 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5589 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005590 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005591 }
5592
5593 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5594 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005595 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005596
5597 return true;
5598}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005599
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005600status_t Camera3Device::RequestBufferStateMachine::initialize(
5601 sp<camera3::StatusTracker> statusTracker) {
5602 if (statusTracker == nullptr) {
5603 ALOGE("%s: statusTracker is null", __FUNCTION__);
5604 return BAD_VALUE;
5605 }
5606
5607 std::lock_guard<std::mutex> lock(mLock);
5608 mStatusTracker = statusTracker;
5609 mRequestBufferStatusId = statusTracker->addComponent();
5610 return OK;
5611}
5612
5613bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5614 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005615 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005616 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005617 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005618 return true;
5619 }
5620 return false;
5621}
5622
5623void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5624 std::lock_guard<std::mutex> lock(mLock);
5625 if (!mRequestBufferOngoing) {
5626 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5627 return;
5628 }
5629 mRequestBufferOngoing = false;
5630 if (mStatus == RB_STATUS_PENDING_STOP) {
5631 checkSwitchToStopLocked();
5632 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005633 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005634}
5635
5636void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5637 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005638 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005639 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005640 return;
5641}
5642
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005643void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005644 std::lock_guard<std::mutex> lock(mLock);
5645 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005646 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5647 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005648 mInflightMapEmpty = false;
5649 if (mStatus == RB_STATUS_STOPPED) {
5650 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005651 }
5652 return;
5653}
5654
5655void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5656 std::lock_guard<std::mutex> lock(mLock);
5657 mRequestThreadPaused = true;
5658 if (mStatus == RB_STATUS_PENDING_STOP) {
5659 checkSwitchToStopLocked();
5660 }
5661 return;
5662}
5663
5664void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5665 std::lock_guard<std::mutex> lock(mLock);
5666 mInflightMapEmpty = true;
5667 if (mStatus == RB_STATUS_PENDING_STOP) {
5668 checkSwitchToStopLocked();
5669 }
5670 return;
5671}
5672
5673void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5674 std::lock_guard<std::mutex> lock(mLock);
5675 if (!checkSwitchToStopLocked()) {
5676 mStatus = RB_STATUS_PENDING_STOP;
5677 }
5678 return;
5679}
5680
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005681bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5682 std::lock_guard<std::mutex> lock(mLock);
5683 if (mRequestBufferOngoing) {
5684 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5685 __FUNCTION__);
5686 return false;
5687 }
5688 mSwitchedToOffline = true;
5689 mInflightMapEmpty = true;
5690 mRequestThreadPaused = true;
5691 mStatus = RB_STATUS_STOPPED;
5692 return true;
5693}
5694
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005695void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5696 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5697 if (statusTracker != nullptr) {
5698 if (active) {
5699 statusTracker->markComponentActive(mRequestBufferStatusId);
5700 } else {
5701 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5702 }
5703 }
5704}
5705
5706bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5707 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5708 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005709 return true;
5710 }
5711 return false;
5712}
5713
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005714bool Camera3Device::startRequestBuffer() {
5715 return mRequestBufferSM.startRequestBuffer();
5716}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005717
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005718void Camera3Device::endRequestBuffer() {
5719 mRequestBufferSM.endRequestBuffer();
5720}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005721
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005722nsecs_t Camera3Device::getWaitDuration() {
5723 return kBaseGetBufferWait + getExpectedInFlightDuration();
5724}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005725
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005726void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5727 mInterface->getInflightBufferKeys(out);
5728}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005729
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005730void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5731 mInterface->getInflightRequestBufferKeys(out);
5732}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005733
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005734std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5735 std::vector<sp<Camera3StreamInterface>> ret;
5736 bool hasInputStream = mInputStream != nullptr;
5737 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5738 if (hasInputStream) {
5739 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005740 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005741 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5742 ret.push_back(mOutputStreams[i]);
5743 }
5744 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5745 ret.push_back(mDeletedStreams[i]);
5746 }
5747 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005748}
5749
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005750status_t Camera3Device::switchToOffline(
5751 const std::vector<int32_t>& streamsToKeep,
5752 /*out*/ sp<CameraOfflineSessionBase>* session) {
5753 ATRACE_CALL();
5754 if (session == nullptr) {
5755 ALOGE("%s: session must not be null", __FUNCTION__);
5756 return BAD_VALUE;
5757 }
5758
5759 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005760
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005761 bool hasInputStream = mInputStream != nullptr;
5762 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
5763 bool inputStreamSupportsOffline = hasInputStream ?
5764 mInputStream->getOfflineProcessingSupport() : false;
5765 auto outputStreamIds = mOutputStreams.getStreamIds();
5766 auto streamIds = outputStreamIds;
5767 if (hasInputStream) {
5768 streamIds.push_back(mInputStream->getId());
5769 }
5770
5771 // Check all streams in streamsToKeep supports offline mode
5772 for (auto id : streamsToKeep) {
5773 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5774 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
5775 return BAD_VALUE;
5776 } else if (id == inputStreamId) {
5777 if (!inputStreamSupportsOffline) {
5778 ALOGE("%s: input stream %d cannot be switched to offline",
5779 __FUNCTION__, id);
5780 return BAD_VALUE;
5781 }
5782 } else {
5783 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
5784 if (!stream->getOfflineProcessingSupport()) {
5785 ALOGE("%s: output stream %d cannot be switched to offline",
5786 __FUNCTION__, id);
5787 return BAD_VALUE;
5788 }
5789 }
5790 }
5791
5792 // TODO: block surface sharing and surface group streams until we can support them
5793
5794 // Stop repeating request, wait until all remaining requests are submitted, then call into
5795 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005796 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
5797 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005798 camera3::BufferRecords bufferRecords;
5799 status_t ret = mRequestThread->switchToOffline(
5800 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005801
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005802 if (ret != OK) {
5803 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
5804 return ret;
5805 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005806
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005807 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
5808 if (!succ) {
5809 SET_ERR("HAL must not be calling requestStreamBuffers call");
5810 // TODO: block ALL callbacks from HAL till app configured new streams?
5811 return UNKNOWN_ERROR;
5812 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005813
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005814 // Verify offlineSessionInfo
5815 std::vector<int32_t> offlineStreamIds;
5816 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
5817 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5818 // verify stream IDs
5819 int32_t id = offlineStream.id;
5820 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5821 SET_ERR("stream ID %d not found!", id);
5822 return UNKNOWN_ERROR;
5823 }
5824
5825 // When not using HAL buf manager, only allow streams requested by app to be preserved
5826 if (!mUseHalBufManager) {
5827 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
5828 SET_ERR("stream ID %d must not be switched to offline!", id);
5829 return UNKNOWN_ERROR;
5830 }
5831 }
5832
5833 offlineStreamIds.push_back(id);
5834 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
5835 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
5836 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
5837 // Verify number of outstanding buffers
5838 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
5839 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
5840 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
5841 return UNKNOWN_ERROR;
5842 }
5843 }
5844
5845 // Verify all streams to be deleted don't have any outstanding buffers
5846 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5847 inputStreamId) == offlineStreamIds.end()) {
5848 if (mInputStream->hasOutstandingBuffers()) {
5849 SET_ERR("Input stream %d still has %zu outstanding buffer!",
5850 inputStreamId, mInputStream->getOutstandingBuffersCount());
5851 return UNKNOWN_ERROR;
5852 }
5853 }
5854
5855 for (const auto& outStreamId : outputStreamIds) {
5856 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5857 outStreamId) == offlineStreamIds.end()) {
5858 auto outStream = mOutputStreams.get(outStreamId);
5859 if (outStream->hasOutstandingBuffers()) {
5860 SET_ERR("Output stream %d still has %zu outstanding buffer!",
5861 outStreamId, outStream->getOutstandingBuffersCount());
5862 return UNKNOWN_ERROR;
5863 }
5864 }
5865 }
5866
5867 InFlightRequestMap offlineReqs;
5868 // Verify inflight requests and their pending buffers
5869 {
5870 std::lock_guard<std::mutex> l(mInFlightLock);
5871 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
5872 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
5873 if (idx == NAME_NOT_FOUND) {
5874 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
5875 return UNKNOWN_ERROR;
5876 }
5877
5878 const auto& inflightReq = mInFlightMap.valueAt(idx);
5879 // TODO: check specific stream IDs
5880 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
5881 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
5882 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
5883 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
5884 return UNKNOWN_ERROR;
5885 }
5886 offlineReqs.add(offlineReq.frameNumber, inflightReq);
5887 }
5888 }
5889
5890 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005891 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005892 camera3::StreamSet offlineStreamSet;
5893 sp<camera3::Camera3Stream> inputStream;
5894 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5895 int32_t id = offlineStream.id;
5896 if (mInputStream != nullptr && id == mInputStream->getId()) {
5897 inputStream = mInputStream;
5898 } else {
5899 offlineStreamSet.add(id, mOutputStreams.get(id));
5900 }
5901 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005902
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005903 // TODO: check if we need to lock before copying states
5904 // though technically no other thread should be talking to Camera3Device at this point
5905 Camera3OfflineStates offlineStates(
5906 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07005907 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
5908 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
5909 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
5910 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
5911 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
5912 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
5913 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005914
5915 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
5916 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
5917
5918 // Delete all streams that has been transferred to offline session
5919 Mutex::Autolock l(mLock);
5920 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5921 int32_t id = offlineStream.id;
5922 if (mInputStream != nullptr && id == mInputStream->getId()) {
5923 mInputStream.clear();
5924 } else {
5925 mOutputStreams.remove(id);
5926 }
5927 }
5928
5929 // disconnect all other streams and switch to UNCONFIGURED state
5930 if (mInputStream != nullptr) {
5931 ret = mInputStream->disconnect();
5932 if (ret != OK) {
5933 SET_ERR_L("disconnect input stream failed!");
5934 return UNKNOWN_ERROR;
5935 }
5936 }
5937
5938 for (auto streamId : mOutputStreams.getStreamIds()) {
5939 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
5940 ret = stream->disconnect();
5941 if (ret != OK) {
5942 SET_ERR_L("disconnect output stream %d failed!", streamId);
5943 return UNKNOWN_ERROR;
5944 }
5945 }
5946
5947 mInputStream.clear();
5948 mOutputStreams.clear();
5949 mNeedConfig = true;
5950 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
5951 mOperatingMode = NO_MODE;
5952 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005953 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005954
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005955 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005956 // TO be done by CameraDeviceClient/Camera3OfflineSession
5957 // register the offline client to camera service
5958 // Setup result passthing threads etc
5959 // Initialize offline session so HAL can start sending callback to it (result Fmq)
5960 // TODO: check how many onIdle callback will be sent
5961 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005962}
5963
Emilian Peevcc0b7952020-01-07 13:54:47 -08005964void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5965 ATRACE_CALL();
5966
5967 if (offlineStreamIds == nullptr) {
5968 return;
5969 }
5970
5971 Mutex::Autolock il(mInterfaceLock);
5972
5973 auto streamIds = mOutputStreams.getStreamIds();
5974 bool hasInputStream = mInputStream != nullptr;
5975 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5976 offlineStreamIds->push_back(mInputStream->getId());
5977 }
5978
5979 for (const auto & streamId : streamIds) {
5980 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5981 // Streams that use the camera buffer manager are currently not supported in
5982 // offline mode
5983 if (stream->getOfflineProcessingSupport() &&
5984 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5985 offlineStreamIds->push_back(streamId);
5986 }
5987 }
5988}
5989
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005990status_t Camera3Device::setRotateAndCropAutoBehavior(
5991 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5992 ATRACE_CALL();
5993 Mutex::Autolock il(mInterfaceLock);
5994 Mutex::Autolock l(mLock);
5995 if (mRequestThread == nullptr) {
5996 return INVALID_OPERATION;
5997 }
5998 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5999}
6000
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006001}; // namespace android