blob: 87bdef6fd4b65dfccf08d5730f110372576c557c [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"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700759 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800760 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700761 r.numBuffersLeft);
762 }
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,
1046 mInFlightLock, mInFlightMap,
1047 mOutputLock, mResultQueue, mResultSignal,
1048 mNextShutterFrameNumber,
1049 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1050 mNextResultFrameNumber,
1051 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1052 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1053 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001054 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1055 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001056 };
1057
Yifan Honga640c5a2017-04-12 16:30:31 -07001058 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001059 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001060 }
1061 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001062 return hardware::Void();
1063}
1064
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001065// Only one processCaptureResult should be called at a time, so
1066// the locks won't block. The locks are present here simply to enforce this.
1067hardware::Return<void> Camera3Device::processCaptureResult(
1068 const hardware::hidl_vec<
1069 hardware::camera::device::V3_2::CaptureResult>& results) {
1070 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1071
1072 // Ideally we should grab mLock, but that can lead to deadlock, and
1073 // it's not super important to get up to date value of mStatus for this
1074 // warning print, hence skipping the lock here
1075 if (mStatus == STATUS_ERROR) {
1076 // Per API contract, HAL should act as closed after device error
1077 // But mStatus can be set to error by framework as well, so just log
1078 // a warning here.
1079 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1080 }
1081
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001082 sp<NotificationListener> listener;
1083 {
1084 std::lock_guard<std::mutex> l(mOutputLock);
1085 listener = mListener.promote();
1086 }
1087
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001088 if (mProcessCaptureResultLock.tryLock() != OK) {
1089 // This should never happen; it indicates a wrong client implementation
1090 // that doesn't follow the contract. But, we can be tolerant here.
1091 ALOGE("%s: callback overlapped! waiting 1s...",
1092 __FUNCTION__);
1093 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1094 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1095 __FUNCTION__);
1096 // really don't know what to do, so bail out.
1097 return hardware::Void();
1098 }
1099 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001100
1101 CaptureOutputStates states {
1102 mId,
1103 mInFlightLock, mInFlightMap,
1104 mOutputLock, mResultQueue, mResultSignal,
1105 mNextShutterFrameNumber,
1106 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1107 mNextResultFrameNumber,
1108 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1109 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1110 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001111 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1112 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001113 };
1114
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001115 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001116 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001117 }
1118 mProcessCaptureResultLock.unlock();
1119 return hardware::Void();
1120}
1121
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001122hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001123 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001124 // Ideally we should grab mLock, but that can lead to deadlock, and
1125 // it's not super important to get up to date value of mStatus for this
1126 // warning print, hence skipping the lock here
1127 if (mStatus == STATUS_ERROR) {
1128 // Per API contract, HAL should act as closed after device error
1129 // But mStatus can be set to error by framework as well, so just log
1130 // a warning here.
1131 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001132 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001133
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001134 sp<NotificationListener> listener;
1135 {
1136 std::lock_guard<std::mutex> l(mOutputLock);
1137 listener = mListener.promote();
1138 }
1139
1140 CaptureOutputStates states {
1141 mId,
1142 mInFlightLock, mInFlightMap,
1143 mOutputLock, mResultQueue, mResultSignal,
1144 mNextShutterFrameNumber,
1145 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1146 mNextResultFrameNumber,
1147 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1148 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1149 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001150 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1151 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001152 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001153 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001154 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001155 }
1156 return hardware::Void();
1157}
1158
Emilian Peevaebbe412018-01-15 13:53:24 +00001159status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001160 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001161 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001162 ATRACE_CALL();
1163
Emilian Peevaebbe412018-01-15 13:53:24 +00001164 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001165}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001166
Jianing Weicb0652e2014-03-12 18:29:36 -07001167status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1168 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001169 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001170
Emilian Peevaebbe412018-01-15 13:53:24 +00001171 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001172 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001173 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001174
Emilian Peevaebbe412018-01-15 13:53:24 +00001175 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001176 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001177}
1178
Emilian Peevaebbe412018-01-15 13:53:24 +00001179status_t Camera3Device::setStreamingRequestList(
1180 const List<const PhysicalCameraSettingsList> &requestsList,
1181 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001182 ATRACE_CALL();
1183
Emilian Peevaebbe412018-01-15 13:53:24 +00001184 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001185}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001186
1187sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001188 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001189 status_t res;
1190
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001191 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001192 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1193 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001194 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1195 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001196 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001198 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001199 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001200 } else if (mStatus == STATUS_UNCONFIGURED) {
1201 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001202 CLOGE("No streams configured");
1203 return NULL;
1204 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001205 }
1206
Shuzhen Wang0129d522016-10-30 22:43:41 -07001207 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001208 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001209}
1210
Jianing Weicb0652e2014-03-12 18:29:36 -07001211status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001212 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001213 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001214 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001215
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 switch (mStatus) {
1217 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001218 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return INVALID_OPERATION;
1220 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001221 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001223 case STATUS_UNCONFIGURED:
1224 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225 case STATUS_ACTIVE:
1226 // OK
1227 break;
1228 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001229 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230 return INVALID_OPERATION;
1231 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001232 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001233
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001234 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001235}
1236
1237status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1238 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001239 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001240
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001241 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001242}
1243
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001244status_t Camera3Device::createInputStream(
1245 uint32_t width, uint32_t height, int format, int *id) {
1246 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001247 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001248 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001249 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001250 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1251 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001252
1253 status_t res;
1254 bool wasActive = false;
1255
1256 switch (mStatus) {
1257 case STATUS_ERROR:
1258 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1259 return INVALID_OPERATION;
1260 case STATUS_UNINITIALIZED:
1261 ALOGE("%s: Device not initialized", __FUNCTION__);
1262 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001263 case STATUS_UNCONFIGURED:
1264 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001265 // OK
1266 break;
1267 case STATUS_ACTIVE:
1268 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001269 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001270 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001271 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001272 return res;
1273 }
1274 wasActive = true;
1275 break;
1276 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001277 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001278 return INVALID_OPERATION;
1279 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001280 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001281
1282 if (mInputStream != 0) {
1283 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1284 return INVALID_OPERATION;
1285 }
1286
1287 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1288 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001289 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001290
1291 mInputStream = newStream;
1292
1293 *id = mNextStreamId++;
1294
1295 // Continue captures if active at start
1296 if (wasActive) {
1297 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001298 // Reuse current operating mode and session parameters for new stream config
1299 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001300 if (res != OK) {
1301 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1302 __FUNCTION__, mNextStreamId, strerror(-res), res);
1303 return res;
1304 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001305 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001306 }
1307
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001308 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001309 return OK;
1310}
1311
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001312status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001313 uint32_t width, uint32_t height, int format,
1314 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001315 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001316 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001317 ATRACE_CALL();
1318
1319 if (consumer == nullptr) {
1320 ALOGE("%s: consumer must not be null", __FUNCTION__);
1321 return BAD_VALUE;
1322 }
1323
1324 std::vector<sp<Surface>> consumers;
1325 consumers.push_back(consumer);
1326
1327 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001328 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1329 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001330}
1331
1332status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1333 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1334 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001335 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001336 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001337 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001338
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001339 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001340 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001341 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001342 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001343 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1344 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1345 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001346
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001347 status_t res;
1348 bool wasActive = false;
1349
1350 switch (mStatus) {
1351 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001352 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001353 return INVALID_OPERATION;
1354 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001355 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001356 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001357 case STATUS_UNCONFIGURED:
1358 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001359 // OK
1360 break;
1361 case STATUS_ACTIVE:
1362 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001363 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001364 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001365 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001366 return res;
1367 }
1368 wasActive = true;
1369 break;
1370 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001371 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001372 return INVALID_OPERATION;
1373 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001374 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001375
1376 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001377
Shuzhen Wang0129d522016-10-30 22:43:41 -07001378 if (consumers.size() == 0 && !hasDeferredConsumer) {
1379 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1380 return BAD_VALUE;
1381 }
Zhijun He5d677d12016-05-29 16:52:39 -07001382
Shuzhen Wang0129d522016-10-30 22:43:41 -07001383 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001384 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1385 return BAD_VALUE;
1386 }
1387
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001388 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001389 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001390 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001391 blobBufferSize = getPointCloudBufferSize();
1392 if (blobBufferSize <= 0) {
1393 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1394 return BAD_VALUE;
1395 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001396 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1397 blobBufferSize = width * height;
1398 } else {
1399 blobBufferSize = getJpegBufferSize(width, height);
1400 if (blobBufferSize <= 0) {
1401 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1402 return BAD_VALUE;
1403 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001404 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001405 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001406 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001407 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001408 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1409 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1410 if (rawOpaqueBufferSize <= 0) {
1411 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1412 return BAD_VALUE;
1413 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001414 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001415 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001416 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001417 } else if (isShared) {
1418 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1419 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001420 mTimestampOffset, physicalCameraId, streamSetId,
1421 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001422 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001423 newStream = new Camera3OutputStream(mNextStreamId,
1424 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001425 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001426 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001427 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001428 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001429 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 }
Emilian Peev40ead602017-09-26 15:46:36 +01001431
1432 size_t consumerCount = consumers.size();
1433 for (size_t i = 0; i < consumerCount; i++) {
1434 int id = newStream->getSurfaceId(consumers[i]);
1435 if (id < 0) {
1436 SET_ERR_L("Invalid surface id");
1437 return BAD_VALUE;
1438 }
1439 if (surfaceIds != nullptr) {
1440 surfaceIds->push_back(id);
1441 }
1442 }
1443
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001444 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001445
Emilian Peev08dd2452017-04-06 16:55:14 +01001446 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001447
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001448 res = mOutputStreams.add(mNextStreamId, newStream);
1449 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001450 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001451 return res;
1452 }
1453
1454 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001455 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456
1457 // Continue captures if active at start
1458 if (wasActive) {
1459 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001460 // Reuse current operating mode and session parameters for new stream config
1461 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001462 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001463 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1464 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001465 return res;
1466 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001467 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001468 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001469 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001471}
1472
Emilian Peev710c1422017-08-30 11:19:38 +01001473status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001474 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001475 if (nullptr == streamInfo) {
1476 return BAD_VALUE;
1477 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001478 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001479 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001480
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 switch (mStatus) {
1482 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001483 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 return INVALID_OPERATION;
1485 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001486 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001487 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001488 case STATUS_UNCONFIGURED:
1489 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490 case STATUS_ACTIVE:
1491 // OK
1492 break;
1493 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001494 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 return INVALID_OPERATION;
1496 }
1497
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001498 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1499 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001500 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001501 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502 }
1503
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001504 streamInfo->width = stream->getWidth();
1505 streamInfo->height = stream->getHeight();
1506 streamInfo->format = stream->getFormat();
1507 streamInfo->dataSpace = stream->getDataSpace();
1508 streamInfo->formatOverridden = stream->isFormatOverridden();
1509 streamInfo->originalFormat = stream->getOriginalFormat();
1510 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1511 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001512 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001513}
1514
1515status_t Camera3Device::setStreamTransform(int id,
1516 int transform) {
1517 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001518 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001519 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001520
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 switch (mStatus) {
1522 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001523 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001524 return INVALID_OPERATION;
1525 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001526 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001527 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001528 case STATUS_UNCONFIGURED:
1529 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530 case STATUS_ACTIVE:
1531 // OK
1532 break;
1533 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001534 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001535 return INVALID_OPERATION;
1536 }
1537
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001538 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1539 if (stream == nullptr) {
1540 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001541 return BAD_VALUE;
1542 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001543 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001544}
1545
1546status_t Camera3Device::deleteStream(int id) {
1547 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001548 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001549 Mutex::Autolock l(mLock);
1550 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001551
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001552 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001553
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 // CameraDevice semantics require device to already be idle before
1555 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001556 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001557 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001558 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001559 }
1560
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001561 if (mStatus == STATUS_ERROR) {
1562 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1563 __FUNCTION__, mId.string());
1564 return -EBUSY;
1565 }
1566
Igor Murashkin2fba5842013-04-22 14:03:54 -07001567 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001568 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 if (mInputStream != NULL && id == mInputStream->getId()) {
1570 deletedStream = mInputStream;
1571 mInputStream.clear();
1572 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001573 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001574 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 return BAD_VALUE;
1576 }
Zhijun He5f446352014-01-22 09:49:33 -08001577 }
1578
1579 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001580 if (stream != nullptr) {
1581 deletedStream = stream;
1582 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583 }
1584
1585 // Free up the stream endpoint so that it can be used by some other stream
1586 res = deletedStream->disconnect();
1587 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001588 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001589 // fall through since we want to still list the stream as deleted.
1590 }
1591 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001592 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593
1594 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001595}
1596
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001597status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001598 ATRACE_CALL();
1599 ALOGV("%s: E", __FUNCTION__);
1600
1601 Mutex::Autolock il(mInterfaceLock);
1602 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001603
Emilian Peev811d2952018-05-25 11:08:40 +01001604 // In case the client doesn't include any session parameter, try a
1605 // speculative configuration using the values from the last cached
1606 // default request.
1607 if (sessionParams.isEmpty() &&
1608 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1609 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1610 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1611 mLastTemplateId);
1612 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1613 operatingMode);
1614 }
1615
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001616 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1617}
1618
1619status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1620 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001621 //Filter out any incoming session parameters
1622 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001623 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1624 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001625 CameraMetadata filteredParams(availableSessionKeys.count);
1626 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1627 filteredParams.getAndLock());
1628 set_camera_metadata_vendor_id(meta, mVendorTagId);
1629 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001630 if (availableSessionKeys.count > 0) {
1631 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1632 camera_metadata_ro_entry entry = params.find(
1633 availableSessionKeys.data.i32[i]);
1634 if (entry.count > 0) {
1635 filteredParams.update(entry);
1636 }
1637 }
1638 }
1639
1640 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001641}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001642
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001643status_t Camera3Device::getInputBufferProducer(
1644 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001645 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001646 Mutex::Autolock il(mInterfaceLock);
1647 Mutex::Autolock l(mLock);
1648
1649 if (producer == NULL) {
1650 return BAD_VALUE;
1651 } else if (mInputStream == NULL) {
1652 return INVALID_OPERATION;
1653 }
1654
1655 return mInputStream->getInputBufferProducer(producer);
1656}
1657
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001658status_t Camera3Device::createDefaultRequest(int templateId,
1659 CameraMetadata *request) {
1660 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001661 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001662
1663 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1664 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001665 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001666 return BAD_VALUE;
1667 }
1668
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001669 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001670
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001671 {
1672 Mutex::Autolock l(mLock);
1673 switch (mStatus) {
1674 case STATUS_ERROR:
1675 CLOGE("Device has encountered a serious error");
1676 return INVALID_OPERATION;
1677 case STATUS_UNINITIALIZED:
1678 CLOGE("Device is not initialized!");
1679 return INVALID_OPERATION;
1680 case STATUS_UNCONFIGURED:
1681 case STATUS_CONFIGURED:
1682 case STATUS_ACTIVE:
1683 // OK
1684 break;
1685 default:
1686 SET_ERR_L("Unexpected status: %d", mStatus);
1687 return INVALID_OPERATION;
1688 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001689
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001690 if (!mRequestTemplateCache[templateId].isEmpty()) {
1691 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001692 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001693 return OK;
1694 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001695 }
1696
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001697 camera_metadata_t *rawRequest;
1698 status_t res = mInterface->constructDefaultRequestSettings(
1699 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001700
1701 {
1702 Mutex::Autolock l(mLock);
1703 if (res == BAD_VALUE) {
1704 ALOGI("%s: template %d is not supported on this camera device",
1705 __FUNCTION__, templateId);
1706 return res;
1707 } else if (res != OK) {
1708 CLOGE("Unable to construct request template %d: %s (%d)",
1709 templateId, strerror(-res), res);
1710 return res;
1711 }
1712
1713 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1714 mRequestTemplateCache[templateId].acquire(rawRequest);
1715
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001716 // Override the template request with zoomRatioMapper
1717 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1718 &mRequestTemplateCache[templateId]);
1719 if (res != OK) {
1720 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1721 templateId, strerror(-res), res);
1722 return res;
1723 }
1724
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001725 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001726 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001727 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001728 return OK;
1729}
1730
1731status_t Camera3Device::waitUntilDrained() {
1732 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001733 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001734 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001735 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001736
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001737 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001738}
1739
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001740status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001741 switch (mStatus) {
1742 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001743 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001744 ALOGV("%s: Already idle", __FUNCTION__);
1745 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001746 case STATUS_CONFIGURED:
1747 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001748 case STATUS_ERROR:
1749 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001750 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001751 break;
1752 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001753 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001754 return INVALID_OPERATION;
1755 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001756 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1757 maxExpectedDuration);
1758 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001759 if (res != OK) {
1760 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1761 res);
1762 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001763 return res;
1764}
1765
Ruben Brunk183f0562015-08-12 12:55:02 -07001766
1767void Camera3Device::internalUpdateStatusLocked(Status status) {
1768 mStatus = status;
1769 mRecentStatusUpdates.add(mStatus);
1770 mStatusChanged.broadcast();
1771}
1772
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001773void Camera3Device::pauseStateNotify(bool enable) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08001774 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001775 Mutex::Autolock l(mLock);
1776
1777 mPauseStateNotify = enable;
1778}
1779
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001780// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001781status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001782 if (mRequestThread.get() != nullptr) {
1783 mRequestThread->setPaused(true);
1784 } else {
1785 return NO_INIT;
1786 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001787
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001788 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1789 maxExpectedDuration);
1790 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001791 if (res != OK) {
1792 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001793 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001794 }
1795
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001796 return res;
1797}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001798
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001799// Resume after internalPauseAndWaitLocked
1800status_t Camera3Device::internalResumeLocked() {
1801 status_t res;
1802
1803 mRequestThread->setPaused(false);
1804
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001805 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1806 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001807 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1808 if (res != OK) {
1809 SET_ERR_L("Can't transition to active in %f seconds!",
1810 kActiveTimeout/1e9);
1811 }
1812 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001813 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001814}
1815
Ruben Brunk183f0562015-08-12 12:55:02 -07001816status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001817 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001818
1819 size_t startIndex = 0;
1820 if (mStatusWaiters == 0) {
1821 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1822 // this status list
1823 mRecentStatusUpdates.clear();
1824 } else {
1825 // If other threads are waiting on updates to this status list, set the position of the
1826 // first element that this list will check rather than clearing the list.
1827 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828 }
1829
Ruben Brunk183f0562015-08-12 12:55:02 -07001830 mStatusWaiters++;
1831
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001832 if (!active && mUseHalBufManager) {
1833 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001834 if (mStatus == STATUS_ACTIVE) {
1835 mRequestThread->signalPipelineDrain(streamIds);
1836 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001837 mRequestBufferSM.onWaitUntilIdle();
1838 }
1839
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001840 bool stateSeen = false;
1841 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001842 if (active == (mStatus == STATUS_ACTIVE)) {
1843 // Desired state is current
1844 break;
1845 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001846
1847 res = mStatusChanged.waitRelative(mLock, timeout);
1848 if (res != OK) break;
1849
Ruben Brunk183f0562015-08-12 12:55:02 -07001850 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1851 // transitions.
1852 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1853 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1854 __FUNCTION__);
1855
1856 // Encountered desired state since we began waiting
1857 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001858 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1859 stateSeen = true;
1860 break;
1861 }
1862 }
1863 } while (!stateSeen);
1864
Ruben Brunk183f0562015-08-12 12:55:02 -07001865 mStatusWaiters--;
1866
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001867 return res;
1868}
1869
1870
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001871status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001872 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001873 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001874
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001875 if (listener != NULL && mListener != NULL) {
1876 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1877 }
1878 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001879 mRequestThread->setNotificationListener(listener);
1880 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001881
1882 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001883}
1884
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001885bool Camera3Device::willNotify3A() {
1886 return false;
1887}
1888
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001889status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001890 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001891 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001892
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001893 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001894 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1895 if (st == std::cv_status::timeout) {
1896 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001897 }
1898 }
1899 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001900}
1901
Jianing Weicb0652e2014-03-12 18:29:36 -07001902status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001903 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001904 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001905
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001906 if (mResultQueue.empty()) {
1907 return NOT_ENOUGH_DATA;
1908 }
1909
Jianing Weicb0652e2014-03-12 18:29:36 -07001910 if (frame == NULL) {
1911 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1912 return BAD_VALUE;
1913 }
1914
1915 CaptureResult &result = *(mResultQueue.begin());
1916 frame->mResultExtras = result.mResultExtras;
1917 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001918 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001919 mResultQueue.erase(mResultQueue.begin());
1920
1921 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001922}
1923
1924status_t Camera3Device::triggerAutofocus(uint32_t id) {
1925 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001926 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001927
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001928 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1929 // Mix-in this trigger into the next request and only the next request.
1930 RequestTrigger trigger[] = {
1931 {
1932 ANDROID_CONTROL_AF_TRIGGER,
1933 ANDROID_CONTROL_AF_TRIGGER_START
1934 },
1935 {
1936 ANDROID_CONTROL_AF_TRIGGER_ID,
1937 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001938 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001939 };
1940
1941 return mRequestThread->queueTrigger(trigger,
1942 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001943}
1944
1945status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1946 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001947 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001948
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001949 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1950 // Mix-in this trigger into the next request and only the next request.
1951 RequestTrigger trigger[] = {
1952 {
1953 ANDROID_CONTROL_AF_TRIGGER,
1954 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1955 },
1956 {
1957 ANDROID_CONTROL_AF_TRIGGER_ID,
1958 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001959 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001960 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001961
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001962 return mRequestThread->queueTrigger(trigger,
1963 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001964}
1965
1966status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1967 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001968 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001969
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001970 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1971 // Mix-in this trigger into the next request and only the next request.
1972 RequestTrigger trigger[] = {
1973 {
1974 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1975 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1976 },
1977 {
1978 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1979 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001980 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001981 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001982
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001983 return mRequestThread->queueTrigger(trigger,
1984 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001985}
1986
Jianing Weicb0652e2014-03-12 18:29:36 -07001987status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001988 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001989 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001990 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001991
Zhijun He7ef20392014-04-21 16:04:17 -07001992 {
1993 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01001994
1995 // b/116514106 "disconnect()" can get called twice for the same device. The
1996 // camera device will not be initialized during the second run.
1997 if (mStatus == STATUS_UNINITIALIZED) {
1998 return OK;
1999 }
2000
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002001 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002002 }
2003
Emilian Peev08dd2452017-04-06 16:55:14 +01002004 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002005}
2006
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002007status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002008 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2009}
2010
2011status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002012 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002013 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002014 Mutex::Autolock il(mInterfaceLock);
2015 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002016
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002017 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2018 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002019 CLOGE("Stream %d does not exist", streamId);
2020 return BAD_VALUE;
2021 }
2022
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002023 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002024 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002025 return BAD_VALUE;
2026 }
2027
2028 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002029 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002030 return BAD_VALUE;
2031 }
2032
Ruben Brunkc78ac262015-08-13 17:58:46 -07002033 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002034}
2035
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002036status_t Camera3Device::tearDown(int streamId) {
2037 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002038 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002039 Mutex::Autolock il(mInterfaceLock);
2040 Mutex::Autolock l(mLock);
2041
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002042 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2043 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002044 CLOGE("Stream %d does not exist", streamId);
2045 return BAD_VALUE;
2046 }
2047
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002048 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2049 CLOGE("Stream %d is a target of a in-progress request", streamId);
2050 return BAD_VALUE;
2051 }
2052
2053 return stream->tearDown();
2054}
2055
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002056status_t Camera3Device::addBufferListenerForStream(int streamId,
2057 wp<Camera3StreamBufferListener> listener) {
2058 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002059 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002060 Mutex::Autolock il(mInterfaceLock);
2061 Mutex::Autolock l(mLock);
2062
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002063 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2064 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002065 CLOGE("Stream %d does not exist", streamId);
2066 return BAD_VALUE;
2067 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002068 stream->addBufferListener(listener);
2069
2070 return OK;
2071}
2072
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002073/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002074 * Methods called by subclasses
2075 */
2076
2077void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002078 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002079 {
2080 // Need mLock to safely update state and synchronize to current
2081 // state of methods in flight.
2082 Mutex::Autolock l(mLock);
2083 // We can get various system-idle notices from the status tracker
2084 // while starting up. Only care about them if we've actually sent
2085 // in some requests recently.
2086 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2087 return;
2088 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002089 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2090 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002091 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002092
2093 // Skip notifying listener if we're doing some user-transparent
2094 // state changes
2095 if (mPauseStateNotify) return;
2096 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002097
2098 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002099 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002100 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002101 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002102 }
2103 if (idle && listener != NULL) {
2104 listener->notifyIdle();
2105 }
2106}
2107
Shuzhen Wang758c2152017-01-10 18:26:18 -08002108status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002109 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002110 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002111 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2112 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002113
2114 if (surfaceIds == nullptr) {
2115 return BAD_VALUE;
2116 }
2117
Zhijun He5d677d12016-05-29 16:52:39 -07002118 Mutex::Autolock il(mInterfaceLock);
2119 Mutex::Autolock l(mLock);
2120
Shuzhen Wang758c2152017-01-10 18:26:18 -08002121 if (consumers.size() == 0) {
2122 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002123 return BAD_VALUE;
2124 }
2125
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002126 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2127 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002128 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002129 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002130 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002131
2132 // isConsumerConfigurationDeferred will be off after setConsumers
2133 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002134 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002135 if (res != OK) {
2136 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2137 return res;
2138 }
2139
Emilian Peev40ead602017-09-26 15:46:36 +01002140 for (auto &consumer : consumers) {
2141 int id = stream->getSurfaceId(consumer);
2142 if (id < 0) {
2143 CLOGE("Invalid surface id!");
2144 return BAD_VALUE;
2145 }
2146 surfaceIds->push_back(id);
2147 }
2148
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002149 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002150 if (!stream->isConfiguring()) {
2151 CLOGE("Stream %d was already fully configured.", streamId);
2152 return INVALID_OPERATION;
2153 }
Zhijun He5d677d12016-05-29 16:52:39 -07002154
Shuzhen Wang0129d522016-10-30 22:43:41 -07002155 res = stream->finishConfiguration();
2156 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002157 // If finishConfiguration fails due to abandoned surface, do not set
2158 // device to error state.
2159 bool isSurfaceAbandoned =
2160 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2161 if (!isSurfaceAbandoned) {
2162 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2163 stream->getId(), strerror(-res), res);
2164 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002165 return res;
2166 }
Zhijun He5d677d12016-05-29 16:52:39 -07002167 }
2168
2169 return OK;
2170}
2171
Emilian Peev40ead602017-09-26 15:46:36 +01002172status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2173 const std::vector<OutputStreamInfo> &outputInfo,
2174 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2175 Mutex::Autolock il(mInterfaceLock);
2176 Mutex::Autolock l(mLock);
2177
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002178 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2179 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002180 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002181 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002182 }
2183
2184 for (const auto &it : removedSurfaceIds) {
2185 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2186 CLOGE("Shared surface still part of a pending request!");
2187 return -EBUSY;
2188 }
2189 }
2190
Emilian Peev40ead602017-09-26 15:46:36 +01002191 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2192 if (res != OK) {
2193 CLOGE("Stream %d failed to update stream (error %d %s) ",
2194 streamId, res, strerror(-res));
2195 if (res == UNKNOWN_ERROR) {
2196 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2197 __FUNCTION__);
2198 }
2199 return res;
2200 }
2201
2202 return res;
2203}
2204
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002205status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2206 Mutex::Autolock il(mInterfaceLock);
2207 Mutex::Autolock l(mLock);
2208
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002209 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2210 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002211 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2212 return BAD_VALUE;
2213 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002214 return stream->dropBuffers(dropping);
2215}
2216
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002217/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002218 * Camera3Device private methods
2219 */
2220
2221sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002222 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002223 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002224
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002225 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002226 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002227
2228 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002229 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002230 if (inputStreams.count > 0) {
2231 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002232 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002233 CLOGE("Request references unknown input stream %d",
2234 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002235 return NULL;
2236 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002237
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002238 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002239 SET_ERR_L("%s: input stream %d is not configured!",
2240 __FUNCTION__, mInputStream->getId());
2241 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002242 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002243 // Check if stream prepare is blocking requests.
2244 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002245 CLOGE("Request references an input stream that's being prepared!");
2246 return NULL;
2247 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002248
2249 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002250 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002251 }
2252
2253 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002254 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002255 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002256 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002257 return NULL;
2258 }
2259
2260 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002261 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2262 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002263 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002264 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002265 return NULL;
2266 }
Zhijun He5d677d12016-05-29 16:52:39 -07002267 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002268 auto iter = surfaceMap.find(streams.data.i32[i]);
2269 if (iter != surfaceMap.end()) {
2270 const std::vector<size_t>& surfaces = iter->second;
2271 for (const auto& surface : surfaces) {
2272 if (stream->isConsumerConfigurationDeferred(surface)) {
2273 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2274 "due to deferred consumer", stream->getId(), surface);
2275 return NULL;
2276 }
2277 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002278 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002279 }
2280
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002281 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002282 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2283 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002284 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002285 // Check if stream prepare is blocking requests.
2286 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002287 CLOGE("Request references an output stream that's being prepared!");
2288 return NULL;
2289 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002290
2291 newRequest->mOutputStreams.push(stream);
2292 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002293 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002294 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002295
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002296 auto rotateAndCropEntry =
2297 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2298 if (rotateAndCropEntry.count > 0 &&
2299 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2300 newRequest->mRotateAndCropAuto = true;
2301 } else {
2302 newRequest->mRotateAndCropAuto = false;
2303 }
2304
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002305 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002306}
2307
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002308void Camera3Device::cancelStreamsConfigurationLocked() {
2309 int res = OK;
2310 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2311 res = mInputStream->cancelConfiguration();
2312 if (res != OK) {
2313 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2314 mInputStream->getId(), strerror(-res), res);
2315 }
2316 }
2317
2318 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002319 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002320 if (outputStream->isConfiguring()) {
2321 res = outputStream->cancelConfiguration();
2322 if (res != OK) {
2323 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2324 outputStream->getId(), strerror(-res), res);
2325 }
2326 }
2327 }
2328
2329 // Return state to that at start of call, so that future configures
2330 // properly clean things up
2331 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2332 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002333
2334 res = mPreparerThread->resume();
2335 if (res != OK) {
2336 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2337 }
2338}
2339
2340bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2341 ATRACE_CALL();
2342 bool ret = false;
2343
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002344 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002345 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2346
2347 Mutex::Autolock l(mLock);
2348 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2349 if (rc == NO_ERROR) {
2350 mNeedConfig = true;
2351 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2352 if (rc == NO_ERROR) {
2353 ret = true;
2354 mPauseStateNotify = false;
2355 //Moving to active state while holding 'mLock' is important.
2356 //There could be pending calls to 'create-/deleteStream' which
2357 //will trigger another stream configuration while the already
2358 //present streams end up with outstanding buffers that will
2359 //not get drained.
2360 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002361 } else if (rc == DEAD_OBJECT) {
2362 // DEAD_OBJECT can be returned if either the consumer surface is
2363 // abandoned, or the HAL has died.
2364 // - If the HAL has died, configureStreamsLocked call will set
2365 // device to error state,
2366 // - If surface is abandoned, we should not set device to error
2367 // state.
2368 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002369 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002370 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002371 }
2372 } else {
2373 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2374 }
2375
2376 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002377}
2378
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002379status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002380 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002381 ATRACE_CALL();
2382 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002383
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002384 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002385 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002386 return INVALID_OPERATION;
2387 }
2388
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002389 if (operatingMode < 0) {
2390 CLOGE("Invalid operating mode: %d", operatingMode);
2391 return BAD_VALUE;
2392 }
2393
2394 bool isConstrainedHighSpeed =
2395 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2396 operatingMode;
2397
2398 if (mOperatingMode != operatingMode) {
2399 mNeedConfig = true;
2400 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2401 mOperatingMode = operatingMode;
2402 }
2403
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002404 // In case called from configureStreams, abort queued input buffers not belonging to
2405 // any pending requests.
2406 if (mInputStream != NULL && notifyRequestThread) {
2407 while (true) {
2408 camera3_stream_buffer_t inputBuffer;
2409 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2410 /*respectHalLimit*/ false);
2411 if (res != OK) {
2412 // Exhausted acquiring all input buffers.
2413 break;
2414 }
2415
2416 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2417 res = mInputStream->returnInputBuffer(inputBuffer);
2418 if (res != OK) {
2419 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2420 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2421 }
2422 }
2423 }
2424
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002425 if (!mNeedConfig) {
2426 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2427 return OK;
2428 }
2429
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002430 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2431 // adding a dummy stream instead.
2432 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2433 if (mOutputStreams.size() == 0) {
2434 addDummyStreamLocked();
2435 } else {
2436 tryRemoveDummyStreamLocked();
2437 }
2438
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002439 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002440 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002441
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002442 mPreparerThread->pause();
2443
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002444 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002445 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002446 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2447
2448 Vector<camera3_stream_t*> streams;
2449 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002450 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002451
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002452
2453 if (mInputStream != NULL) {
2454 camera3_stream_t *inputStream;
2455 inputStream = mInputStream->startConfiguration();
2456 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002457 CLOGE("Can't start input stream configuration");
2458 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002459 return INVALID_OPERATION;
2460 }
2461 streams.add(inputStream);
2462 }
2463
2464 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002465
2466 // Don't configure bidi streams twice, nor add them twice to the list
2467 if (mOutputStreams[i].get() ==
2468 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2469
2470 config.num_streams--;
2471 continue;
2472 }
2473
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002474 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002475 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002476 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002477 CLOGE("Can't start output stream configuration");
2478 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002479 return INVALID_OPERATION;
2480 }
2481 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002482
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002483 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002484 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2485 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002486 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2487 bufferSizes[k] = static_cast<uint32_t>(
2488 getJpegBufferSize(outputStream->width, outputStream->height));
2489 } else if (outputStream->data_space ==
2490 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2491 bufferSizes[k] = outputStream->width * outputStream->height;
2492 } else {
2493 ALOGW("%s: Blob dataSpace %d not supported",
2494 __FUNCTION__, outputStream->data_space);
2495 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002496 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002497 }
2498
2499 config.streams = streams.editArray();
2500
2501 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002502 // max_buffers, usage, and priv fields, as well as data_space and format
2503 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002504
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002505 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002506 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002507 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002508
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002509 if (res == BAD_VALUE) {
2510 // HAL rejected this set of streams as unsupported, clean up config
2511 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002512 CLOGE("Set of requested inputs/outputs not supported by HAL");
2513 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002514 return BAD_VALUE;
2515 } else if (res != OK) {
2516 // Some other kind of error from configure_streams - this is not
2517 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002518 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2519 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002520 return res;
2521 }
2522
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002523 // Finish all stream configuration immediately.
2524 // TODO: Try to relax this later back to lazy completion, which should be
2525 // faster
2526
Igor Murashkin073f8572013-05-02 14:59:28 -07002527 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002528 bool streamReConfigured = false;
2529 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002530 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002531 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002532 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002533 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002534 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2535 return DEAD_OBJECT;
2536 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002537 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002538 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002539 if (streamReConfigured) {
2540 mInterface->onStreamReConfigured(mInputStream->getId());
2541 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002542 }
2543
2544 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002545 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002546 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002547 bool streamReConfigured = false;
2548 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002549 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002550 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002551 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002552 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002553 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2554 return DEAD_OBJECT;
2555 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002556 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002557 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002558 if (streamReConfigured) {
2559 mInterface->onStreamReConfigured(outputStream->getId());
2560 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002561 }
2562 }
2563
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002564 // Request thread needs to know to avoid using repeat-last-settings protocol
2565 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002566 if (notifyRequestThread) {
2567 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2568 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002569
Zhijun He90f7c372016-08-16 16:19:43 -07002570 char value[PROPERTY_VALUE_MAX];
2571 property_get("camera.fifo.disable", value, "0");
2572 int32_t disableFifo = atoi(value);
2573 if (disableFifo != 1) {
2574 // Boost priority of request thread to SCHED_FIFO.
2575 pid_t requestThreadTid = mRequestThread->getTid();
2576 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002577 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002578 if (res != OK) {
2579 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2580 strerror(-res), res);
2581 } else {
2582 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2583 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002584 }
2585
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002586 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002587 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2588 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2589 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2590 sessionParams.unlock(newSessionParams);
2591 mSessionParams.unlock(currentSessionParams);
2592 if (updateSessionParams) {
2593 mSessionParams = sessionParams;
2594 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002595
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002596 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002597
Ruben Brunk183f0562015-08-12 12:55:02 -07002598 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2599 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002600
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002601 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002602
Zhijun He0a210512014-07-24 13:45:15 -07002603 // tear down the deleted streams after configure streams.
2604 mDeletedStreams.clear();
2605
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002606 auto rc = mPreparerThread->resume();
2607 if (rc != OK) {
2608 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2609 return rc;
2610 }
2611
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002612 if (mDummyStreamId == NO_STREAM) {
2613 mRequestBufferSM.onStreamsConfigured();
2614 }
2615
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002616 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002617}
2618
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002619status_t Camera3Device::addDummyStreamLocked() {
2620 ATRACE_CALL();
2621 status_t res;
2622
2623 if (mDummyStreamId != NO_STREAM) {
2624 // Should never be adding a second dummy stream when one is already
2625 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002626 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2627 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002628 return INVALID_OPERATION;
2629 }
2630
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002631 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002632
2633 sp<Camera3OutputStreamInterface> dummyStream =
2634 new Camera3DummyStream(mNextStreamId);
2635
2636 res = mOutputStreams.add(mNextStreamId, dummyStream);
2637 if (res < 0) {
2638 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2639 return res;
2640 }
2641
2642 mDummyStreamId = mNextStreamId;
2643 mNextStreamId++;
2644
2645 return OK;
2646}
2647
2648status_t Camera3Device::tryRemoveDummyStreamLocked() {
2649 ATRACE_CALL();
2650 status_t res;
2651
2652 if (mDummyStreamId == NO_STREAM) return OK;
2653 if (mOutputStreams.size() == 1) return OK;
2654
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002655 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002656
2657 // Ok, have a dummy stream and there's at least one other output stream,
2658 // so remove the dummy
2659
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002660 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2661 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002662 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2663 return INVALID_OPERATION;
2664 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002665 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002666
2667 // Free up the stream endpoint so that it can be used by some other stream
2668 res = deletedStream->disconnect();
2669 if (res != OK) {
2670 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2671 // fall through since we want to still list the stream as deleted.
2672 }
2673 mDeletedStreams.add(deletedStream);
2674 mDummyStreamId = NO_STREAM;
2675
2676 return res;
2677}
2678
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002679void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002680 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002681 Mutex::Autolock l(mLock);
2682 va_list args;
2683 va_start(args, fmt);
2684
2685 setErrorStateLockedV(fmt, args);
2686
2687 va_end(args);
2688}
2689
2690void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002691 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002692 Mutex::Autolock l(mLock);
2693 setErrorStateLockedV(fmt, args);
2694}
2695
2696void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2697 va_list args;
2698 va_start(args, fmt);
2699
2700 setErrorStateLockedV(fmt, args);
2701
2702 va_end(args);
2703}
2704
2705void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002706 // Print out all error messages to log
2707 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002708 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002709
2710 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002711 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002712
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002713 mErrorCause = errorCause;
2714
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002715 if (mRequestThread != nullptr) {
2716 mRequestThread->setPaused(true);
2717 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002718 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002719
2720 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002721 sp<NotificationListener> listener = mListener.promote();
2722 if (listener != NULL) {
2723 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002724 CaptureResultExtras());
2725 }
2726
2727 // Save stack trace. View by dumping it later.
2728 CameraTraces::saveTrace();
2729 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002730}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002731
2732/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002733 * In-flight request management
2734 */
2735
Jianing Weicb0652e2014-03-12 18:29:36 -07002736status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002737 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002738 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002739 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002740 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08002741 const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002742 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002743 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002744
2745 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002746 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002747 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002748 rotateAndCropAuto, cameraIdsWithZoom, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002749 if (res < 0) return res;
2750
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002751 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002752 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2753 // avoid a deadlock during reprocess requests.
2754 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002755 if (mStatusTracker != nullptr) {
2756 mStatusTracker->markComponentActive(mInFlightStatusId);
2757 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002758 }
2759
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002760 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002761 return OK;
2762}
2763
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002764void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002765 // Indicate idle inFlightMap to the status tracker
2766 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002767 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002768 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2769 // avoid a deadlock during reprocess requests.
2770 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002771 if (mStatusTracker != nullptr) {
2772 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2773 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002774 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002775 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002776}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002777
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002778void Camera3Device::checkInflightMapLengthLocked() {
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002779 // Sanity check - if we have too many in-flight frames with long total inflight duration,
2780 // something has likely gone wrong. This might still be legit only if application send in
2781 // a long burst of long exposure requests.
2782 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2783 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2784 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2785 mInFlightMap.size(), mExpectedInflightDuration);
2786 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2787 kInFlightWarnLimitHighSpeed) {
2788 CLOGW("In-flight list too large for high speed configuration: %zu,"
2789 "total inflight duration %" PRIu64,
2790 mInFlightMap.size(), mExpectedInflightDuration);
2791 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002792 }
2793}
2794
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002795void Camera3Device::onInflightMapFlushedLocked() {
2796 mExpectedInflightDuration = 0;
2797}
2798
2799void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2800 ATRACE_CALL();
2801 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2802 mInFlightMap.removeItemsAt(idx, 1);
2803
2804 onInflightEntryRemovedLocked(duration);
2805}
2806
2807
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002808void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002809 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002810 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002811 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002812 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002813 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002814 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002815
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002816 FlushInflightReqStates states {
2817 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
2818 listener, *this, *mInterface, *this};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002819
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002820 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002821}
2822
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002823CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002824 ALOGV("%s", __FUNCTION__);
2825
Igor Murashkin1e479c02013-09-06 16:55:14 -07002826 CameraMetadata retVal;
2827
2828 if (mRequestThread != NULL) {
2829 retVal = mRequestThread->getLatestRequest();
2830 }
2831
Igor Murashkin1e479c02013-09-06 16:55:14 -07002832 return retVal;
2833}
2834
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002835void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002836 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2837 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2838
2839 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2840 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002841}
2842
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002843/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002844 * HalInterface inner class methods
2845 */
2846
Yifan Hongf79b5542017-04-11 14:44:25 -07002847Camera3Device::HalInterface::HalInterface(
2848 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002849 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002850 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002851 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002852 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08002853 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002854 mIsReconfigurationQuerySupported(true),
2855 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002856 // Check with hardware service manager if we can downcast these interfaces
2857 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002858 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
2859 if (castResult_3_6.isOk()) {
2860 mHidlSession_3_6 = castResult_3_6;
2861 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002862 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
2863 if (castResult_3_5.isOk()) {
2864 mHidlSession_3_5 = castResult_3_5;
2865 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002866 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
2867 if (castResult_3_4.isOk()) {
2868 mHidlSession_3_4 = castResult_3_4;
2869 }
2870 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
2871 if (castResult_3_3.isOk()) {
2872 mHidlSession_3_3 = castResult_3_3;
2873 }
2874}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002875
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002876Camera3Device::HalInterface::HalInterface() :
2877 mUseHalBufManager(false),
2878 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002879
2880Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002881 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002882 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002883 mUseHalBufManager(other.mUseHalBufManager),
2884 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002885
2886bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01002887 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002888}
2889
2890void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002891 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00002892 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00002893 mHidlSession_3_4.clear();
2894 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002895 mHidlSession.clear();
2896}
2897
2898status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2899 camera3_request_template_t templateId,
2900 /*out*/ camera_metadata_t **requestTemplate) {
2901 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
2902 if (!valid()) return INVALID_OPERATION;
2903 status_t res = OK;
2904
Emilian Peev31abd0a2017-05-11 18:37:46 +01002905 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002906
2907 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01002908 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002909 status = s;
2910 if (status == common::V1_0::Status::OK) {
2911 const camera_metadata *r =
2912 reinterpret_cast<const camera_metadata_t*>(request.data());
2913 size_t expectedSize = request.size();
2914 int ret = validate_camera_metadata_structure(r, &expectedSize);
2915 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
2916 *requestTemplate = clone_camera_metadata(r);
2917 if (*requestTemplate == nullptr) {
2918 ALOGE("%s: Unable to clone camera metadata received from HAL",
2919 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01002920 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002921 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002922 } else {
2923 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
2924 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01002925 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002926 }
2927 };
2928 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08002929 RequestTemplate id;
2930 switch (templateId) {
2931 case CAMERA3_TEMPLATE_PREVIEW:
2932 id = RequestTemplate::PREVIEW;
2933 break;
2934 case CAMERA3_TEMPLATE_STILL_CAPTURE:
2935 id = RequestTemplate::STILL_CAPTURE;
2936 break;
2937 case CAMERA3_TEMPLATE_VIDEO_RECORD:
2938 id = RequestTemplate::VIDEO_RECORD;
2939 break;
2940 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
2941 id = RequestTemplate::VIDEO_SNAPSHOT;
2942 break;
2943 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
2944 id = RequestTemplate::ZERO_SHUTTER_LAG;
2945 break;
2946 case CAMERA3_TEMPLATE_MANUAL:
2947 id = RequestTemplate::MANUAL;
2948 break;
2949 default:
2950 // Unknown template ID, or this HAL is too old to support it
2951 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002952 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08002953 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002954
Emilian Peev31abd0a2017-05-11 18:37:46 +01002955 if (!err.isOk()) {
2956 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
2957 res = DEAD_OBJECT;
2958 } else {
2959 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002960 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01002961
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002962 return res;
2963}
2964
Emilian Peev4ec17882019-01-24 17:16:58 -08002965bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
2966 CameraMetadata& newSessionParams) {
2967 // We do reconfiguration by default;
2968 bool ret = true;
2969 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
2970 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
2971 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
2972 oldSessionParams.getAndLock());
2973 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
2974 newSessionParams.getAndLock());
2975 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
2976 get_camera_metadata_size(oldSessioMeta));
2977 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
2978 get_camera_metadata_size(newSessioMeta));
2979 hardware::camera::common::V1_0::Status callStatus;
2980 bool required;
2981 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
2982 bool requiredFlag) {
2983 callStatus = s;
2984 required = requiredFlag;
2985 };
2986 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
2987 oldSessionParams.unlock(oldSessioMeta);
2988 newSessionParams.unlock(newSessioMeta);
2989 if (err.isOk()) {
2990 switch (callStatus) {
2991 case hardware::camera::common::V1_0::Status::OK:
2992 ret = required;
2993 break;
2994 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
2995 mIsReconfigurationQuerySupported = false;
2996 ret = true;
2997 break;
2998 default:
2999 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3000 ret = true;
3001 }
3002 } else {
3003 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3004 ret = true;
3005 }
3006 }
3007
3008 return ret;
3009}
3010
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003011status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003012 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003013 ATRACE_NAME("CameraHal::configureStreams");
3014 if (!valid()) return INVALID_OPERATION;
3015 status_t res = OK;
3016
Emilian Peev31abd0a2017-05-11 18:37:46 +01003017 // Convert stream config to HIDL
3018 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003019 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3020 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3021 requestedConfiguration3_2.streams.resize(config->num_streams);
3022 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003023 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003024 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3025 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003026 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003027
Emilian Peev31abd0a2017-05-11 18:37:46 +01003028 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3029 cam3stream->setBufferFreedListener(this);
3030 int streamId = cam3stream->getId();
3031 StreamType streamType;
3032 switch (src->stream_type) {
3033 case CAMERA3_STREAM_OUTPUT:
3034 streamType = StreamType::OUTPUT;
3035 break;
3036 case CAMERA3_STREAM_INPUT:
3037 streamType = StreamType::INPUT;
3038 break;
3039 default:
3040 ALOGE("%s: Stream %d: Unsupported stream type %d",
3041 __FUNCTION__, streamId, config->streams[i]->stream_type);
3042 return BAD_VALUE;
3043 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003044 dst3_2.id = streamId;
3045 dst3_2.streamType = streamType;
3046 dst3_2.width = src->width;
3047 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003048 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003049 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003050 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3051 // to HAL are original, not the overriden ones.
3052 if (mHidlSession_3_5 != nullptr) {
3053 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3054 cam3stream->getOriginalFormat() : src->format);
3055 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3056 cam3stream->getOriginalDataSpace() : src->data_space);
3057 } else {
3058 dst3_2.format = mapToPixelFormat(src->format);
3059 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3060 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003061 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003062 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003063 if (src->physical_camera_id != nullptr) {
3064 dst3_4.physicalCameraId = src->physical_camera_id;
3065 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003066
3067 activeStreams.insert(streamId);
3068 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003069 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003070 }
3071 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003072 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003073
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003074 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003075 res = mapToStreamConfigurationMode(
3076 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003077 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003078 if (res != OK) {
3079 return res;
3080 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003081 requestedConfiguration3_2.operationMode = operationMode;
3082 requestedConfiguration3_4.operationMode = operationMode;
3083 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003084 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3085 get_camera_metadata_size(sessionParams));
3086
Emilian Peev31abd0a2017-05-11 18:37:46 +01003087 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003088 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003089 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003090 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003091 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003092
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003093 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003094 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3095 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003096 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003097 };
3098
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003099 auto configStream36Cb = [&status, &finalConfiguration3_6]
3100 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3101 finalConfiguration3_6 = halConfiguration;
3102 status = s;
3103 };
3104
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003105 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3106 (hardware::Return<void>& err) -> status_t {
3107 if (!err.isOk()) {
3108 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3109 return DEAD_OBJECT;
3110 }
3111 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3112 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3113 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3114 }
3115 return OK;
3116 };
3117
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003118 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3119 (hardware::Return<void>& err) -> status_t {
3120 if (!err.isOk()) {
3121 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3122 return DEAD_OBJECT;
3123 }
3124 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3125 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3126 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3127 }
3128 return OK;
3129 };
3130
Shuzhen Wang92653952019-05-07 15:11:43 -07003131 // See which version of HAL we have
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003132 if (mHidlSession_3_6 != nullptr) {
3133 ALOGV("%s: v3.6 device found", __FUNCTION__);
3134 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3135 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3136 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3137 auto err = mHidlSession_3_6->configureStreams_3_6(
3138 requestedConfiguration3_5, configStream36Cb);
3139 res = postprocConfigStream36(err);
3140 if (res != OK) {
3141 return res;
3142 }
3143 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003144 ALOGV("%s: v3.5 device found", __FUNCTION__);
3145 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3146 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3147 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3148 auto err = mHidlSession_3_5->configureStreams_3_5(
3149 requestedConfiguration3_5, configStream34Cb);
3150 res = postprocConfigStream34(err);
3151 if (res != OK) {
3152 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003153 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003154 } else if (mHidlSession_3_4 != nullptr) {
3155 // We do; use v3.4 for the call
3156 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003157 auto err = mHidlSession_3_4->configureStreams_3_4(
3158 requestedConfiguration3_4, configStream34Cb);
3159 res = postprocConfigStream34(err);
3160 if (res != OK) {
3161 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003162 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003163 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003164 // We do; use v3.3 for the call
3165 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003166 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003167 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003168 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003169 finalConfiguration = halConfiguration;
3170 status = s;
3171 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003172 if (!err.isOk()) {
3173 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3174 return DEAD_OBJECT;
3175 }
3176 } else {
3177 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3178 ALOGV("%s: v3.2 device found", __FUNCTION__);
3179 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003180 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003181 [&status, &finalConfiguration_3_2]
3182 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3183 finalConfiguration_3_2 = halConfiguration;
3184 status = s;
3185 });
3186 if (!err.isOk()) {
3187 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3188 return DEAD_OBJECT;
3189 }
3190 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3191 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3192 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3193 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003194 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003195 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003196 }
3197
3198 if (status != common::V1_0::Status::OK ) {
3199 return CameraProviderManager::mapToStatusT(status);
3200 }
3201
3202 // And convert output stream configuration from HIDL
3203
3204 for (size_t i = 0; i < config->num_streams; i++) {
3205 camera3_stream_t *dst = config->streams[i];
3206 int streamId = Camera3Stream::cast(dst)->getId();
3207
3208 // Start scan at i, with the assumption that the stream order matches
3209 size_t realIdx = i;
3210 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003211 size_t halStreamCount = finalConfiguration.streams.size();
3212 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003213 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003214 found = true;
3215 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003216 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003217 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003218 }
3219 if (!found) {
3220 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3221 __FUNCTION__, streamId);
3222 return INVALID_OPERATION;
3223 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003224 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003225 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003226
Emilian Peev710c1422017-08-30 11:19:38 +01003227 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003228 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3229 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3230
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003231 if (mHidlSession_3_6 != nullptr) {
3232 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3233 }
3234
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003235 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003236 dstStream->setFormatOverride(false);
3237 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003238 if (dst->format != overrideFormat) {
3239 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3240 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003241 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003242 if (dst->data_space != overrideDataSpace) {
3243 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3244 streamId, dst->format);
3245 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003246 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003247 bool needFormatOverride =
3248 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3249 bool needDataspaceOverride =
3250 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003251 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003252 dstStream->setFormatOverride(needFormatOverride);
3253 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003254 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003255 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003256 }
3257
Emilian Peev31abd0a2017-05-11 18:37:46 +01003258 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003259 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003260 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003261 __FUNCTION__, streamId);
3262 return INVALID_OPERATION;
3263 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003264 dstStream->setUsage(
3265 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003266 } else {
3267 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003268 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003269 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3270 __FUNCTION__, streamId);
3271 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003272 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003273 dstStream->setUsage(
3274 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003275 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003276 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003277 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003278
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003279 return res;
3280}
3281
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003282status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003283 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003284 /*out*/std::vector<native_handle_t*>* handlesCreated,
3285 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003286 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003287 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3288 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3289 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003290 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003291 }
3292
3293 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003294
3295 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003296
3297 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003298 if (request->input_buffer != nullptr) {
3299 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3300 buffer_handle_t buf = *(request->input_buffer->buffer);
3301 auto pair = getBufferId(buf, streamId);
3302 bool isNewBuffer = pair.first;
3303 uint64_t bufferId = pair.second;
3304 captureRequest->inputBuffer.streamId = streamId;
3305 captureRequest->inputBuffer.bufferId = bufferId;
3306 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3307 captureRequest->inputBuffer.status = BufferStatus::OK;
3308 native_handle_t *acquireFence = nullptr;
3309 if (request->input_buffer->acquire_fence != -1) {
3310 acquireFence = native_handle_create(1,0);
3311 acquireFence->data[0] = request->input_buffer->acquire_fence;
3312 handlesCreated->push_back(acquireFence);
3313 }
3314 captureRequest->inputBuffer.acquireFence = acquireFence;
3315 captureRequest->inputBuffer.releaseFence = nullptr;
3316
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003317 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003318 request->input_buffer->buffer);
3319 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003320 } else {
3321 captureRequest->inputBuffer.streamId = -1;
3322 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3323 }
3324
3325 captureRequest->outputBuffers.resize(request->num_output_buffers);
3326 for (size_t i = 0; i < request->num_output_buffers; i++) {
3327 const camera3_stream_buffer_t *src = request->output_buffers + i;
3328 StreamBuffer &dst = captureRequest->outputBuffers[i];
3329 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003330 if (src->buffer != nullptr) {
3331 buffer_handle_t buf = *(src->buffer);
3332 auto pair = getBufferId(buf, streamId);
3333 bool isNewBuffer = pair.first;
3334 dst.bufferId = pair.second;
3335 dst.buffer = isNewBuffer ? buf : nullptr;
3336 native_handle_t *acquireFence = nullptr;
3337 if (src->acquire_fence != -1) {
3338 acquireFence = native_handle_create(1,0);
3339 acquireFence->data[0] = src->acquire_fence;
3340 handlesCreated->push_back(acquireFence);
3341 }
3342 dst.acquireFence = acquireFence;
3343 } else if (mUseHalBufManager) {
3344 // HAL buffer management path
3345 dst.bufferId = BUFFER_ID_NO_BUFFER;
3346 dst.buffer = nullptr;
3347 dst.acquireFence = nullptr;
3348 } else {
3349 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3350 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003351 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003352 dst.streamId = streamId;
3353 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003354 dst.releaseFence = nullptr;
3355
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003356 // Output buffers are empty when using HAL buffer manager
3357 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003358 mBufferRecords.pushInflightBuffer(
3359 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003360 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003361 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003362 }
3363 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003364 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003365}
3366
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003367void Camera3Device::HalInterface::cleanupNativeHandles(
3368 std::vector<native_handle_t*> *handles, bool closeFd) {
3369 if (handles == nullptr) {
3370 return;
3371 }
3372 if (closeFd) {
3373 for (auto& handle : *handles) {
3374 native_handle_close(handle);
3375 }
3376 }
3377 for (auto& handle : *handles) {
3378 native_handle_delete(handle);
3379 }
3380 handles->clear();
3381 return;
3382}
3383
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003384status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3385 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3386 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3387 if (!valid()) return INVALID_OPERATION;
3388
Emilian Peevaebbe412018-01-15 13:53:24 +00003389 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3390 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3391 if (castResult_3_4.isOk()) {
3392 hidlSession_3_4 = castResult_3_4;
3393 }
3394
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003395 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003396 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003397 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003398 if (hidlSession_3_4 != nullptr) {
3399 captureRequests_3_4.resize(batchSize);
3400 } else {
3401 captureRequests.resize(batchSize);
3402 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003403 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003404 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003405
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003406 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003407 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003408 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003409 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003410 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003411 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003412 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3413 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003414 }
3415 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003416 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003417 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003418 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003419 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003420 }
3421
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003422 std::vector<device::V3_2::BufferCache> cachesToRemove;
3423 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003424 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003425 for (auto& pair : mFreedBuffers) {
3426 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003427 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003428 cachesToRemove.push_back({pair.first, pair.second});
3429 }
3430 }
3431 mFreedBuffers.clear();
3432 }
3433
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003434 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3435 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003436
3437 // Write metadata to FMQ.
3438 for (size_t i = 0; i < batchSize; i++) {
3439 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003440 device::V3_2::CaptureRequest* captureRequest;
3441 if (hidlSession_3_4 != nullptr) {
3442 captureRequest = &captureRequests_3_4[i].v3_2;
3443 } else {
3444 captureRequest = &captureRequests[i];
3445 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003446
3447 if (request->settings != nullptr) {
3448 size_t settingsSize = get_camera_metadata_size(request->settings);
3449 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3450 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3451 captureRequest->settings.resize(0);
3452 captureRequest->fmqSettingsSize = settingsSize;
3453 } else {
3454 if (mRequestMetadataQueue != nullptr) {
3455 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3456 }
3457 captureRequest->settings.setToExternal(
3458 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3459 get_camera_metadata_size(request->settings));
3460 captureRequest->fmqSettingsSize = 0u;
3461 }
3462 } else {
3463 // A null request settings maps to a size-0 CameraMetadata
3464 captureRequest->settings.resize(0);
3465 captureRequest->fmqSettingsSize = 0u;
3466 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003467
3468 if (hidlSession_3_4 != nullptr) {
3469 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3470 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003471 if (request->physcam_settings != nullptr) {
3472 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3473 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3474 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3475 settingsSize)) {
3476 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3477 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3478 settingsSize;
3479 } else {
3480 if (mRequestMetadataQueue != nullptr) {
3481 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3482 }
3483 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3484 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3485 request->physcam_settings[j])),
3486 get_camera_metadata_size(request->physcam_settings[j]));
3487 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003488 }
Emilian Peev00420d22018-02-05 21:33:13 +00003489 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003490 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003491 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003492 }
3493 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3494 request->physcam_id[j];
3495 }
3496 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003497 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003498
3499 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003500 auto resultCallback =
3501 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3502 status = s;
3503 *numRequestProcessed = n;
3504 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003505 if (hidlSession_3_4 != nullptr) {
3506 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003507 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003508 } else {
3509 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003510 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003511 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003512 if (!err.isOk()) {
3513 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003514 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003515 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003516
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003517 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3518 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3519 __FUNCTION__, *numRequestProcessed, batchSize);
3520 status = common::V1_0::Status::INTERNAL_ERROR;
3521 }
3522
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003523 res = CameraProviderManager::mapToStatusT(status);
3524 if (res == OK) {
3525 if (mHidlSession->isRemote()) {
3526 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3527 // sent to camera HAL processes)
3528 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3529 } else {
3530 // In passthrough mode the FDs are now owned by HAL
3531 cleanupNativeHandles(&handlesCreated);
3532 }
3533 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003534 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003535 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003536 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003537 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003538}
3539
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003540status_t Camera3Device::HalInterface::flush() {
3541 ATRACE_NAME("CameraHal::flush");
3542 if (!valid()) return INVALID_OPERATION;
3543 status_t res = OK;
3544
Emilian Peev31abd0a2017-05-11 18:37:46 +01003545 auto err = mHidlSession->flush();
3546 if (!err.isOk()) {
3547 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3548 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003549 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003550 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003551 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003552
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003553 return res;
3554}
3555
Emilian Peev31abd0a2017-05-11 18:37:46 +01003556status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003557 ATRACE_NAME("CameraHal::dump");
3558 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003559
Emilian Peev31abd0a2017-05-11 18:37:46 +01003560 // Handled by CameraProviderManager::dump
3561
3562 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003563}
3564
3565status_t Camera3Device::HalInterface::close() {
3566 ATRACE_NAME("CameraHal::close()");
3567 if (!valid()) return INVALID_OPERATION;
3568 status_t res = OK;
3569
Emilian Peev31abd0a2017-05-11 18:37:46 +01003570 auto err = mHidlSession->close();
3571 // Interface will be dead shortly anyway, so don't log errors
3572 if (!err.isOk()) {
3573 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003574 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003575
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003576 return res;
3577}
3578
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003579void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3580 ATRACE_NAME("CameraHal::signalPipelineDrain");
3581 if (!valid() || mHidlSession_3_5 == nullptr) {
3582 ALOGE("%s called on invalid camera!", __FUNCTION__);
3583 return;
3584 }
3585
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003586 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003587 if (!err.isOk()) {
3588 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3589 return;
3590 }
3591}
3592
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003593status_t Camera3Device::HalInterface::switchToOffline(
3594 const std::vector<int32_t>& streamsToKeep,
3595 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003596 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3597 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003598 ATRACE_NAME("CameraHal::switchToOffline");
3599 if (!valid() || mHidlSession_3_6 == nullptr) {
3600 ALOGE("%s called on invalid camera!", __FUNCTION__);
3601 return INVALID_OPERATION;
3602 }
3603
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003604 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3605 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003606 return INVALID_OPERATION;
3607 }
3608
3609 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003610 auto resultCallback =
3611 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3612 status = s;
3613 *offlineSessionInfo = info;
3614 *offlineSession = session;
3615 };
3616 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3617
3618 if (!err.isOk()) {
3619 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3620 return DEAD_OBJECT;
3621 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003622
3623 status_t ret = CameraProviderManager::mapToStatusT(status);
3624 if (ret != OK) {
3625 return ret;
3626 }
3627
3628 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3629 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3630 // returns from switchToOffline.
3631
3632
3633 // Validate buffer caches
3634 std::vector<int32_t> streams;
3635 streams.reserve(offlineSessionInfo->offlineStreams.size());
3636 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3637 int32_t id = offlineStream.id;
3638 streams.push_back(id);
3639 // Verify buffer caches
3640 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3641 offlineStream.circulatingBufferIds.end());
3642 if (!verifyBufferIds(id, bufIds)) {
3643 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3644 return UNKNOWN_ERROR;
3645 }
3646 }
3647
3648 // Move buffer records
3649 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3650 bufferRecords->takeInflightBufferMap(mBufferRecords);
3651 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3652 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003653}
3654
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003655void Camera3Device::HalInterface::getInflightBufferKeys(
3656 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003657 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003658 return;
3659}
3660
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003661void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3662 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003663 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003664 return;
3665}
3666
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003667bool Camera3Device::HalInterface::verifyBufferIds(
3668 int32_t streamId, std::vector<uint64_t>& bufIds) {
3669 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003670}
3671
3672status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003673 int32_t frameNumber, int32_t streamId,
3674 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003675 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003676}
3677
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003678status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003679 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003680 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003681}
3682
3683// Find and pop a buffer_handle_t based on bufferId
3684status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003685 uint64_t bufferId,
3686 /*out*/ buffer_handle_t** buffer,
3687 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003688 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003689}
3690
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003691std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3692 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003693 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003694}
3695
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003696void Camera3Device::HalInterface::onBufferFreed(
3697 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003698 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3699 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3700 if (bufferId != BUFFER_ID_NO_BUFFER) {
3701 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003702 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003703}
3704
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003705void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003706 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3707 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3708 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003709 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3710 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003711}
3712
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003713/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003714 * RequestThread inner class methods
3715 */
3716
3717Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003718 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003719 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3720 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003721 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003722 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003723 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003724 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003725 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003726 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003727 mReconfigured(false),
3728 mDoPause(false),
3729 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003730 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003731 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003732 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003733 mCurrentAfTriggerId(0),
3734 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003735 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003736 mRepeatingLastFrameNumber(
3737 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003738 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003739 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003740 mRequestLatency(kRequestLatencyBinSize),
3741 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003742 mLatestSessionParams(sessionParamKeys.size()),
3743 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003744 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003745}
3746
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003747Camera3Device::RequestThread::~RequestThread() {}
3748
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003749void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003750 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003751 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003752 Mutex::Autolock l(mRequestLock);
3753 mListener = listener;
3754}
3755
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003756void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3757 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003758 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003759 Mutex::Autolock l(mRequestLock);
3760 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003761 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003762 // Prepare video stream for high speed recording.
3763 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003764 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003765}
3766
Jianing Wei90e59c92014-03-12 18:29:36 -07003767status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003768 List<sp<CaptureRequest> > &requests,
3769 /*out*/
3770 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003771 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003772 Mutex::Autolock l(mRequestLock);
3773 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3774 ++it) {
3775 mRequestQueue.push_back(*it);
3776 }
3777
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003778 if (lastFrameNumber != NULL) {
3779 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3780 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3781 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3782 *lastFrameNumber);
3783 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003784
Jianing Wei90e59c92014-03-12 18:29:36 -07003785 unpauseForNewRequests();
3786
3787 return OK;
3788}
3789
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003790
3791status_t Camera3Device::RequestThread::queueTrigger(
3792 RequestTrigger trigger[],
3793 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003794 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003795 Mutex::Autolock l(mTriggerMutex);
3796 status_t ret;
3797
3798 for (size_t i = 0; i < count; ++i) {
3799 ret = queueTriggerLocked(trigger[i]);
3800
3801 if (ret != OK) {
3802 return ret;
3803 }
3804 }
3805
3806 return OK;
3807}
3808
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003809const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3810 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003811 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003812 if (d != nullptr) return d->mId;
3813 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003814}
3815
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003816status_t Camera3Device::RequestThread::queueTriggerLocked(
3817 RequestTrigger trigger) {
3818
3819 uint32_t tag = trigger.metadataTag;
3820 ssize_t index = mTriggerMap.indexOfKey(tag);
3821
3822 switch (trigger.getTagType()) {
3823 case TYPE_BYTE:
3824 // fall-through
3825 case TYPE_INT32:
3826 break;
3827 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003828 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3829 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003830 return INVALID_OPERATION;
3831 }
3832
3833 /**
3834 * Collect only the latest trigger, since we only have 1 field
3835 * in the request settings per trigger tag, and can't send more than 1
3836 * trigger per request.
3837 */
3838 if (index != NAME_NOT_FOUND) {
3839 mTriggerMap.editValueAt(index) = trigger;
3840 } else {
3841 mTriggerMap.add(tag, trigger);
3842 }
3843
3844 return OK;
3845}
3846
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003847status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003848 const RequestList &requests,
3849 /*out*/
3850 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003851 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003852 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003853 if (lastFrameNumber != NULL) {
3854 *lastFrameNumber = mRepeatingLastFrameNumber;
3855 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003856 mRepeatingRequests.clear();
3857 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3858 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003859
3860 unpauseForNewRequests();
3861
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003862 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003863 return OK;
3864}
3865
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003866bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003867 if (mRepeatingRequests.empty()) {
3868 return false;
3869 }
3870 int32_t requestId = requestIn->mResultExtras.requestId;
3871 const RequestList &repeatRequests = mRepeatingRequests;
3872 // All repeating requests are guaranteed to have same id so only check first quest
3873 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3874 return (firstRequest->mResultExtras.requestId == requestId);
3875}
3876
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003877status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003878 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003879 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003880 return clearRepeatingRequestsLocked(lastFrameNumber);
3881
3882}
3883
3884status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003885 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003886 if (lastFrameNumber != NULL) {
3887 *lastFrameNumber = mRepeatingLastFrameNumber;
3888 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003889 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003890 return OK;
3891}
3892
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003893status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003894 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003895 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003896 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003897 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003898
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003899 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003900
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003901 // Send errors for all requests pending in the request queue, including
3902 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003903 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003904 if (listener != NULL) {
3905 for (RequestList::iterator it = mRequestQueue.begin();
3906 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003907 // Abort the input buffers for reprocess requests.
3908 if ((*it)->mInputStream != NULL) {
3909 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003910 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3911 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003912 if (res != OK) {
3913 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3914 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3915 } else {
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07003916 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003917 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3918 if (res != OK) {
3919 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3920 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3921 }
3922 }
3923 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003924 // Set the frame number this request would have had, if it
3925 // had been submitted; this frame number will not be reused.
3926 // The requestId and burstId fields were set when the request was
3927 // submitted originally (in convertMetadataListToRequestListLocked)
3928 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003929 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003930 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003931 }
3932 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003933 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003934
3935 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003936 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003937 if (lastFrameNumber != NULL) {
3938 *lastFrameNumber = mRepeatingLastFrameNumber;
3939 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003940 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003941 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003942 return OK;
3943}
3944
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003945status_t Camera3Device::RequestThread::flush() {
3946 ATRACE_CALL();
3947 Mutex::Autolock l(mFlushLock);
3948
Emilian Peev08dd2452017-04-06 16:55:14 +01003949 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003950}
3951
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003952void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003953 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003954 Mutex::Autolock l(mPauseLock);
3955 mDoPause = paused;
3956 mDoPauseSignal.signal();
3957}
3958
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003959status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3960 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003961 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003962 Mutex::Autolock l(mLatestRequestMutex);
3963 status_t res;
3964 while (mLatestRequestId != requestId) {
3965 nsecs_t startTime = systemTime();
3966
3967 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3968 if (res != OK) return res;
3969
3970 timeout -= (systemTime() - startTime);
3971 }
3972
3973 return OK;
3974}
3975
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003976void Camera3Device::RequestThread::requestExit() {
3977 // Call parent to set up shutdown
3978 Thread::requestExit();
3979 // The exit from any possible waits
3980 mDoPauseSignal.signal();
3981 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003982
3983 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3984 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003985}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003986
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003987void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003988 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003989 bool surfaceAbandoned = false;
3990 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003991 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003992 {
3993 Mutex::Autolock l(mRequestLock);
3994 // Check all streams needed by repeating requests are still valid. Otherwise, stop
3995 // repeating requests.
3996 for (const auto& request : mRepeatingRequests) {
3997 for (const auto& s : request->mOutputStreams) {
3998 if (s->isAbandoned()) {
3999 surfaceAbandoned = true;
4000 clearRepeatingRequestsLocked(&lastFrameNumber);
4001 break;
4002 }
4003 }
4004 if (surfaceAbandoned) {
4005 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004006 }
4007 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004008 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004009 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004010
4011 if (listener != NULL && surfaceAbandoned) {
4012 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004013 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004014}
4015
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004016bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004017 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004018 status_t res;
4019 size_t batchSize = mNextRequests.size();
4020 std::vector<camera3_capture_request_t*> requests(batchSize);
4021 uint32_t numRequestProcessed = 0;
4022 for (size_t i = 0; i < batchSize; i++) {
4023 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004024 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004025 }
4026
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004027 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4028
4029 bool triggerRemoveFailed = false;
4030 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4031 for (size_t i = 0; i < numRequestProcessed; i++) {
4032 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4033 nextRequest.submitted = true;
4034
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004035 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004036
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004037 if (!triggerRemoveFailed) {
4038 // Remove any previously queued triggers (after unlock)
4039 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4040 if (removeTriggerRes != OK) {
4041 triggerRemoveFailed = true;
4042 triggerFailedRequest = nextRequest;
4043 }
4044 }
4045 }
4046
4047 if (triggerRemoveFailed) {
4048 SET_ERR("RequestThread: Unable to remove triggers "
4049 "(capture request %d, HAL device: %s (%d)",
4050 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4051 cleanUpFailedRequests(/*sendRequestError*/ false);
4052 return false;
4053 }
4054
4055 if (res != OK) {
4056 // Should only get a failure here for malformed requests or device-level
4057 // errors, so consider all errors fatal. Bad metadata failures should
4058 // come through notify.
4059 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4060 mNextRequests[numRequestProcessed].halRequest.frame_number,
4061 strerror(-res), res);
4062 cleanUpFailedRequests(/*sendRequestError*/ false);
4063 return false;
4064 }
4065 return true;
4066}
4067
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004068nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4069 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4070 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4071 find_camera_metadata_ro_entry(request,
4072 ANDROID_CONTROL_AE_MODE,
4073 &e);
4074 if (e.count == 0) return maxExpectedDuration;
4075
4076 switch (e.data.u8[0]) {
4077 case ANDROID_CONTROL_AE_MODE_OFF:
4078 find_camera_metadata_ro_entry(request,
4079 ANDROID_SENSOR_EXPOSURE_TIME,
4080 &e);
4081 if (e.count > 0) {
4082 maxExpectedDuration = e.data.i64[0];
4083 }
4084 find_camera_metadata_ro_entry(request,
4085 ANDROID_SENSOR_FRAME_DURATION,
4086 &e);
4087 if (e.count > 0) {
4088 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4089 }
4090 break;
4091 default:
4092 find_camera_metadata_ro_entry(request,
4093 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4094 &e);
4095 if (e.count > 1) {
4096 maxExpectedDuration = 1e9 / e.data.u8[0];
4097 }
4098 break;
4099 }
4100
4101 return maxExpectedDuration;
4102}
4103
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004104bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4105 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4106 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4107 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4108 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4109 return true;
4110 }
4111
4112 return false;
4113}
4114
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004115void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4116 // Update the latest request sent to HAL
4117 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4118 Mutex::Autolock al(mLatestRequestMutex);
4119
4120 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4121 mLatestRequest.acquire(cloned);
4122
4123 mLatestPhysicalRequest.clear();
4124 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
4125 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
4126 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
4127 CameraMetadata(cloned));
4128 }
4129
4130 sp<Camera3Device> parent = mParent.promote();
4131 if (parent != NULL) {
4132 parent->monitorMetadata(TagMonitor::REQUEST,
4133 nextRequest.halRequest.frame_number,
4134 0, mLatestRequest, mLatestPhysicalRequest);
4135 }
4136 }
4137
4138 if (nextRequest.halRequest.settings != NULL) {
4139 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4140 nextRequest.halRequest.settings);
4141 }
4142
4143 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4144}
4145
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004146bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4147 ATRACE_CALL();
4148 bool updatesDetected = false;
4149
Emilian Peev4ec17882019-01-24 17:16:58 -08004150 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004151 for (auto tag : mSessionParamKeys) {
4152 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004153 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004154
4155 if (entry.count > 0) {
4156 bool isDifferent = false;
4157 if (lastEntry.count > 0) {
4158 // Have a last value, compare to see if changed
4159 if (lastEntry.type == entry.type &&
4160 lastEntry.count == entry.count) {
4161 // Same type and count, compare values
4162 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4163 size_t entryBytes = bytesPerValue * lastEntry.count;
4164 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4165 if (cmp != 0) {
4166 isDifferent = true;
4167 }
4168 } else {
4169 // Count or type has changed
4170 isDifferent = true;
4171 }
4172 } else {
4173 // No last entry, so always consider to be different
4174 isDifferent = true;
4175 }
4176
4177 if (isDifferent) {
4178 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004179 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4180 updatesDetected = true;
4181 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004182 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004183 }
4184 } else if (lastEntry.count > 0) {
4185 // Value has been removed
4186 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004187 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004188 updatesDetected = true;
4189 }
4190 }
4191
Emilian Peev4ec17882019-01-24 17:16:58 -08004192 bool reconfigureRequired;
4193 if (updatesDetected) {
4194 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4195 updatedParams);
4196 mLatestSessionParams = updatedParams;
4197 } else {
4198 reconfigureRequired = false;
4199 }
4200
4201 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004202}
4203
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004204bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004205 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004206 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004207 // Any function called from threadLoop() must not hold mInterfaceLock since
4208 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4209 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004210
4211 // Handle paused state.
4212 if (waitIfPaused()) {
4213 return true;
4214 }
4215
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004216 // Wait for the next batch of requests.
4217 waitForNextRequestBatch();
4218 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004219 return true;
4220 }
4221
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004222 // Get the latest request ID, if any
4223 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004224 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004225 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004226 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004227 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004228 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004229 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4230 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004231 }
4232
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004233 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4234 // or a single request from streaming or burst. In either case the first element
4235 // should contain the latest camera settings that we need to check for any session
4236 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004237 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004238 res = OK;
4239
4240 //Input stream buffers are already acquired at this point so an input stream
4241 //will not be able to move to idle state unless we force it.
4242 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4243 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4244 if (res != OK) {
4245 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4246 cleanUpFailedRequests(/*sendRequestError*/ false);
4247 return false;
4248 }
4249 }
4250
4251 if (res == OK) {
4252 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4253 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004254 sp<Camera3Device> parent = mParent.promote();
4255 if (parent != nullptr) {
4256 parent->pauseStateNotify(true);
4257 }
4258
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004259 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4260
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004261 if (parent != nullptr) {
4262 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4263 }
4264
4265 statusTracker->markComponentActive(mStatusId);
4266 setPaused(false);
4267 }
4268
4269 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4270 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4271 if (res != OK) {
4272 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4273 cleanUpFailedRequests(/*sendRequestError*/ false);
4274 return false;
4275 }
4276 }
4277 }
4278 }
4279
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004280 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004281 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004282 if (res == TIMED_OUT) {
4283 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004284 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004285 // Check if any stream is abandoned.
4286 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004287 return true;
4288 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004289 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004290 return false;
4291 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004292
Zhijun Hecc27e112013-10-03 16:12:43 -07004293 // Inform waitUntilRequestProcessed thread of a new request ID
4294 {
4295 Mutex::Autolock al(mLatestRequestMutex);
4296
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004297 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004298 mLatestRequestSignal.signal();
4299 }
4300
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004301 // Submit a batch of requests to HAL.
4302 // Use flush lock only when submitting multilple requests in a batch.
4303 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4304 // which may take a long time to finish so synchronizing flush() and
4305 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4306 // For now, only synchronize for high speed recording and we should figure something out for
4307 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004308 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004309
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004310 if (useFlushLock) {
4311 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004312 }
4313
Zhijun Hef0645c12016-08-02 00:58:11 -07004314 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004315 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004316
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004317 sp<Camera3Device> parent = mParent.promote();
4318 if (parent != nullptr) {
4319 parent->mRequestBufferSM.onSubmittingRequest();
4320 }
4321
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004322 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004323 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004324 submitRequestSuccess = sendRequestsBatch();
4325
Shuzhen Wang686f6442017-06-20 16:16:04 -07004326 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4327 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004328
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004329 if (useFlushLock) {
4330 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004331 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004332
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004333 // Unset as current request
4334 {
4335 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004336 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004337 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004338 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004339
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004340 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004341}
4342
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004343status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004344 ATRACE_CALL();
4345
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004346 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004347 for (size_t i = 0; i < mNextRequests.size(); i++) {
4348 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004349 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4350 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4351 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4352
4353 // Prepare a request to HAL
4354 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4355
4356 // Insert any queued triggers (before metadata is locked)
4357 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004358 if (res < 0) {
4359 SET_ERR("RequestThread: Unable to insert triggers "
4360 "(capture request %d, HAL device: %s (%d)",
4361 halRequest->frame_number, strerror(-res), res);
4362 return INVALID_OPERATION;
4363 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004364
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004365 int triggerCount = res;
4366 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4367 mPrevTriggers = triggerCount;
4368
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004369 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
4370
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004371 // If the request is the same as last, or we had triggers last time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004372 bool newRequest =
4373 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004374 // Request settings are all the same within one batch, so only treat the first
4375 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004376 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004377 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004378 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004379 /**
4380 * HAL workaround:
4381 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4382 */
4383 res = addDummyTriggerIds(captureRequest);
4384 if (res != OK) {
4385 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4386 "(capture request %d, HAL device: %s (%d)",
4387 halRequest->frame_number, strerror(-res), res);
4388 return INVALID_OPERATION;
4389 }
4390
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004391 {
4392 // Correct metadata regions for distortion correction if enabled
4393 sp<Camera3Device> parent = mParent.promote();
4394 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004395 List<PhysicalCameraSettings>::iterator it;
4396 for (it = captureRequest->mSettingsList.begin();
4397 it != captureRequest->mSettingsList.end(); it++) {
4398 if (parent->mDistortionMappers.find(it->cameraId) ==
4399 parent->mDistortionMappers.end()) {
4400 continue;
4401 }
4402 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4403 &(it->metadata));
4404 if (res != OK) {
4405 SET_ERR("RequestThread: Unable to correct capture requests "
4406 "for lens distortion for request %d: %s (%d)",
4407 halRequest->frame_number, strerror(-res), res);
4408 return INVALID_OPERATION;
4409 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004410 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004411
4412 for (it = captureRequest->mSettingsList.begin();
4413 it != captureRequest->mSettingsList.end(); it++) {
4414 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4415 parent->mZoomRatioMappers.end()) {
4416 continue;
4417 }
4418
4419 camera_metadata_entry_t e = it->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
4420 if (e.count > 0 && e.data.f[0] != 1.0f) {
4421 cameraIdsWithZoom.insert(it->cameraId);
4422 }
4423
4424 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4425 &(it->metadata));
4426 if (res != OK) {
4427 SET_ERR("RequestThread: Unable to correct capture requests "
4428 "for zoom ratio for request %d: %s (%d)",
4429 halRequest->frame_number, strerror(-res), res);
4430 return INVALID_OPERATION;
4431 }
4432 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004433 if (captureRequest->mRotateAndCropAuto) {
4434 for (it = captureRequest->mSettingsList.begin();
4435 it != captureRequest->mSettingsList.end(); it++) {
4436 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4437 if (mapper != parent->mRotateAndCropMappers.end()) {
4438 res = mapper->second.updateCaptureRequest(&(it->metadata));
4439 if (res != OK) {
4440 SET_ERR("RequestThread: Unable to correct capture requests "
4441 "for rotate-and-crop for request %d: %s (%d)",
4442 halRequest->frame_number, strerror(-res), res);
4443 return INVALID_OPERATION;
4444 }
4445 }
4446 }
4447 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004448 }
4449 }
4450
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004451 /**
4452 * The request should be presorted so accesses in HAL
4453 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4454 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004455 captureRequest->mSettingsList.begin()->metadata.sort();
4456 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004457 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004458 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004459 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4460
4461 IF_ALOGV() {
4462 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4463 find_camera_metadata_ro_entry(
4464 halRequest->settings,
4465 ANDROID_CONTROL_AF_TRIGGER,
4466 &e
4467 );
4468 if (e.count > 0) {
4469 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4470 __FUNCTION__,
4471 halRequest->frame_number,
4472 e.data.u8[0]);
4473 }
4474 }
4475 } else {
4476 // leave request.settings NULL to indicate 'reuse latest given'
4477 ALOGVV("%s: Request settings are REUSED",
4478 __FUNCTION__);
4479 }
4480
Emilian Peevaebbe412018-01-15 13:53:24 +00004481 if (captureRequest->mSettingsList.size() > 1) {
4482 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4483 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004484 if (newRequest) {
4485 halRequest->physcam_settings =
4486 new const camera_metadata* [halRequest->num_physcam_settings];
4487 } else {
4488 halRequest->physcam_settings = nullptr;
4489 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004490 auto it = ++captureRequest->mSettingsList.begin();
4491 size_t i = 0;
4492 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4493 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004494 if (newRequest) {
4495 it->metadata.sort();
4496 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4497 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004498 }
4499 }
4500
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004501 uint32_t totalNumBuffers = 0;
4502
4503 // Fill in buffers
4504 if (captureRequest->mInputStream != NULL) {
4505 halRequest->input_buffer = &captureRequest->mInputBuffer;
4506 totalNumBuffers += 1;
4507 } else {
4508 halRequest->input_buffer = NULL;
4509 }
4510
4511 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4512 captureRequest->mOutputStreams.size());
4513 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004514 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004515
4516 sp<Camera3Device> parent = mParent.promote();
4517 if (parent == NULL) {
4518 // Should not happen, and nowhere to send errors to, so just log it
4519 CLOGE("RequestThread: Parent is gone");
4520 return INVALID_OPERATION;
4521 }
4522 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4523
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004524 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004525 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004526 sp<Camera3OutputStreamInterface> outputStream =
4527 captureRequest->mOutputStreams.editItemAt(j);
4528 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004529
4530 // Prepare video buffers for high speed recording on the first video request.
4531 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4532 // Only try to prepare video stream on the first video request.
4533 mPrepareVideoStream = false;
4534
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004535 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4536 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004537 while (res == NOT_ENOUGH_DATA) {
4538 res = outputStream->prepareNextBuffer();
4539 }
4540 if (res != OK) {
4541 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4542 __FUNCTION__, strerror(-res), res);
4543 outputStream->cancelPrepare();
4544 }
4545 }
4546
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004547 std::vector<size_t> uniqueSurfaceIds;
4548 res = outputStream->getUniqueSurfaceIds(
4549 captureRequest->mOutputSurfaces[streamId],
4550 &uniqueSurfaceIds);
4551 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4552 if (res != OK && res != INVALID_OPERATION) {
4553 ALOGE("%s: failed to query stream %d unique surface IDs",
4554 __FUNCTION__, streamId);
4555 return res;
4556 }
4557 if (res == OK) {
4558 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4559 }
4560
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004561 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004562 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004563 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004564 return TIMED_OUT;
4565 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004566 // HAL will request buffer through requestStreamBuffer API
4567 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
4568 buffer.stream = outputStream->asHalStream();
4569 buffer.buffer = nullptr;
4570 buffer.status = CAMERA3_BUFFER_STATUS_OK;
4571 buffer.acquire_fence = -1;
4572 buffer.release_fence = -1;
4573 } else {
4574 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4575 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004576 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004577 if (res != OK) {
4578 // Can't get output buffer from gralloc queue - this could be due to
4579 // abandoned queue or other consumer misbehavior, so not a fatal
4580 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004581 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004582 " %s (%d)", strerror(-res), res);
4583
4584 return TIMED_OUT;
4585 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004586 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004587
4588 {
4589 sp<Camera3Device> parent = mParent.promote();
4590 if (parent != nullptr) {
4591 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4592 for (const auto& settings : captureRequest->mSettingsList) {
4593 if ((streamCameraId.isEmpty() &&
4594 parent->getId() == settings.cameraId.c_str()) ||
4595 streamCameraId == settings.cameraId.c_str()) {
4596 outputStream->fireBufferRequestForFrameNumber(
4597 captureRequest->mResultExtras.frameNumber,
4598 settings.metadata);
4599 }
4600 }
4601 }
4602 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004603
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004604 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4605
4606 if (!physicalCameraId.isEmpty()) {
4607 // Physical stream isn't supported for input request.
4608 if (halRequest->input_buffer) {
4609 CLOGE("Physical stream is not supported for input request");
4610 return INVALID_OPERATION;
4611 }
4612 requestedPhysicalCameras.insert(physicalCameraId);
4613 }
4614 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004615 }
4616 totalNumBuffers += halRequest->num_output_buffers;
4617
4618 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004619 // If this request list is for constrained high speed recording (not
4620 // preview), and the current request is not the last one in the batch,
4621 // do not send callback to the app.
4622 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004623 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004624 hasCallback = false;
4625 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004626 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004627 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01004628 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4629 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4630 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4631 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4632 isStillCapture = true;
4633 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4634 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004635
4636 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
4637 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4638 isZslCapture = true;
4639 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004640 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004641 res = parent->registerInFlight(halRequest->frame_number,
4642 totalNumBuffers, captureRequest->mResultExtras,
4643 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004644 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004645 calculateMaxExpectedDuration(halRequest->settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004646 requestedPhysicalCameras, isStillCapture, isZslCapture,
4647 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004648 (mUseHalBufManager) ? uniqueSurfaceIdMap :
4649 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004650 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4651 ", burstId = %" PRId32 ".",
4652 __FUNCTION__,
4653 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4654 captureRequest->mResultExtras.burstId);
4655 if (res != OK) {
4656 SET_ERR("RequestThread: Unable to register new in-flight request:"
4657 " %s (%d)", strerror(-res), res);
4658 return INVALID_OPERATION;
4659 }
4660 }
4661
4662 return OK;
4663}
4664
Igor Murashkin1e479c02013-09-06 16:55:14 -07004665CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004666 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004667 Mutex::Autolock al(mLatestRequestMutex);
4668
4669 ALOGV("RequestThread::%s", __FUNCTION__);
4670
4671 return mLatestRequest;
4672}
4673
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004674bool Camera3Device::RequestThread::isStreamPending(
4675 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004676 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004677 Mutex::Autolock l(mRequestLock);
4678
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004679 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004680 if (!nextRequest.submitted) {
4681 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4682 if (stream == s) return true;
4683 }
4684 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004685 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004686 }
4687
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004688 for (const auto& request : mRequestQueue) {
4689 for (const auto& s : request->mOutputStreams) {
4690 if (stream == s) return true;
4691 }
4692 if (stream == request->mInputStream) return true;
4693 }
4694
4695 for (const auto& request : mRepeatingRequests) {
4696 for (const auto& s : request->mOutputStreams) {
4697 if (stream == s) return true;
4698 }
4699 if (stream == request->mInputStream) return true;
4700 }
4701
4702 return false;
4703}
Jianing Weicb0652e2014-03-12 18:29:36 -07004704
Emilian Peev40ead602017-09-26 15:46:36 +01004705bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4706 ATRACE_CALL();
4707 Mutex::Autolock l(mRequestLock);
4708
4709 for (const auto& nextRequest : mNextRequests) {
4710 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4711 if (s.first == streamId) {
4712 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4713 if (it != s.second.end()) {
4714 return true;
4715 }
4716 }
4717 }
4718 }
4719
4720 for (const auto& request : mRequestQueue) {
4721 for (const auto& s : request->mOutputSurfaces) {
4722 if (s.first == streamId) {
4723 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4724 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004725 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004726 }
4727 }
4728 }
4729 }
4730
4731 for (const auto& request : mRepeatingRequests) {
4732 for (const auto& s : request->mOutputSurfaces) {
4733 if (s.first == streamId) {
4734 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4735 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004736 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004737 }
4738 }
4739 }
4740 }
4741
4742 return false;
4743}
4744
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004745void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4746 if (!mUseHalBufManager) {
4747 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4748 return;
4749 }
4750
4751 Mutex::Autolock pl(mPauseLock);
4752 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004753 mInterface->signalPipelineDrain(streamIds);
4754 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004755 }
4756 // If request thread is still busy, wait until paused then notify HAL
4757 mNotifyPipelineDrain = true;
4758 mStreamIdsToBeDrained = streamIds;
4759}
4760
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004761void Camera3Device::RequestThread::clearPreviousRequest() {
4762 Mutex::Autolock l(mRequestLock);
4763 mPrevRequest.clear();
4764}
4765
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004766status_t Camera3Device::RequestThread::switchToOffline(
4767 const std::vector<int32_t>& streamsToKeep,
4768 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004769 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4770 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004771 Mutex::Autolock l(mRequestLock);
4772 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
4773
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004774 // Wait until request thread is fully stopped
4775 // TBD: check if request thread is being paused by other APIs (shouldn't be)
4776
4777 // We could also check for mRepeatingRequests.empty(), but the API interface
4778 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
4779 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004780 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4781 while (!queueEmpty) {
4782 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
4783 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004784 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004785 return res;
4786 } else if (res != OK) {
4787 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
4788 __FUNCTION__, strerror(-res), res);
4789 return res;
4790 }
4791 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4792 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004793
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004794 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004795 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004796}
4797
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004798status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4799 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4800 ATRACE_CALL();
4801 Mutex::Autolock l(mTriggerMutex);
4802 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4803 return BAD_VALUE;
4804 }
4805 mRotateAndCropOverride = rotateAndCropValue;
4806 return OK;
4807}
4808
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004809nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004810 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004811 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004812 return mExpectedInflightDuration > kMinInflightDuration ?
4813 mExpectedInflightDuration : kMinInflightDuration;
4814}
4815
Emilian Peevaebbe412018-01-15 13:53:24 +00004816void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4817 camera3_capture_request_t *halRequest) {
4818 if ((request == nullptr) || (halRequest == nullptr)) {
4819 ALOGE("%s: Invalid request!", __FUNCTION__);
4820 return;
4821 }
4822
4823 if (halRequest->num_physcam_settings > 0) {
4824 if (halRequest->physcam_id != nullptr) {
4825 delete [] halRequest->physcam_id;
4826 halRequest->physcam_id = nullptr;
4827 }
4828 if (halRequest->physcam_settings != nullptr) {
4829 auto it = ++(request->mSettingsList.begin());
4830 size_t i = 0;
4831 for (; it != request->mSettingsList.end(); it++, i++) {
4832 it->metadata.unlock(halRequest->physcam_settings[i]);
4833 }
4834 delete [] halRequest->physcam_settings;
4835 halRequest->physcam_settings = nullptr;
4836 }
4837 }
4838}
4839
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004840void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4841 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004842 return;
4843 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004844
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004845 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004846 // Skip the ones that have been submitted successfully.
4847 if (nextRequest.submitted) {
4848 continue;
4849 }
4850
4851 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4852 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4853 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4854
4855 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004856 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004857 }
4858
Emilian Peevaebbe412018-01-15 13:53:24 +00004859 cleanupPhysicalSettings(captureRequest, halRequest);
4860
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004861 if (captureRequest->mInputStream != NULL) {
4862 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4863 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4864 }
4865
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004866 // No output buffer can be returned when using HAL buffer manager
4867 if (!mUseHalBufManager) {
4868 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4869 //Buffers that failed processing could still have
4870 //valid acquire fence.
4871 int acquireFence = (*outputBuffers)[i].acquire_fence;
4872 if (0 <= acquireFence) {
4873 close(acquireFence);
4874 outputBuffers->editItemAt(i).acquire_fence = -1;
4875 }
4876 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4877 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
4878 /*timestampIncreasing*/true, std::vector<size_t> (),
4879 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004880 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004881 }
4882
4883 if (sendRequestError) {
4884 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004885 sp<NotificationListener> listener = mListener.promote();
4886 if (listener != NULL) {
4887 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004888 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004889 captureRequest->mResultExtras);
4890 }
4891 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004892
4893 // Remove yet-to-be submitted inflight request from inflightMap
4894 {
4895 sp<Camera3Device> parent = mParent.promote();
4896 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004897 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004898 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4899 if (idx >= 0) {
4900 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4901 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4902 parent->removeInFlightMapEntryLocked(idx);
4903 }
4904 }
4905 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004906 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004907
4908 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004909 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004910}
4911
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004912void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004913 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004914 // Optimized a bit for the simple steady-state case (single repeating
4915 // request), to avoid putting that request in the queue temporarily.
4916 Mutex::Autolock l(mRequestLock);
4917
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004918 assert(mNextRequests.empty());
4919
4920 NextRequest nextRequest;
4921 nextRequest.captureRequest = waitForNextRequestLocked();
4922 if (nextRequest.captureRequest == nullptr) {
4923 return;
4924 }
4925
4926 nextRequest.halRequest = camera3_capture_request_t();
4927 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004928 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004929
4930 // Wait for additional requests
4931 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4932
4933 for (size_t i = 1; i < batchSize; i++) {
4934 NextRequest additionalRequest;
4935 additionalRequest.captureRequest = waitForNextRequestLocked();
4936 if (additionalRequest.captureRequest == nullptr) {
4937 break;
4938 }
4939
4940 additionalRequest.halRequest = camera3_capture_request_t();
4941 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004942 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004943 }
4944
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004945 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004946 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004947 mNextRequests.size(), batchSize);
4948 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004949 }
4950
4951 return;
4952}
4953
4954sp<Camera3Device::CaptureRequest>
4955 Camera3Device::RequestThread::waitForNextRequestLocked() {
4956 status_t res;
4957 sp<CaptureRequest> nextRequest;
4958
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004959 while (mRequestQueue.empty()) {
4960 if (!mRepeatingRequests.empty()) {
4961 // Always atomically enqueue all requests in a repeating request
4962 // list. Guarantees a complete in-sequence set of captures to
4963 // application.
4964 const RequestList &requests = mRepeatingRequests;
4965 RequestList::const_iterator firstRequest =
4966 requests.begin();
4967 nextRequest = *firstRequest;
4968 mRequestQueue.insert(mRequestQueue.end(),
4969 ++firstRequest,
4970 requests.end());
4971 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004972
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004973 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004974
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004975 break;
4976 }
4977
4978 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4979
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004980 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4981 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004982 Mutex::Autolock pl(mPauseLock);
4983 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004984 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004985 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004986 if (mNotifyPipelineDrain) {
4987 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4988 mNotifyPipelineDrain = false;
4989 mStreamIdsToBeDrained.clear();
4990 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004991 // Let the tracker know
4992 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4993 if (statusTracker != 0) {
4994 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4995 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004996 sp<Camera3Device> parent = mParent.promote();
4997 if (parent != nullptr) {
4998 parent->mRequestBufferSM.onRequestThreadPaused();
4999 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005000 }
5001 // Stop waiting for now and let thread management happen
5002 return NULL;
5003 }
5004 }
5005
5006 if (nextRequest == NULL) {
5007 // Don't have a repeating request already in hand, so queue
5008 // must have an entry now.
5009 RequestList::iterator firstRequest =
5010 mRequestQueue.begin();
5011 nextRequest = *firstRequest;
5012 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005013 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5014 sp<NotificationListener> listener = mListener.promote();
5015 if (listener != NULL) {
5016 listener->notifyRequestQueueEmpty();
5017 }
5018 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005019 }
5020
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005021 // In case we've been unpaused by setPaused clearing mDoPause, need to
5022 // update internal pause state (capture/setRepeatingRequest unpause
5023 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005024 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005025 if (mPaused) {
5026 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5027 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5028 if (statusTracker != 0) {
5029 statusTracker->markComponentActive(mStatusId);
5030 }
5031 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005032 mPaused = false;
5033
5034 // Check if we've reconfigured since last time, and reset the preview
5035 // request if so. Can't use 'NULL request == repeat' across configure calls.
5036 if (mReconfigured) {
5037 mPrevRequest.clear();
5038 mReconfigured = false;
5039 }
5040
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005041 if (nextRequest != NULL) {
5042 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005043 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5044 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005045
5046 // Since RequestThread::clear() removes buffers from the input stream,
5047 // get the right buffer here before unlocking mRequestLock
5048 if (nextRequest->mInputStream != NULL) {
5049 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5050 if (res != OK) {
5051 // Can't get input buffer from gralloc queue - this could be due to
5052 // disconnected queue or other producer misbehavior, so not a fatal
5053 // error
5054 ALOGE("%s: Can't get input buffer, skipping request:"
5055 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005056
5057 sp<NotificationListener> listener = mListener.promote();
5058 if (listener != NULL) {
5059 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005060 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005061 nextRequest->mResultExtras);
5062 }
5063 return NULL;
5064 }
5065 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005066 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005067
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005068 return nextRequest;
5069}
5070
5071bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005072 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005073 status_t res;
5074 Mutex::Autolock l(mPauseLock);
5075 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005076 if (mPaused == false) {
5077 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005078 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005079 if (mNotifyPipelineDrain) {
5080 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5081 mNotifyPipelineDrain = false;
5082 mStreamIdsToBeDrained.clear();
5083 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005084 // Let the tracker know
5085 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5086 if (statusTracker != 0) {
5087 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5088 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005089 sp<Camera3Device> parent = mParent.promote();
5090 if (parent != nullptr) {
5091 parent->mRequestBufferSM.onRequestThreadPaused();
5092 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005093 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005094
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005095 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005096 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005097 return true;
5098 }
5099 }
5100 // We don't set mPaused to false here, because waitForNextRequest needs
5101 // to further manage the paused state in case of starvation.
5102 return false;
5103}
5104
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005105void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005106 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005107 // With work to do, mark thread as unpaused.
5108 // If paused by request (setPaused), don't resume, to avoid
5109 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005110 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005111 Mutex::Autolock p(mPauseLock);
5112 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005113 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5114 if (mPaused) {
5115 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5116 if (statusTracker != 0) {
5117 statusTracker->markComponentActive(mStatusId);
5118 }
5119 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005120 mPaused = false;
5121 }
5122}
5123
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005124void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5125 sp<Camera3Device> parent = mParent.promote();
5126 if (parent != NULL) {
5127 va_list args;
5128 va_start(args, fmt);
5129
5130 parent->setErrorStateV(fmt, args);
5131
5132 va_end(args);
5133 }
5134}
5135
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005136status_t Camera3Device::RequestThread::insertTriggers(
5137 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005138 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005139 Mutex::Autolock al(mTriggerMutex);
5140
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005141 sp<Camera3Device> parent = mParent.promote();
5142 if (parent == NULL) {
5143 CLOGE("RequestThread: Parent is gone");
5144 return DEAD_OBJECT;
5145 }
5146
Emilian Peevaebbe412018-01-15 13:53:24 +00005147 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005148 size_t count = mTriggerMap.size();
5149
5150 for (size_t i = 0; i < count; ++i) {
5151 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005152 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005153
5154 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5155 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5156 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005157 if (isAeTrigger) {
5158 request->mResultExtras.precaptureTriggerId = triggerId;
5159 mCurrentPreCaptureTriggerId = triggerId;
5160 } else {
5161 request->mResultExtras.afTriggerId = triggerId;
5162 mCurrentAfTriggerId = triggerId;
5163 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005164 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005165 }
5166
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005167 camera_metadata_entry entry = metadata.find(tag);
5168
5169 if (entry.count > 0) {
5170 /**
5171 * Already has an entry for this trigger in the request.
5172 * Rewrite it with our requested trigger value.
5173 */
5174 RequestTrigger oldTrigger = trigger;
5175
5176 oldTrigger.entryValue = entry.data.u8[0];
5177
5178 mTriggerReplacedMap.add(tag, oldTrigger);
5179 } else {
5180 /**
5181 * More typical, no trigger entry, so we just add it
5182 */
5183 mTriggerRemovedMap.add(tag, trigger);
5184 }
5185
5186 status_t res;
5187
5188 switch (trigger.getTagType()) {
5189 case TYPE_BYTE: {
5190 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5191 res = metadata.update(tag,
5192 &entryValue,
5193 /*count*/1);
5194 break;
5195 }
5196 case TYPE_INT32:
5197 res = metadata.update(tag,
5198 &trigger.entryValue,
5199 /*count*/1);
5200 break;
5201 default:
5202 ALOGE("%s: Type not supported: 0x%x",
5203 __FUNCTION__,
5204 trigger.getTagType());
5205 return INVALID_OPERATION;
5206 }
5207
5208 if (res != OK) {
5209 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5210 ", value %d", __FUNCTION__, trigger.getTagName(),
5211 trigger.entryValue);
5212 return res;
5213 }
5214
5215 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5216 trigger.getTagName(),
5217 trigger.entryValue);
5218 }
5219
5220 mTriggerMap.clear();
5221
5222 return count;
5223}
5224
5225status_t Camera3Device::RequestThread::removeTriggers(
5226 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005227 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005228 Mutex::Autolock al(mTriggerMutex);
5229
Emilian Peevaebbe412018-01-15 13:53:24 +00005230 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005231
5232 /**
5233 * Replace all old entries with their old values.
5234 */
5235 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5236 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5237
5238 status_t res;
5239
5240 uint32_t tag = trigger.metadataTag;
5241 switch (trigger.getTagType()) {
5242 case TYPE_BYTE: {
5243 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5244 res = metadata.update(tag,
5245 &entryValue,
5246 /*count*/1);
5247 break;
5248 }
5249 case TYPE_INT32:
5250 res = metadata.update(tag,
5251 &trigger.entryValue,
5252 /*count*/1);
5253 break;
5254 default:
5255 ALOGE("%s: Type not supported: 0x%x",
5256 __FUNCTION__,
5257 trigger.getTagType());
5258 return INVALID_OPERATION;
5259 }
5260
5261 if (res != OK) {
5262 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5263 ", trigger value %d", __FUNCTION__,
5264 trigger.getTagName(), trigger.entryValue);
5265 return res;
5266 }
5267 }
5268 mTriggerReplacedMap.clear();
5269
5270 /**
5271 * Remove all new entries.
5272 */
5273 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5274 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5275 status_t res = metadata.erase(trigger.metadataTag);
5276
5277 if (res != OK) {
5278 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5279 ", trigger value %d", __FUNCTION__,
5280 trigger.getTagName(), trigger.entryValue);
5281 return res;
5282 }
5283 }
5284 mTriggerRemovedMap.clear();
5285
5286 return OK;
5287}
5288
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005289status_t Camera3Device::RequestThread::addDummyTriggerIds(
5290 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005291 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005292 static const int32_t dummyTriggerId = 1;
5293 status_t res;
5294
Emilian Peevaebbe412018-01-15 13:53:24 +00005295 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005296
5297 // If AF trigger is active, insert a dummy AF trigger ID if none already
5298 // exists
5299 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5300 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5301 if (afTrigger.count > 0 &&
5302 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5303 afId.count == 0) {
5304 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5305 if (res != OK) return res;
5306 }
5307
5308 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5309 // if none already exists
5310 camera_metadata_entry pcTrigger =
5311 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5312 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5313 if (pcTrigger.count > 0 &&
5314 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5315 pcId.count == 0) {
5316 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5317 &dummyTriggerId, 1);
5318 if (res != OK) return res;
5319 }
5320
5321 return OK;
5322}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005323
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005324bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5325 const sp<CaptureRequest> &request) {
5326 ATRACE_CALL();
5327
5328 if (request->mRotateAndCropAuto) {
5329 Mutex::Autolock l(mTriggerMutex);
5330 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5331
5332 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5333 if (rotateAndCropEntry.count > 0) {
5334 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5335 return false;
5336 } else {
5337 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5338 return true;
5339 }
5340 } else {
5341 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5342 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5343 &rotateAndCrop_u8, 1);
5344 return true;
5345 }
5346 }
5347 return false;
5348}
5349
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005350/**
5351 * PreparerThread inner class methods
5352 */
5353
5354Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005355 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005356 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005357}
5358
5359Camera3Device::PreparerThread::~PreparerThread() {
5360 Thread::requestExitAndWait();
5361 if (mCurrentStream != nullptr) {
5362 mCurrentStream->cancelPrepare();
5363 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5364 mCurrentStream.clear();
5365 }
5366 clear();
5367}
5368
Ruben Brunkc78ac262015-08-13 17:58:46 -07005369status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005370 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005371 status_t res;
5372
5373 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005374 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005375
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005376 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005377 if (res == OK) {
5378 // No preparation needed, fire listener right off
5379 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005380 if (listener != NULL) {
5381 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005382 }
5383 return OK;
5384 } else if (res != NOT_ENOUGH_DATA) {
5385 return res;
5386 }
5387
5388 // Need to prepare, start up thread if necessary
5389 if (!mActive) {
5390 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5391 // isn't running
5392 Thread::requestExitAndWait();
5393 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5394 if (res != OK) {
5395 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005396 if (listener != NULL) {
5397 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005398 }
5399 return res;
5400 }
5401 mCancelNow = false;
5402 mActive = true;
5403 ALOGV("%s: Preparer stream started", __FUNCTION__);
5404 }
5405
5406 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005407 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005408 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5409
5410 return OK;
5411}
5412
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005413void Camera3Device::PreparerThread::pause() {
5414 ATRACE_CALL();
5415
5416 Mutex::Autolock l(mLock);
5417
5418 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5419 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5420 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5421 int currentMaxCount = mCurrentMaxCount;
5422 mPendingStreams.clear();
5423 mCancelNow = true;
5424 while (mActive) {
5425 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5426 if (res == TIMED_OUT) {
5427 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5428 return;
5429 } else if (res != OK) {
5430 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5431 return;
5432 }
5433 }
5434
5435 //Check whether the prepare thread was able to complete the current
5436 //stream. In case work is still pending emplace it along with the rest
5437 //of the streams in the pending list.
5438 if (currentStream != nullptr) {
5439 if (!mCurrentPrepareComplete) {
5440 pendingStreams.emplace(currentMaxCount, currentStream);
5441 }
5442 }
5443
5444 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5445 for (const auto& it : mPendingStreams) {
5446 it.second->cancelPrepare();
5447 }
5448}
5449
5450status_t Camera3Device::PreparerThread::resume() {
5451 ATRACE_CALL();
5452 status_t res;
5453
5454 Mutex::Autolock l(mLock);
5455 sp<NotificationListener> listener = mListener.promote();
5456
5457 if (mActive) {
5458 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5459 return NO_INIT;
5460 }
5461
5462 auto it = mPendingStreams.begin();
5463 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005464 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005465 if (res == OK) {
5466 if (listener != NULL) {
5467 listener->notifyPrepared(it->second->getId());
5468 }
5469 it = mPendingStreams.erase(it);
5470 } else if (res != NOT_ENOUGH_DATA) {
5471 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5472 res, strerror(-res));
5473 it = mPendingStreams.erase(it);
5474 } else {
5475 it++;
5476 }
5477 }
5478
5479 if (mPendingStreams.empty()) {
5480 return OK;
5481 }
5482
5483 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5484 if (res != OK) {
5485 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5486 __FUNCTION__, res, strerror(-res));
5487 return res;
5488 }
5489 mCancelNow = false;
5490 mActive = true;
5491 ALOGV("%s: Preparer stream started", __FUNCTION__);
5492
5493 return OK;
5494}
5495
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005496status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005497 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005498 Mutex::Autolock l(mLock);
5499
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005500 for (const auto& it : mPendingStreams) {
5501 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005502 }
5503 mPendingStreams.clear();
5504 mCancelNow = true;
5505
5506 return OK;
5507}
5508
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005509void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005510 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005511 Mutex::Autolock l(mLock);
5512 mListener = listener;
5513}
5514
5515bool Camera3Device::PreparerThread::threadLoop() {
5516 status_t res;
5517 {
5518 Mutex::Autolock l(mLock);
5519 if (mCurrentStream == nullptr) {
5520 // End thread if done with work
5521 if (mPendingStreams.empty()) {
5522 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5523 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5524 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5525 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005526 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005527 return false;
5528 }
5529
5530 // Get next stream to prepare
5531 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005532 mCurrentStream = it->second;
5533 mCurrentMaxCount = it->first;
5534 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005535 mPendingStreams.erase(it);
5536 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5537 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5538 } else if (mCancelNow) {
5539 mCurrentStream->cancelPrepare();
5540 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5541 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5542 mCurrentStream.clear();
5543 mCancelNow = false;
5544 return true;
5545 }
5546 }
5547
5548 res = mCurrentStream->prepareNextBuffer();
5549 if (res == NOT_ENOUGH_DATA) return true;
5550 if (res != OK) {
5551 // Something bad happened; try to recover by cancelling prepare and
5552 // signalling listener anyway
5553 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5554 mCurrentStream->getId(), res, strerror(-res));
5555 mCurrentStream->cancelPrepare();
5556 }
5557
5558 // This stream has finished, notify listener
5559 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005560 sp<NotificationListener> listener = mListener.promote();
5561 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005562 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5563 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005564 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005565 }
5566
5567 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5568 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005569 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005570
5571 return true;
5572}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005573
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005574status_t Camera3Device::RequestBufferStateMachine::initialize(
5575 sp<camera3::StatusTracker> statusTracker) {
5576 if (statusTracker == nullptr) {
5577 ALOGE("%s: statusTracker is null", __FUNCTION__);
5578 return BAD_VALUE;
5579 }
5580
5581 std::lock_guard<std::mutex> lock(mLock);
5582 mStatusTracker = statusTracker;
5583 mRequestBufferStatusId = statusTracker->addComponent();
5584 return OK;
5585}
5586
5587bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5588 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005589 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005590 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005591 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005592 return true;
5593 }
5594 return false;
5595}
5596
5597void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5598 std::lock_guard<std::mutex> lock(mLock);
5599 if (!mRequestBufferOngoing) {
5600 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5601 return;
5602 }
5603 mRequestBufferOngoing = false;
5604 if (mStatus == RB_STATUS_PENDING_STOP) {
5605 checkSwitchToStopLocked();
5606 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005607 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005608}
5609
5610void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5611 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005612 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005613 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005614 return;
5615}
5616
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005617void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005618 std::lock_guard<std::mutex> lock(mLock);
5619 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005620 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5621 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005622 mInflightMapEmpty = false;
5623 if (mStatus == RB_STATUS_STOPPED) {
5624 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005625 }
5626 return;
5627}
5628
5629void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5630 std::lock_guard<std::mutex> lock(mLock);
5631 mRequestThreadPaused = true;
5632 if (mStatus == RB_STATUS_PENDING_STOP) {
5633 checkSwitchToStopLocked();
5634 }
5635 return;
5636}
5637
5638void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5639 std::lock_guard<std::mutex> lock(mLock);
5640 mInflightMapEmpty = true;
5641 if (mStatus == RB_STATUS_PENDING_STOP) {
5642 checkSwitchToStopLocked();
5643 }
5644 return;
5645}
5646
5647void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5648 std::lock_guard<std::mutex> lock(mLock);
5649 if (!checkSwitchToStopLocked()) {
5650 mStatus = RB_STATUS_PENDING_STOP;
5651 }
5652 return;
5653}
5654
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005655bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5656 std::lock_guard<std::mutex> lock(mLock);
5657 if (mRequestBufferOngoing) {
5658 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5659 __FUNCTION__);
5660 return false;
5661 }
5662 mSwitchedToOffline = true;
5663 mInflightMapEmpty = true;
5664 mRequestThreadPaused = true;
5665 mStatus = RB_STATUS_STOPPED;
5666 return true;
5667}
5668
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005669void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5670 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5671 if (statusTracker != nullptr) {
5672 if (active) {
5673 statusTracker->markComponentActive(mRequestBufferStatusId);
5674 } else {
5675 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5676 }
5677 }
5678}
5679
5680bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5681 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5682 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005683 return true;
5684 }
5685 return false;
5686}
5687
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005688bool Camera3Device::startRequestBuffer() {
5689 return mRequestBufferSM.startRequestBuffer();
5690}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005691
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005692void Camera3Device::endRequestBuffer() {
5693 mRequestBufferSM.endRequestBuffer();
5694}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005695
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005696nsecs_t Camera3Device::getWaitDuration() {
5697 return kBaseGetBufferWait + getExpectedInFlightDuration();
5698}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005699
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005700void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5701 mInterface->getInflightBufferKeys(out);
5702}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005703
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005704void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5705 mInterface->getInflightRequestBufferKeys(out);
5706}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005707
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005708std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5709 std::vector<sp<Camera3StreamInterface>> ret;
5710 bool hasInputStream = mInputStream != nullptr;
5711 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5712 if (hasInputStream) {
5713 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005714 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005715 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5716 ret.push_back(mOutputStreams[i]);
5717 }
5718 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5719 ret.push_back(mDeletedStreams[i]);
5720 }
5721 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005722}
5723
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005724status_t Camera3Device::switchToOffline(
5725 const std::vector<int32_t>& streamsToKeep,
5726 /*out*/ sp<CameraOfflineSessionBase>* session) {
5727 ATRACE_CALL();
5728 if (session == nullptr) {
5729 ALOGE("%s: session must not be null", __FUNCTION__);
5730 return BAD_VALUE;
5731 }
5732
5733 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005734
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005735 bool hasInputStream = mInputStream != nullptr;
5736 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
5737 bool inputStreamSupportsOffline = hasInputStream ?
5738 mInputStream->getOfflineProcessingSupport() : false;
5739 auto outputStreamIds = mOutputStreams.getStreamIds();
5740 auto streamIds = outputStreamIds;
5741 if (hasInputStream) {
5742 streamIds.push_back(mInputStream->getId());
5743 }
5744
5745 // Check all streams in streamsToKeep supports offline mode
5746 for (auto id : streamsToKeep) {
5747 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5748 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
5749 return BAD_VALUE;
5750 } else if (id == inputStreamId) {
5751 if (!inputStreamSupportsOffline) {
5752 ALOGE("%s: input stream %d cannot be switched to offline",
5753 __FUNCTION__, id);
5754 return BAD_VALUE;
5755 }
5756 } else {
5757 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
5758 if (!stream->getOfflineProcessingSupport()) {
5759 ALOGE("%s: output stream %d cannot be switched to offline",
5760 __FUNCTION__, id);
5761 return BAD_VALUE;
5762 }
5763 }
5764 }
5765
5766 // TODO: block surface sharing and surface group streams until we can support them
5767
5768 // Stop repeating request, wait until all remaining requests are submitted, then call into
5769 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005770 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
5771 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005772 camera3::BufferRecords bufferRecords;
5773 status_t ret = mRequestThread->switchToOffline(
5774 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005775
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005776 if (ret != OK) {
5777 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
5778 return ret;
5779 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005780
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005781 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
5782 if (!succ) {
5783 SET_ERR("HAL must not be calling requestStreamBuffers call");
5784 // TODO: block ALL callbacks from HAL till app configured new streams?
5785 return UNKNOWN_ERROR;
5786 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005787
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005788 // Verify offlineSessionInfo
5789 std::vector<int32_t> offlineStreamIds;
5790 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
5791 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5792 // verify stream IDs
5793 int32_t id = offlineStream.id;
5794 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5795 SET_ERR("stream ID %d not found!", id);
5796 return UNKNOWN_ERROR;
5797 }
5798
5799 // When not using HAL buf manager, only allow streams requested by app to be preserved
5800 if (!mUseHalBufManager) {
5801 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
5802 SET_ERR("stream ID %d must not be switched to offline!", id);
5803 return UNKNOWN_ERROR;
5804 }
5805 }
5806
5807 offlineStreamIds.push_back(id);
5808 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
5809 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
5810 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
5811 // Verify number of outstanding buffers
5812 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
5813 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
5814 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
5815 return UNKNOWN_ERROR;
5816 }
5817 }
5818
5819 // Verify all streams to be deleted don't have any outstanding buffers
5820 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5821 inputStreamId) == offlineStreamIds.end()) {
5822 if (mInputStream->hasOutstandingBuffers()) {
5823 SET_ERR("Input stream %d still has %zu outstanding buffer!",
5824 inputStreamId, mInputStream->getOutstandingBuffersCount());
5825 return UNKNOWN_ERROR;
5826 }
5827 }
5828
5829 for (const auto& outStreamId : outputStreamIds) {
5830 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5831 outStreamId) == offlineStreamIds.end()) {
5832 auto outStream = mOutputStreams.get(outStreamId);
5833 if (outStream->hasOutstandingBuffers()) {
5834 SET_ERR("Output stream %d still has %zu outstanding buffer!",
5835 outStreamId, outStream->getOutstandingBuffersCount());
5836 return UNKNOWN_ERROR;
5837 }
5838 }
5839 }
5840
5841 InFlightRequestMap offlineReqs;
5842 // Verify inflight requests and their pending buffers
5843 {
5844 std::lock_guard<std::mutex> l(mInFlightLock);
5845 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
5846 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
5847 if (idx == NAME_NOT_FOUND) {
5848 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
5849 return UNKNOWN_ERROR;
5850 }
5851
5852 const auto& inflightReq = mInFlightMap.valueAt(idx);
5853 // TODO: check specific stream IDs
5854 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
5855 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
5856 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
5857 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
5858 return UNKNOWN_ERROR;
5859 }
5860 offlineReqs.add(offlineReq.frameNumber, inflightReq);
5861 }
5862 }
5863
5864 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005865 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005866 camera3::StreamSet offlineStreamSet;
5867 sp<camera3::Camera3Stream> inputStream;
5868 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5869 int32_t id = offlineStream.id;
5870 if (mInputStream != nullptr && id == mInputStream->getId()) {
5871 inputStream = mInputStream;
5872 } else {
5873 offlineStreamSet.add(id, mOutputStreams.get(id));
5874 }
5875 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005876
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005877 // TODO: check if we need to lock before copying states
5878 // though technically no other thread should be talking to Camera3Device at this point
5879 Camera3OfflineStates offlineStates(
5880 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
5881 mUsePartialResult, mNumPartialResults, mNextResultFrameNumber,
5882 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
5883 mNextShutterFrameNumber, mNextReprocessShutterFrameNumber,
5884 mNextZslStillShutterFrameNumber, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005885 mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005886
5887 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
5888 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
5889
5890 // Delete all streams that has been transferred to offline session
5891 Mutex::Autolock l(mLock);
5892 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5893 int32_t id = offlineStream.id;
5894 if (mInputStream != nullptr && id == mInputStream->getId()) {
5895 mInputStream.clear();
5896 } else {
5897 mOutputStreams.remove(id);
5898 }
5899 }
5900
5901 // disconnect all other streams and switch to UNCONFIGURED state
5902 if (mInputStream != nullptr) {
5903 ret = mInputStream->disconnect();
5904 if (ret != OK) {
5905 SET_ERR_L("disconnect input stream failed!");
5906 return UNKNOWN_ERROR;
5907 }
5908 }
5909
5910 for (auto streamId : mOutputStreams.getStreamIds()) {
5911 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
5912 ret = stream->disconnect();
5913 if (ret != OK) {
5914 SET_ERR_L("disconnect output stream %d failed!", streamId);
5915 return UNKNOWN_ERROR;
5916 }
5917 }
5918
5919 mInputStream.clear();
5920 mOutputStreams.clear();
5921 mNeedConfig = true;
5922 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
5923 mOperatingMode = NO_MODE;
5924 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005925 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005926
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005927 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005928 // TO be done by CameraDeviceClient/Camera3OfflineSession
5929 // register the offline client to camera service
5930 // Setup result passthing threads etc
5931 // Initialize offline session so HAL can start sending callback to it (result Fmq)
5932 // TODO: check how many onIdle callback will be sent
5933 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005934}
5935
Emilian Peevcc0b7952020-01-07 13:54:47 -08005936void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5937 ATRACE_CALL();
5938
5939 if (offlineStreamIds == nullptr) {
5940 return;
5941 }
5942
5943 Mutex::Autolock il(mInterfaceLock);
5944
5945 auto streamIds = mOutputStreams.getStreamIds();
5946 bool hasInputStream = mInputStream != nullptr;
5947 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5948 offlineStreamIds->push_back(mInputStream->getId());
5949 }
5950
5951 for (const auto & streamId : streamIds) {
5952 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5953 // Streams that use the camera buffer manager are currently not supported in
5954 // offline mode
5955 if (stream->getOfflineProcessingSupport() &&
5956 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5957 offlineStreamIds->push_back(streamId);
5958 }
5959 }
5960}
5961
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005962status_t Camera3Device::setRotateAndCropAutoBehavior(
5963 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5964 ATRACE_CALL();
5965 Mutex::Autolock il(mInterfaceLock);
5966 Mutex::Autolock l(mLock);
5967 if (mRequestThread == nullptr) {
5968 return INVALID_OPERATION;
5969 }
5970 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5971}
5972
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005973}; // namespace android