blob: 7b3dfb44f0be2658a6e0409e92082718ccf14adc [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080052#include <android/hardware/camera2/ICameraDeviceUser.h>
53
Igor Murashkinff3e31d2013-10-23 16:40:06 -070054#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070055#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070056#include "device3/Camera3Device.h"
57#include "device3/Camera3OutputStream.h"
58#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070059#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070060#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070061#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070062#include "utils/CameraThreadState.h"
Jayant Chowdharyd4776262020-06-23 23:45:57 -070063#include "utils/TraceHFR.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080064
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080065#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080066#include <tuple>
67
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080068using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080069using namespace android::hardware::camera;
70using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080071
72namespace android {
73
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080074Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080075 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080076 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070077 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070078 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070079 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070080 mUsePartialResult(false),
81 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080082 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070083 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070084 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070085 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070086 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070087 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070088 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000089 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010090 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070091 mLastTemplateId(-1),
92 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080093{
94 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080095 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080096}
97
98Camera3Device::~Camera3Device()
99{
100 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700102 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800103}
104
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800105const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800106 return mId;
107}
108
Emilian Peevbd8c5032018-02-14 23:05:40 +0000109status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800110 ATRACE_CALL();
111 Mutex::Autolock il(mInterfaceLock);
112 Mutex::Autolock l(mLock);
113
114 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
115 if (mStatus != STATUS_UNINITIALIZED) {
116 CLOGE("Already initialized!");
117 return INVALID_OPERATION;
118 }
119 if (manager == nullptr) return INVALID_OPERATION;
120
121 sp<ICameraDeviceSession> session;
122 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800123 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800124 /*out*/ &session);
125 ATRACE_END();
126 if (res != OK) {
127 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
128 return res;
129 }
130
Steven Moreland5ff9c912017-03-09 23:13:00 -0800131 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800132 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700133 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800134 session->close();
135 return res;
136 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800137 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800138
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700139 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700140 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700141 if (isLogical) {
142 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700143 res = manager->getCameraCharacteristics(
144 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700145 if (res != OK) {
146 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
147 physicalId.c_str(), strerror(-res), res);
148 session->close();
149 return res;
150 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700151
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800152 bool usePrecorrectArray =
153 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
154 if (usePrecorrectArray) {
155 res = mDistortionMappers[physicalId].setupStaticInfo(
156 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700157 if (res != OK) {
158 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
159 "correction", physicalId.c_str());
160 session->close();
161 return res;
162 }
163 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800164
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800165 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800166 &mPhysicalDeviceInfoMap[physicalId],
167 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700168 }
169 }
170
Yifan Hongf79b5542017-04-11 14:44:25 -0700171 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700172 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
173 [&queue](const auto& descriptor) {
174 queue = std::make_shared<RequestMetadataQueue>(descriptor);
175 if (!queue->isValid() || queue->availableToWrite() <= 0) {
176 ALOGE("HAL returns empty request metadata fmq, not use it");
177 queue = nullptr;
178 // don't use the queue onwards.
179 }
180 });
181 if (!requestQueueRet.isOk()) {
182 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
183 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700184 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700185 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700186
187 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700188 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700189 [&resQueue](const auto& descriptor) {
190 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
191 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700192 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700193 resQueue = nullptr;
194 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700195 }
196 });
197 if (!resultQueueRet.isOk()) {
198 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
199 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700200 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700201 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700202 IF_ALOGV() {
203 session->interfaceChain([](
204 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
205 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800206 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700207 ALOGV(" %s", iface.c_str());
208 }
209 });
210 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700211
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800212 camera_metadata_entry bufMgrMode =
213 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
214 if (bufMgrMode.count > 0) {
215 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
216 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
217 }
218
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700219 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
220 for (size_t i = 0; i < capabilities.count; i++) {
221 uint8_t capability = capabilities.data.u8[i];
222 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
223 mSupportOfflineProcessing = true;
224 }
225 }
226
227 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000228 std::string providerType;
229 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000230 mTagMonitor.initialize(mVendorTagId);
231 if (!monitorTags.isEmpty()) {
232 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
233 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800234
Shuzhen Wang268a1362018-10-16 16:32:59 -0700235 // Metadata tags needs fixup for monochrome camera device version less
236 // than 3.5.
237 hardware::hidl_version maxVersion{0,0};
238 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
239 if (res != OK) {
240 ALOGE("%s: Error in getting camera device version id: %s (%d)",
241 __FUNCTION__, strerror(-res), res);
242 return res;
243 }
244 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
245 maxVersion.get_major(), maxVersion.get_minor());
246
247 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700248 for (size_t i = 0; i < capabilities.count; i++) {
249 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700250 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
251 isMonochrome = true;
252 }
253 }
254 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
255
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800256 return initializeCommonLocked();
257}
258
259status_t Camera3Device::initializeCommonLocked() {
260
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700261 /** Start up status tracker thread */
262 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800263 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700264 if (res != OK) {
265 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
266 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800267 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700268 mStatusTracker.clear();
269 return res;
270 }
271
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700272 /** Register in-flight map to the status tracker */
273 mInFlightStatusId = mStatusTracker->addComponent();
274
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700275 if (mUseHalBufManager) {
276 res = mRequestBufferSM.initialize(mStatusTracker);
277 if (res != OK) {
278 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
279 strerror(-res), res);
280 mInterface->close();
281 mStatusTracker.clear();
282 return res;
283 }
284 }
285
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800286 /** Create buffer manager */
287 mBufferManager = new Camera3BufferManager();
288
289 Vector<int32_t> sessionParamKeys;
290 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
291 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
292 if (sessionKeysEntry.count > 0) {
293 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
294 }
295
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700296 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700297 mRequestThread = new RequestThread(
298 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800299 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800300 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700301 SET_ERR_L("Unable to start request queue thread: %s (%d)",
302 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800303 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800304 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800305 return res;
306 }
307
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700308 mPreparerThread = new PreparerThread();
309
Ruben Brunk183f0562015-08-12 12:55:02 -0700310 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800311 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700312 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700313 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700314 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800315
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800316 // Measure the clock domain offset between camera and video/hw_composer
317 camera_metadata_entry timestampSource =
318 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
319 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
320 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
321 mTimestampOffset = getMonoToBoottimeOffset();
322 }
323
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700324 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100325 camera_metadata_entry partialResultsCount =
326 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
327 if (partialResultsCount.count > 0) {
328 mNumPartialResults = partialResultsCount.data.i32[0];
329 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700330 }
331
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700332 camera_metadata_entry configs =
333 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
334 for (uint32_t i = 0; i < configs.count; i += 4) {
335 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
336 configs.data.i32[i + 3] ==
337 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
338 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
339 configs.data.i32[i + 2]));
340 }
341 }
342
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800343 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
344 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700345 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700346 if (res != OK) {
347 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
348 return res;
349 }
350 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800351
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800352 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800353 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800354
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800355 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
356 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
357 }
358
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800359 return OK;
360}
361
362status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700363 return disconnectImpl();
364}
365
366status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800367 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700368 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800369
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700370 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700371 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700372 {
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800373 Mutex::Autolock il(mInterfaceLock);
374 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
375 {
376 Mutex::Autolock l(mLock);
377 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700378
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800379 if (mStatus == STATUS_ACTIVE ||
380 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
381 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700382 if (res != OK) {
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800383 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700384 // Continue to close device even in case of error
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800385 } else {
386 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
387 if (res != OK) {
388 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
389 maxExpectedDuration);
390 // Continue to close device even in case of error
391 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700392 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700393 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800394
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800395 if (mStatus == STATUS_ERROR) {
396 CLOGE("Shutting down in an error state");
397 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700398
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800399 if (mStatusTracker != NULL) {
400 mStatusTracker->requestExit();
401 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700402
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800403 if (mRequestThread != NULL) {
404 mRequestThread->requestExit();
405 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700406
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800407 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
408 for (size_t i = 0; i < mOutputStreams.size(); i++) {
409 streams.push_back(mOutputStreams[i]);
410 }
411 if (mInputStream != nullptr) {
412 streams.push_back(mInputStream);
413 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700414 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700415 }
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800416 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
417 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700418 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
419 // HAL may be in a bad state, so waiting for request thread
420 // (which may be stuck in the HAL processCaptureRequest call)
421 // could be dangerous.
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800422 // give up mInterfaceLock here and then lock it again. Could this lead
423 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700424 mRequestThread->join();
425 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700426 {
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800427 Mutex::Autolock il(mInterfaceLock);
428 if (mStatusTracker != NULL) {
429 mStatusTracker->join();
430 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800431
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800432 HalInterface* interface;
433 {
434 Mutex::Autolock l(mLock);
435 mRequestThread.clear();
436 Mutex::Autolock stLock(mTrackerLock);
437 mStatusTracker.clear();
438 interface = mInterface.get();
439 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700440
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800441 // Call close without internal mutex held, as the HAL close may need to
442 // wait on assorted callbacks,etc, to complete before it can return.
443 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700444
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800445 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800446
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800447 {
448 Mutex::Autolock l(mLock);
449 mInterface->clear();
450 mOutputStreams.clear();
451 mInputStream.clear();
452 mDeletedStreams.clear();
453 mBufferManager.clear();
454 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
455 }
456
457 for (auto& weakStream : streams) {
458 sp<Camera3StreamInterface> stream = weakStream.promote();
459 if (stream != nullptr) {
460 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
461 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
462 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700463 }
464 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700465 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700466 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800467}
468
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700469// For dumping/debugging only -
470// try to acquire a lock a few times, eventually give up to proceed with
471// debug/dump operations
472bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
473 bool gotLock = false;
474 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
475 if (lock.tryLock() == NO_ERROR) {
476 gotLock = true;
477 break;
478 } else {
479 usleep(kDumpSleepDuration);
480 }
481 }
482 return gotLock;
483}
484
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700485Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
486 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100487 const int STREAM_CONFIGURATION_SIZE = 4;
488 const int STREAM_FORMAT_OFFSET = 0;
489 const int STREAM_WIDTH_OFFSET = 1;
490 const int STREAM_HEIGHT_OFFSET = 2;
491 const int STREAM_IS_INPUT_OFFSET = 3;
492 camera_metadata_ro_entry_t availableStreamConfigs =
493 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
494 if (availableStreamConfigs.count == 0 ||
495 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
496 return Size(0, 0);
497 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700498
Emilian Peev08dd2452017-04-06 16:55:14 +0100499 // Get max jpeg size (area-wise).
500 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
501 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
502 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
503 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
504 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
505 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
506 && format == HAL_PIXEL_FORMAT_BLOB &&
507 (width * height > maxJpegWidth * maxJpegHeight)) {
508 maxJpegWidth = width;
509 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700510 }
511 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100512
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700513 return Size(maxJpegWidth, maxJpegHeight);
514}
515
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800516nsecs_t Camera3Device::getMonoToBoottimeOffset() {
517 // try three times to get the clock offset, choose the one
518 // with the minimum gap in measurements.
519 const int tries = 3;
520 nsecs_t bestGap, measured;
521 for (int i = 0; i < tries; ++i) {
522 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
523 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
524 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
525 const nsecs_t gap = tmono2 - tmono;
526 if (i == 0 || gap < bestGap) {
527 bestGap = gap;
528 measured = tbase - ((tmono + tmono2) >> 1);
529 }
530 }
531 return measured;
532}
533
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
535 int frameworkFormat) {
536 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
537}
538
539DataspaceFlags Camera3Device::mapToHidlDataspace(
540 android_dataspace dataSpace) {
541 return dataSpace;
542}
543
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700544BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100545 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700546 return usage;
547}
548
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800549StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
550 switch (rotation) {
551 case CAMERA3_STREAM_ROTATION_0:
552 return StreamRotation::ROTATION_0;
553 case CAMERA3_STREAM_ROTATION_90:
554 return StreamRotation::ROTATION_90;
555 case CAMERA3_STREAM_ROTATION_180:
556 return StreamRotation::ROTATION_180;
557 case CAMERA3_STREAM_ROTATION_270:
558 return StreamRotation::ROTATION_270;
559 }
560 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
561 return StreamRotation::ROTATION_0;
562}
563
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800564status_t Camera3Device::mapToStreamConfigurationMode(
565 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
566 if (mode == nullptr) return BAD_VALUE;
567 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
568 switch(operationMode) {
569 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
570 *mode = StreamConfigurationMode::NORMAL_MODE;
571 break;
572 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
573 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
574 break;
575 default:
576 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
577 return BAD_VALUE;
578 }
579 } else {
580 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800581 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800582 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800583}
584
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800585int Camera3Device::mapToFrameworkFormat(
586 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
587 return static_cast<uint32_t>(pixelFormat);
588}
589
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700590android_dataspace Camera3Device::mapToFrameworkDataspace(
591 DataspaceFlags dataSpace) {
592 return static_cast<android_dataspace>(dataSpace);
593}
594
Emilian Peev050f5dc2017-05-18 14:43:56 +0100595uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700596 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700597 return usage;
598}
599
Emilian Peev050f5dc2017-05-18 14:43:56 +0100600uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700601 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700602 return usage;
603}
604
Zhijun Hef7da0962014-04-24 13:27:56 -0700605ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700606 // Get max jpeg size (area-wise).
607 Size maxJpegResolution = getMaxJpegResolution();
608 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800609 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
610 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700611 return BAD_VALUE;
612 }
613
Zhijun Hef7da0962014-04-24 13:27:56 -0700614 // Get max jpeg buffer size
615 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700616 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
617 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800618 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
619 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700620 return BAD_VALUE;
621 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700622 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800623 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700624
625 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700626 float scaleFactor = ((float) (width * height)) /
627 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800628 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
629 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700630 if (jpegBufferSize > maxJpegBufferSize) {
631 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700632 }
633
634 return jpegBufferSize;
635}
636
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700637ssize_t Camera3Device::getPointCloudBufferSize() const {
638 const int FLOATS_PER_POINT=4;
639 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
640 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800641 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
642 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700643 return BAD_VALUE;
644 }
645 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
646 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
647 return maxBytesForPointCloud;
648}
649
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800650ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800651 const int PER_CONFIGURATION_SIZE = 3;
652 const int WIDTH_OFFSET = 0;
653 const int HEIGHT_OFFSET = 1;
654 const int SIZE_OFFSET = 2;
655 camera_metadata_ro_entry rawOpaqueSizes =
656 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800657 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800658 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800659 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
660 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800661 return BAD_VALUE;
662 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700663
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800664 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
665 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
666 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
667 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
668 }
669 }
670
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800671 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
672 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800673 return BAD_VALUE;
674}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700675
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800676status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
677 ATRACE_CALL();
678 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700679
680 // Try to lock, but continue in case of failure (to avoid blocking in
681 // deadlocks)
682 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
683 bool gotLock = tryLockSpinRightRound(mLock);
684
685 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800686 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
687 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700688 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800689 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
690 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700691
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800692 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700693
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800694 String16 templatesOption("-t");
695 int n = args.size();
696 for (int i = 0; i < n; i++) {
697 if (args[i] == templatesOption) {
698 dumpTemplates = true;
699 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000700 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700701 if (i + 1 < n) {
702 String8 monitorTags = String8(args[i + 1]);
703 if (monitorTags == "off") {
704 mTagMonitor.disableMonitoring();
705 } else {
706 mTagMonitor.parseTagsToMonitor(monitorTags);
707 }
708 } else {
709 mTagMonitor.disableMonitoring();
710 }
711 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800712 }
713
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800714 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800715
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800716 const char *status =
717 mStatus == STATUS_ERROR ? "ERROR" :
718 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700719 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
720 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800721 mStatus == STATUS_ACTIVE ? "ACTIVE" :
722 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700723
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800724 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700725 if (mStatus == STATUS_ERROR) {
726 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
727 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800728 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800729 const char *mode =
730 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
731 mOperatingMode == static_cast<int>(
732 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
733 "CUSTOM";
734 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800735
736 if (mInputStream != NULL) {
737 write(fd, lines.string(), lines.size());
738 mInputStream->dump(fd, args);
739 } else {
740 lines.appendFormat(" No input stream.\n");
741 write(fd, lines.string(), lines.size());
742 }
743 for (size_t i = 0; i < mOutputStreams.size(); i++) {
744 mOutputStreams[i]->dump(fd,args);
745 }
746
Zhijun He431503c2016-03-07 17:30:16 -0800747 if (mBufferManager != NULL) {
748 lines = String8(" Camera3 Buffer Manager:\n");
749 write(fd, lines.string(), lines.size());
750 mBufferManager->dump(fd, args);
751 }
Zhijun He125684a2015-12-26 15:07:30 -0800752
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700753 lines = String8(" In-flight requests:\n");
754 if (mInFlightMap.size() == 0) {
755 lines.append(" None\n");
756 } else {
757 for (size_t i = 0; i < mInFlightMap.size(); i++) {
758 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700759 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700760 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800761 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700762 r.numBuffersLeft);
763 }
764 }
765 write(fd, lines.string(), lines.size());
766
Shuzhen Wang686f6442017-06-20 16:16:04 -0700767 if (mRequestThread != NULL) {
768 mRequestThread->dumpCaptureRequestLatency(fd,
769 " ProcessCaptureRequest latency histogram:");
770 }
771
Igor Murashkin1e479c02013-09-06 16:55:14 -0700772 {
773 lines = String8(" Last request sent:\n");
774 write(fd, lines.string(), lines.size());
775
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700776 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700777 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
778 }
779
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800780 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800781 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800782 "TEMPLATE_PREVIEW",
783 "TEMPLATE_STILL_CAPTURE",
784 "TEMPLATE_VIDEO_RECORD",
785 "TEMPLATE_VIDEO_SNAPSHOT",
786 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800787 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800788 };
789
790 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800791 camera_metadata_t *templateRequest = nullptr;
792 mInterface->constructDefaultRequestSettings(
793 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800794 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800795 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800796 lines.append(" Not supported\n");
797 write(fd, lines.string(), lines.size());
798 } else {
799 write(fd, lines.string(), lines.size());
800 dump_indented_camera_metadata(templateRequest,
801 fd, /*verbosity*/2, /*indentation*/8);
802 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800803 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800804 }
805 }
806
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700807 mTagMonitor.dumpMonitoredMetadata(fd);
808
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800809 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800810 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800811 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800812 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800813 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800814
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700815 if (gotLock) mLock.unlock();
816 if (gotInterfaceLock) mInterfaceLock.unlock();
817
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800818 return OK;
819}
820
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800821const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800822 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800823 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
824 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700825 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800826 mStatus == STATUS_ERROR ?
827 "when in error state" : "before init");
828 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700829 if (physicalId.isEmpty()) {
830 return mDeviceInfo;
831 } else {
832 std::string id(physicalId.c_str());
833 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
834 return mPhysicalDeviceInfoMap.at(id);
835 } else {
836 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
837 return mDeviceInfo;
838 }
839 }
840}
841
842const CameraMetadata& Camera3Device::info() const {
843 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800844 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800845}
846
Jianing Wei90e59c92014-03-12 18:29:36 -0700847status_t Camera3Device::checkStatusOkToCaptureLocked() {
848 switch (mStatus) {
849 case STATUS_ERROR:
850 CLOGE("Device has encountered a serious error");
851 return INVALID_OPERATION;
852 case STATUS_UNINITIALIZED:
853 CLOGE("Device not initialized");
854 return INVALID_OPERATION;
855 case STATUS_UNCONFIGURED:
856 case STATUS_CONFIGURED:
857 case STATUS_ACTIVE:
858 // OK
859 break;
860 default:
861 SET_ERR_L("Unexpected status: %d", mStatus);
862 return INVALID_OPERATION;
863 }
864 return OK;
865}
866
867status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000868 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700869 const std::list<const SurfaceMap> &surfaceMaps,
870 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700871 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700872 if (requestList == NULL) {
873 CLOGE("requestList cannot be NULL.");
874 return BAD_VALUE;
875 }
876
Jianing Weicb0652e2014-03-12 18:29:36 -0700877 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000878 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700879 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
880 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
881 ++metadataIt, ++surfaceMapIt) {
882 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700883 if (newRequest == 0) {
884 CLOGE("Can't create capture request");
885 return BAD_VALUE;
886 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700887
Shuzhen Wang9d066012016-09-30 11:30:20 -0700888 newRequest->mRepeating = repeating;
889
Jianing Weicb0652e2014-03-12 18:29:36 -0700890 // Setup burst Id and request Id
891 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800892 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
893 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700894 CLOGE("RequestID does not exist in metadata");
895 return BAD_VALUE;
896 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800897 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700898
Jianing Wei90e59c92014-03-12 18:29:36 -0700899 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700900
901 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700902 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700903 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
904 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
905 return BAD_VALUE;
906 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700907
908 // Setup batch size if this is a high speed video recording request.
909 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
910 auto firstRequest = requestList->begin();
911 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
912 if (outputStream->isVideoStream()) {
913 (*firstRequest)->mBatchSize = requestList->size();
914 break;
915 }
916 }
917 }
918
Jianing Wei90e59c92014-03-12 18:29:36 -0700919 return OK;
920}
921
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800922status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800923 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800924
Emilian Peevaebbe412018-01-15 13:53:24 +0000925 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700926 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000927 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700928
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800929 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700930}
931
Emilian Peevaebbe412018-01-15 13:53:24 +0000932void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700933 std::list<const SurfaceMap>& surfaceMaps,
934 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000935 PhysicalCameraSettingsList requestList;
936 requestList.push_back({std::string(getId().string()), request});
937 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700938
939 SurfaceMap surfaceMap;
940 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
941 // With no surface list passed in, stream and surface will have 1-to-1
942 // mapping. So the surface index is 0 for each stream in the surfaceMap.
943 for (size_t i = 0; i < streams.count; i++) {
944 surfaceMap[streams.data.i32[i]].push_back(0);
945 }
946 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800947}
948
Jianing Wei90e59c92014-03-12 18:29:36 -0700949status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000950 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700951 const std::list<const SurfaceMap> &surfaceMaps,
952 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700953 /*out*/
954 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700955 ATRACE_CALL();
956 Mutex::Autolock il(mInterfaceLock);
957 Mutex::Autolock l(mLock);
958
959 status_t res = checkStatusOkToCaptureLocked();
960 if (res != OK) {
961 // error logged by previous call
962 return res;
963 }
964
965 RequestList requestList;
966
Shuzhen Wang0129d522016-10-30 22:43:41 -0700967 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
968 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700969 if (res != OK) {
970 // error logged by previous call
971 return res;
972 }
973
974 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700975 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700976 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700977 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700978 }
979
980 if (res == OK) {
981 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
982 if (res != OK) {
983 SET_ERR_L("Can't transition to active in %f seconds!",
984 kActiveTimeout/1e9);
985 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800986 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700987 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700988 } else {
989 CLOGE("Cannot queue request. Impossible.");
990 return BAD_VALUE;
991 }
992
993 return res;
994}
995
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700996hardware::Return<void> Camera3Device::requestStreamBuffers(
997 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
998 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -0800999 RequestBufferStates states {
1000 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams,
1001 *this, *mInterface, *this};
1002 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001003 return hardware::Void();
1004}
1005
1006hardware::Return<void> Camera3Device::returnStreamBuffers(
1007 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001008 ReturnBufferStates states {
1009 mId, mUseHalBufManager, mOutputStreams, *mInterface};
1010 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001011 return hardware::Void();
1012}
1013
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001014hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001015 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001016 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001017 // Ideally we should grab mLock, but that can lead to deadlock, and
1018 // it's not super important to get up to date value of mStatus for this
1019 // warning print, hence skipping the lock here
1020 if (mStatus == STATUS_ERROR) {
1021 // Per API contract, HAL should act as closed after device error
1022 // But mStatus can be set to error by framework as well, so just log
1023 // a warning here.
1024 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001025 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001026
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001027 sp<NotificationListener> listener;
1028 {
1029 std::lock_guard<std::mutex> l(mOutputLock);
1030 listener = mListener.promote();
1031 }
1032
Yifan Honga640c5a2017-04-12 16:30:31 -07001033 if (mProcessCaptureResultLock.tryLock() != OK) {
1034 // This should never happen; it indicates a wrong client implementation
1035 // that doesn't follow the contract. But, we can be tolerant here.
1036 ALOGE("%s: callback overlapped! waiting 1s...",
1037 __FUNCTION__);
1038 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1039 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1040 __FUNCTION__);
1041 // really don't know what to do, so bail out.
1042 return hardware::Void();
1043 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001044 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001045 CaptureOutputStates states {
1046 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001047 mInFlightLock, mLastCompletedRegularFrameNumber,
1048 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1049 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001050 mNextShutterFrameNumber,
1051 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1052 mNextResultFrameNumber,
1053 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1054 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1055 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001056 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1057 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001058 };
1059
Yifan Honga640c5a2017-04-12 16:30:31 -07001060 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001061 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001062 }
1063 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001064 return hardware::Void();
1065}
1066
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001067// Only one processCaptureResult should be called at a time, so
1068// the locks won't block. The locks are present here simply to enforce this.
1069hardware::Return<void> Camera3Device::processCaptureResult(
1070 const hardware::hidl_vec<
1071 hardware::camera::device::V3_2::CaptureResult>& results) {
1072 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1073
1074 // Ideally we should grab mLock, but that can lead to deadlock, and
1075 // it's not super important to get up to date value of mStatus for this
1076 // warning print, hence skipping the lock here
1077 if (mStatus == STATUS_ERROR) {
1078 // Per API contract, HAL should act as closed after device error
1079 // But mStatus can be set to error by framework as well, so just log
1080 // a warning here.
1081 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1082 }
1083
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001084 sp<NotificationListener> listener;
1085 {
1086 std::lock_guard<std::mutex> l(mOutputLock);
1087 listener = mListener.promote();
1088 }
1089
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001090 if (mProcessCaptureResultLock.tryLock() != OK) {
1091 // This should never happen; it indicates a wrong client implementation
1092 // that doesn't follow the contract. But, we can be tolerant here.
1093 ALOGE("%s: callback overlapped! waiting 1s...",
1094 __FUNCTION__);
1095 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1096 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1097 __FUNCTION__);
1098 // really don't know what to do, so bail out.
1099 return hardware::Void();
1100 }
1101 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001102
1103 CaptureOutputStates states {
1104 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001105 mInFlightLock, mLastCompletedRegularFrameNumber,
1106 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1107 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001108 mNextShutterFrameNumber,
1109 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1110 mNextResultFrameNumber,
1111 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1112 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1113 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001114 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1115 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001116 };
1117
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001118 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001119 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001120 }
1121 mProcessCaptureResultLock.unlock();
1122 return hardware::Void();
1123}
1124
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001125hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001126 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001127 // Ideally we should grab mLock, but that can lead to deadlock, and
1128 // it's not super important to get up to date value of mStatus for this
1129 // warning print, hence skipping the lock here
1130 if (mStatus == STATUS_ERROR) {
1131 // Per API contract, HAL should act as closed after device error
1132 // But mStatus can be set to error by framework as well, so just log
1133 // a warning here.
1134 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001135 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001136
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001137 sp<NotificationListener> listener;
1138 {
1139 std::lock_guard<std::mutex> l(mOutputLock);
1140 listener = mListener.promote();
1141 }
1142
1143 CaptureOutputStates states {
1144 mId,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07001145 mInFlightLock, mLastCompletedRegularFrameNumber,
1146 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
1147 mInFlightMap, mOutputLock, mResultQueue, mResultSignal,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001148 mNextShutterFrameNumber,
1149 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1150 mNextResultFrameNumber,
1151 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1152 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1153 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001154 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1155 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001156 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001157 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001158 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001159 }
1160 return hardware::Void();
1161}
1162
Emilian Peevaebbe412018-01-15 13:53:24 +00001163status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001164 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001165 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001166 ATRACE_CALL();
1167
Emilian Peevaebbe412018-01-15 13:53:24 +00001168 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001169}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001170
Jianing Weicb0652e2014-03-12 18:29:36 -07001171status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1172 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001173 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001174
Emilian Peevaebbe412018-01-15 13:53:24 +00001175 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001176 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001177 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001178
Emilian Peevaebbe412018-01-15 13:53:24 +00001179 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001180 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001181}
1182
Emilian Peevaebbe412018-01-15 13:53:24 +00001183status_t Camera3Device::setStreamingRequestList(
1184 const List<const PhysicalCameraSettingsList> &requestsList,
1185 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001186 ATRACE_CALL();
1187
Emilian Peevaebbe412018-01-15 13:53:24 +00001188 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001189}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001190
1191sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001192 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001193 status_t res;
1194
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001195 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001196 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1197 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001198 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1199 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001200 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001201 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001202 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001203 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001204 } else if (mStatus == STATUS_UNCONFIGURED) {
1205 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001206 CLOGE("No streams configured");
1207 return NULL;
1208 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001209 }
1210
Shuzhen Wang0129d522016-10-30 22:43:41 -07001211 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001212 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001213}
1214
Jianing Weicb0652e2014-03-12 18:29:36 -07001215status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001216 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001217 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001218 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001219
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001220 switch (mStatus) {
1221 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001222 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001223 return INVALID_OPERATION;
1224 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001225 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001227 case STATUS_UNCONFIGURED:
1228 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229 case STATUS_ACTIVE:
1230 // OK
1231 break;
1232 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001233 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001234 return INVALID_OPERATION;
1235 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001236 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001237
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001238 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001239}
1240
1241status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1242 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001243 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001244
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001245 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001246}
1247
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001248status_t Camera3Device::createInputStream(
1249 uint32_t width, uint32_t height, int format, int *id) {
1250 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001251 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001252 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001253 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001254 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1255 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001256
1257 status_t res;
1258 bool wasActive = false;
1259
1260 switch (mStatus) {
1261 case STATUS_ERROR:
1262 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1263 return INVALID_OPERATION;
1264 case STATUS_UNINITIALIZED:
1265 ALOGE("%s: Device not initialized", __FUNCTION__);
1266 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001267 case STATUS_UNCONFIGURED:
1268 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001269 // OK
1270 break;
1271 case STATUS_ACTIVE:
1272 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001273 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001274 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001275 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001276 return res;
1277 }
1278 wasActive = true;
1279 break;
1280 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001281 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001282 return INVALID_OPERATION;
1283 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001284 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001285
1286 if (mInputStream != 0) {
1287 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1288 return INVALID_OPERATION;
1289 }
1290
1291 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1292 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001293 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001294
1295 mInputStream = newStream;
1296
1297 *id = mNextStreamId++;
1298
1299 // Continue captures if active at start
1300 if (wasActive) {
1301 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001302 // Reuse current operating mode and session parameters for new stream config
1303 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001304 if (res != OK) {
1305 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1306 __FUNCTION__, mNextStreamId, strerror(-res), res);
1307 return res;
1308 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001309 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001310 }
1311
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001312 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001313 return OK;
1314}
1315
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001316status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001317 uint32_t width, uint32_t height, int format,
1318 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001319 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001320 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001321 ATRACE_CALL();
1322
1323 if (consumer == nullptr) {
1324 ALOGE("%s: consumer must not be null", __FUNCTION__);
1325 return BAD_VALUE;
1326 }
1327
1328 std::vector<sp<Surface>> consumers;
1329 consumers.push_back(consumer);
1330
1331 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001332 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1333 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001334}
1335
1336status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1337 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1338 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001339 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001340 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001341 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001342
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001343 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001344 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001345 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001346 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001347 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1348 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1349 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001350
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001351 status_t res;
1352 bool wasActive = false;
1353
1354 switch (mStatus) {
1355 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001356 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001357 return INVALID_OPERATION;
1358 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001359 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001360 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001361 case STATUS_UNCONFIGURED:
1362 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001363 // OK
1364 break;
1365 case STATUS_ACTIVE:
1366 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001367 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001368 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001369 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001370 return res;
1371 }
1372 wasActive = true;
1373 break;
1374 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001375 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001376 return INVALID_OPERATION;
1377 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001378 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001379
1380 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001381
Shuzhen Wang0129d522016-10-30 22:43:41 -07001382 if (consumers.size() == 0 && !hasDeferredConsumer) {
1383 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1384 return BAD_VALUE;
1385 }
Zhijun He5d677d12016-05-29 16:52:39 -07001386
Shuzhen Wang0129d522016-10-30 22:43:41 -07001387 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001388 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1389 return BAD_VALUE;
1390 }
1391
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001392 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001393 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001394 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001395 blobBufferSize = getPointCloudBufferSize();
1396 if (blobBufferSize <= 0) {
1397 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1398 return BAD_VALUE;
1399 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001400 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1401 blobBufferSize = width * height;
1402 } else {
1403 blobBufferSize = getJpegBufferSize(width, height);
1404 if (blobBufferSize <= 0) {
1405 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1406 return BAD_VALUE;
1407 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001408 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001409 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001410 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001411 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001412 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1413 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1414 if (rawOpaqueBufferSize <= 0) {
1415 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1416 return BAD_VALUE;
1417 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001418 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001419 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001420 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001421 } else if (isShared) {
1422 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1423 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001424 mTimestampOffset, physicalCameraId, streamSetId,
1425 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001426 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001427 newStream = new Camera3OutputStream(mNextStreamId,
1428 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001429 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001431 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001432 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001433 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001434 }
Emilian Peev40ead602017-09-26 15:46:36 +01001435
1436 size_t consumerCount = consumers.size();
1437 for (size_t i = 0; i < consumerCount; i++) {
1438 int id = newStream->getSurfaceId(consumers[i]);
1439 if (id < 0) {
1440 SET_ERR_L("Invalid surface id");
1441 return BAD_VALUE;
1442 }
1443 if (surfaceIds != nullptr) {
1444 surfaceIds->push_back(id);
1445 }
1446 }
1447
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001448 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001449
Emilian Peev08dd2452017-04-06 16:55:14 +01001450 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001451
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001452 res = mOutputStreams.add(mNextStreamId, newStream);
1453 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001454 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001455 return res;
1456 }
1457
1458 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001459 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001460
1461 // Continue captures if active at start
1462 if (wasActive) {
1463 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001464 // Reuse current operating mode and session parameters for new stream config
1465 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001467 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1468 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001469 return res;
1470 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001471 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001472 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001473 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001475}
1476
Emilian Peev710c1422017-08-30 11:19:38 +01001477status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001478 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001479 if (nullptr == streamInfo) {
1480 return BAD_VALUE;
1481 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001482 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001483 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001484
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 switch (mStatus) {
1486 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001487 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001488 return INVALID_OPERATION;
1489 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001490 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001491 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001492 case STATUS_UNCONFIGURED:
1493 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 case STATUS_ACTIVE:
1495 // OK
1496 break;
1497 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001498 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001499 return INVALID_OPERATION;
1500 }
1501
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001502 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1503 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001504 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001505 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506 }
1507
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001508 streamInfo->width = stream->getWidth();
1509 streamInfo->height = stream->getHeight();
1510 streamInfo->format = stream->getFormat();
1511 streamInfo->dataSpace = stream->getDataSpace();
1512 streamInfo->formatOverridden = stream->isFormatOverridden();
1513 streamInfo->originalFormat = stream->getOriginalFormat();
1514 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1515 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001516 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001517}
1518
1519status_t Camera3Device::setStreamTransform(int id,
1520 int transform) {
1521 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001522 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001524
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001525 switch (mStatus) {
1526 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001527 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 return INVALID_OPERATION;
1529 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001530 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001531 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001532 case STATUS_UNCONFIGURED:
1533 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 case STATUS_ACTIVE:
1535 // OK
1536 break;
1537 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001538 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 return INVALID_OPERATION;
1540 }
1541
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001542 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1543 if (stream == nullptr) {
1544 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 return BAD_VALUE;
1546 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001547 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001548}
1549
1550status_t Camera3Device::deleteStream(int id) {
1551 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 Mutex::Autolock l(mLock);
1554 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001555
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001556 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001557
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 // CameraDevice semantics require device to already be idle before
1559 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001560 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001561 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001562 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001563 }
1564
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001565 if (mStatus == STATUS_ERROR) {
1566 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1567 __FUNCTION__, mId.string());
1568 return -EBUSY;
1569 }
1570
Igor Murashkin2fba5842013-04-22 14:03:54 -07001571 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001572 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001573 if (mInputStream != NULL && id == mInputStream->getId()) {
1574 deletedStream = mInputStream;
1575 mInputStream.clear();
1576 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001577 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001578 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579 return BAD_VALUE;
1580 }
Zhijun He5f446352014-01-22 09:49:33 -08001581 }
1582
1583 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001584 if (stream != nullptr) {
1585 deletedStream = stream;
1586 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001587 }
1588
1589 // Free up the stream endpoint so that it can be used by some other stream
1590 res = deletedStream->disconnect();
1591 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001592 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593 // fall through since we want to still list the stream as deleted.
1594 }
1595 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001596 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001597
1598 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001599}
1600
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001601status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001602 ATRACE_CALL();
1603 ALOGV("%s: E", __FUNCTION__);
1604
1605 Mutex::Autolock il(mInterfaceLock);
1606 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001607
Emilian Peev811d2952018-05-25 11:08:40 +01001608 // In case the client doesn't include any session parameter, try a
1609 // speculative configuration using the values from the last cached
1610 // default request.
1611 if (sessionParams.isEmpty() &&
1612 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1613 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1614 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1615 mLastTemplateId);
1616 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1617 operatingMode);
1618 }
1619
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001620 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1621}
1622
1623status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1624 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001625 //Filter out any incoming session parameters
1626 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001627 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1628 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001629 CameraMetadata filteredParams(availableSessionKeys.count);
1630 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1631 filteredParams.getAndLock());
1632 set_camera_metadata_vendor_id(meta, mVendorTagId);
1633 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001634 if (availableSessionKeys.count > 0) {
1635 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1636 camera_metadata_ro_entry entry = params.find(
1637 availableSessionKeys.data.i32[i]);
1638 if (entry.count > 0) {
1639 filteredParams.update(entry);
1640 }
1641 }
1642 }
1643
1644 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001645}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001646
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001647status_t Camera3Device::getInputBufferProducer(
1648 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001649 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001650 Mutex::Autolock il(mInterfaceLock);
1651 Mutex::Autolock l(mLock);
1652
1653 if (producer == NULL) {
1654 return BAD_VALUE;
1655 } else if (mInputStream == NULL) {
1656 return INVALID_OPERATION;
1657 }
1658
1659 return mInputStream->getInputBufferProducer(producer);
1660}
1661
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001662status_t Camera3Device::createDefaultRequest(int templateId,
1663 CameraMetadata *request) {
1664 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001665 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001666
1667 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1668 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001669 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001670 return BAD_VALUE;
1671 }
1672
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001673 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001674
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001675 {
1676 Mutex::Autolock l(mLock);
1677 switch (mStatus) {
1678 case STATUS_ERROR:
1679 CLOGE("Device has encountered a serious error");
1680 return INVALID_OPERATION;
1681 case STATUS_UNINITIALIZED:
1682 CLOGE("Device is not initialized!");
1683 return INVALID_OPERATION;
1684 case STATUS_UNCONFIGURED:
1685 case STATUS_CONFIGURED:
1686 case STATUS_ACTIVE:
1687 // OK
1688 break;
1689 default:
1690 SET_ERR_L("Unexpected status: %d", mStatus);
1691 return INVALID_OPERATION;
1692 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001693
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001694 if (!mRequestTemplateCache[templateId].isEmpty()) {
1695 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001696 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001697 return OK;
1698 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001699 }
1700
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001701 camera_metadata_t *rawRequest;
1702 status_t res = mInterface->constructDefaultRequestSettings(
1703 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001704
1705 {
1706 Mutex::Autolock l(mLock);
1707 if (res == BAD_VALUE) {
1708 ALOGI("%s: template %d is not supported on this camera device",
1709 __FUNCTION__, templateId);
1710 return res;
1711 } else if (res != OK) {
1712 CLOGE("Unable to construct request template %d: %s (%d)",
1713 templateId, strerror(-res), res);
1714 return res;
1715 }
1716
1717 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1718 mRequestTemplateCache[templateId].acquire(rawRequest);
1719
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001720 // Override the template request with zoomRatioMapper
1721 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1722 &mRequestTemplateCache[templateId]);
1723 if (res != OK) {
1724 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1725 templateId, strerror(-res), res);
1726 return res;
1727 }
1728
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001729 // Fill in JPEG_QUALITY if not available
1730 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1731 static const uint8_t kDefaultJpegQuality = 95;
1732 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1733 &kDefaultJpegQuality, 1);
1734 }
1735
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001736 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001737 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001738 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001739 return OK;
1740}
1741
1742status_t Camera3Device::waitUntilDrained() {
1743 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001744 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001745 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001746 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001747
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001748 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001749}
1750
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001751status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001752 switch (mStatus) {
1753 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001754 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001755 ALOGV("%s: Already idle", __FUNCTION__);
1756 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001757 case STATUS_CONFIGURED:
1758 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001759 case STATUS_ERROR:
1760 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001761 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001762 break;
1763 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001764 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001765 return INVALID_OPERATION;
1766 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001767 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1768 maxExpectedDuration);
1769 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001770 if (res != OK) {
1771 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1772 res);
1773 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001774 return res;
1775}
1776
Ruben Brunk183f0562015-08-12 12:55:02 -07001777
1778void Camera3Device::internalUpdateStatusLocked(Status status) {
1779 mStatus = status;
1780 mRecentStatusUpdates.add(mStatus);
1781 mStatusChanged.broadcast();
1782}
1783
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001784// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001785status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001786 if (mRequestThread.get() != nullptr) {
1787 mRequestThread->setPaused(true);
1788 } else {
1789 return NO_INIT;
1790 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001791
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001792 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1793 maxExpectedDuration);
1794 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001795 if (res != OK) {
1796 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001797 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001798 }
1799
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001800 return res;
1801}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001802
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001803// Resume after internalPauseAndWaitLocked
1804status_t Camera3Device::internalResumeLocked() {
1805 status_t res;
1806
1807 mRequestThread->setPaused(false);
1808
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001809 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1810 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001811 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1812 if (res != OK) {
1813 SET_ERR_L("Can't transition to active in %f seconds!",
1814 kActiveTimeout/1e9);
1815 }
1816 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001817 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001818}
1819
Ruben Brunk183f0562015-08-12 12:55:02 -07001820status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001821 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001822
1823 size_t startIndex = 0;
1824 if (mStatusWaiters == 0) {
1825 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1826 // this status list
1827 mRecentStatusUpdates.clear();
1828 } else {
1829 // If other threads are waiting on updates to this status list, set the position of the
1830 // first element that this list will check rather than clearing the list.
1831 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001832 }
1833
Ruben Brunk183f0562015-08-12 12:55:02 -07001834 mStatusWaiters++;
1835
Yin-Chia Yehfe70f2d2020-07-28 00:17:58 -07001836 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001837 if (!active && mUseHalBufManager) {
1838 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001839 if (mStatus == STATUS_ACTIVE) {
1840 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehfe70f2d2020-07-28 00:17:58 -07001841 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001842 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001843 mRequestBufferSM.onWaitUntilIdle();
1844 }
1845
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001846 bool stateSeen = false;
1847 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001848 if (active == (mStatus == STATUS_ACTIVE)) {
1849 // Desired state is current
1850 break;
1851 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001852
1853 res = mStatusChanged.waitRelative(mLock, timeout);
1854 if (res != OK) break;
1855
Ruben Brunk183f0562015-08-12 12:55:02 -07001856 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1857 // transitions.
1858 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1859 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1860 __FUNCTION__);
1861
1862 // Encountered desired state since we began waiting
1863 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001864 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1865 stateSeen = true;
1866 break;
1867 }
1868 }
1869 } while (!stateSeen);
1870
Yin-Chia Yehfe70f2d2020-07-28 00:17:58 -07001871 if (signalPipelineDrain) {
1872 mRequestThread->resetPipelineDrain();
1873 }
1874
Ruben Brunk183f0562015-08-12 12:55:02 -07001875 mStatusWaiters--;
1876
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001877 return res;
1878}
1879
1880
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001881status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001882 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001883 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001884
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001885 if (listener != NULL && mListener != NULL) {
1886 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1887 }
1888 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001889 mRequestThread->setNotificationListener(listener);
1890 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001891
1892 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001893}
1894
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001895bool Camera3Device::willNotify3A() {
1896 return false;
1897}
1898
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001899status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001900 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001901 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001902
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001903 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001904 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1905 if (st == std::cv_status::timeout) {
1906 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001907 }
1908 }
1909 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001910}
1911
Jianing Weicb0652e2014-03-12 18:29:36 -07001912status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001913 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001914 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001915
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001916 if (mResultQueue.empty()) {
1917 return NOT_ENOUGH_DATA;
1918 }
1919
Jianing Weicb0652e2014-03-12 18:29:36 -07001920 if (frame == NULL) {
1921 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1922 return BAD_VALUE;
1923 }
1924
1925 CaptureResult &result = *(mResultQueue.begin());
1926 frame->mResultExtras = result.mResultExtras;
1927 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001928 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001929 mResultQueue.erase(mResultQueue.begin());
1930
1931 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001932}
1933
1934status_t Camera3Device::triggerAutofocus(uint32_t id) {
1935 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001936 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001937
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001938 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1939 // Mix-in this trigger into the next request and only the next request.
1940 RequestTrigger trigger[] = {
1941 {
1942 ANDROID_CONTROL_AF_TRIGGER,
1943 ANDROID_CONTROL_AF_TRIGGER_START
1944 },
1945 {
1946 ANDROID_CONTROL_AF_TRIGGER_ID,
1947 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001948 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001949 };
1950
1951 return mRequestThread->queueTrigger(trigger,
1952 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001953}
1954
1955status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1956 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001957 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001958
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001959 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1960 // Mix-in this trigger into the next request and only the next request.
1961 RequestTrigger trigger[] = {
1962 {
1963 ANDROID_CONTROL_AF_TRIGGER,
1964 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1965 },
1966 {
1967 ANDROID_CONTROL_AF_TRIGGER_ID,
1968 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001969 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001970 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001971
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001972 return mRequestThread->queueTrigger(trigger,
1973 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001974}
1975
1976status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1977 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001978 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001979
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001980 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1981 // Mix-in this trigger into the next request and only the next request.
1982 RequestTrigger trigger[] = {
1983 {
1984 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1985 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1986 },
1987 {
1988 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1989 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001990 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001991 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001992
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001993 return mRequestThread->queueTrigger(trigger,
1994 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001995}
1996
Jianing Weicb0652e2014-03-12 18:29:36 -07001997status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001998 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001999 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002000 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002001
Zhijun He7ef20392014-04-21 16:04:17 -07002002 {
2003 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002004
2005 // b/116514106 "disconnect()" can get called twice for the same device. The
2006 // camera device will not be initialized during the second run.
2007 if (mStatus == STATUS_UNINITIALIZED) {
2008 return OK;
2009 }
2010
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002011 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002012 }
2013
Emilian Peev08dd2452017-04-06 16:55:14 +01002014 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002015}
2016
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002017status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002018 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2019}
2020
2021status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002022 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002023 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002024 Mutex::Autolock il(mInterfaceLock);
2025 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002026
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002027 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2028 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002029 CLOGE("Stream %d does not exist", streamId);
2030 return BAD_VALUE;
2031 }
2032
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002033 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002034 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002035 return BAD_VALUE;
2036 }
2037
2038 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002039 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002040 return BAD_VALUE;
2041 }
2042
Ruben Brunkc78ac262015-08-13 17:58:46 -07002043 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002044}
2045
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002046status_t Camera3Device::tearDown(int streamId) {
2047 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002048 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002049 Mutex::Autolock il(mInterfaceLock);
2050 Mutex::Autolock l(mLock);
2051
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002052 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2053 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002054 CLOGE("Stream %d does not exist", streamId);
2055 return BAD_VALUE;
2056 }
2057
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002058 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2059 CLOGE("Stream %d is a target of a in-progress request", streamId);
2060 return BAD_VALUE;
2061 }
2062
2063 return stream->tearDown();
2064}
2065
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002066status_t Camera3Device::addBufferListenerForStream(int streamId,
2067 wp<Camera3StreamBufferListener> listener) {
2068 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002069 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002070 Mutex::Autolock il(mInterfaceLock);
2071 Mutex::Autolock l(mLock);
2072
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002073 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2074 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002075 CLOGE("Stream %d does not exist", streamId);
2076 return BAD_VALUE;
2077 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002078 stream->addBufferListener(listener);
2079
2080 return OK;
2081}
2082
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002083/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002084 * Methods called by subclasses
2085 */
2086
2087void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002088 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002089 {
2090 // Need mLock to safely update state and synchronize to current
2091 // state of methods in flight.
2092 Mutex::Autolock l(mLock);
2093 // We can get various system-idle notices from the status tracker
2094 // while starting up. Only care about them if we've actually sent
2095 // in some requests recently.
2096 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2097 return;
2098 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002099 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2100 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002101 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002102
2103 // Skip notifying listener if we're doing some user-transparent
2104 // state changes
2105 if (mPauseStateNotify) return;
2106 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002107
2108 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002109 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002110 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002111 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002112 }
2113 if (idle && listener != NULL) {
2114 listener->notifyIdle();
2115 }
2116}
2117
Shuzhen Wang758c2152017-01-10 18:26:18 -08002118status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002119 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002120 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002121 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2122 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002123
2124 if (surfaceIds == nullptr) {
2125 return BAD_VALUE;
2126 }
2127
Zhijun He5d677d12016-05-29 16:52:39 -07002128 Mutex::Autolock il(mInterfaceLock);
2129 Mutex::Autolock l(mLock);
2130
Shuzhen Wang758c2152017-01-10 18:26:18 -08002131 if (consumers.size() == 0) {
2132 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002133 return BAD_VALUE;
2134 }
2135
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002136 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2137 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002138 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002139 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002140 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002141
2142 // isConsumerConfigurationDeferred will be off after setConsumers
2143 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002144 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002145 if (res != OK) {
2146 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2147 return res;
2148 }
2149
Emilian Peev40ead602017-09-26 15:46:36 +01002150 for (auto &consumer : consumers) {
2151 int id = stream->getSurfaceId(consumer);
2152 if (id < 0) {
2153 CLOGE("Invalid surface id!");
2154 return BAD_VALUE;
2155 }
2156 surfaceIds->push_back(id);
2157 }
2158
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002159 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002160 if (!stream->isConfiguring()) {
2161 CLOGE("Stream %d was already fully configured.", streamId);
2162 return INVALID_OPERATION;
2163 }
Zhijun He5d677d12016-05-29 16:52:39 -07002164
Shuzhen Wang0129d522016-10-30 22:43:41 -07002165 res = stream->finishConfiguration();
2166 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002167 // If finishConfiguration fails due to abandoned surface, do not set
2168 // device to error state.
2169 bool isSurfaceAbandoned =
2170 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2171 if (!isSurfaceAbandoned) {
2172 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2173 stream->getId(), strerror(-res), res);
2174 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002175 return res;
2176 }
Zhijun He5d677d12016-05-29 16:52:39 -07002177 }
2178
2179 return OK;
2180}
2181
Emilian Peev40ead602017-09-26 15:46:36 +01002182status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2183 const std::vector<OutputStreamInfo> &outputInfo,
2184 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2185 Mutex::Autolock il(mInterfaceLock);
2186 Mutex::Autolock l(mLock);
2187
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002188 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2189 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002190 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002191 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002192 }
2193
2194 for (const auto &it : removedSurfaceIds) {
2195 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2196 CLOGE("Shared surface still part of a pending request!");
2197 return -EBUSY;
2198 }
2199 }
2200
Emilian Peev40ead602017-09-26 15:46:36 +01002201 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2202 if (res != OK) {
2203 CLOGE("Stream %d failed to update stream (error %d %s) ",
2204 streamId, res, strerror(-res));
2205 if (res == UNKNOWN_ERROR) {
2206 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2207 __FUNCTION__);
2208 }
2209 return res;
2210 }
2211
2212 return res;
2213}
2214
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002215status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2216 Mutex::Autolock il(mInterfaceLock);
2217 Mutex::Autolock l(mLock);
2218
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002219 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2220 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002221 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2222 return BAD_VALUE;
2223 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002224 return stream->dropBuffers(dropping);
2225}
2226
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002227/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002228 * Camera3Device private methods
2229 */
2230
2231sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002232 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002233 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002234
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002235 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002236 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002237
2238 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002239 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002240 if (inputStreams.count > 0) {
2241 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002242 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002243 CLOGE("Request references unknown input stream %d",
2244 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002245 return NULL;
2246 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002247
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002248 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002249 SET_ERR_L("%s: input stream %d is not configured!",
2250 __FUNCTION__, mInputStream->getId());
2251 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002252 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002253 // Check if stream prepare is blocking requests.
2254 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002255 CLOGE("Request references an input stream that's being prepared!");
2256 return NULL;
2257 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002258
2259 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002260 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002261 }
2262
2263 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002264 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002265 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002266 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002267 return NULL;
2268 }
2269
2270 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002271 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2272 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002273 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002274 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002275 return NULL;
2276 }
Zhijun He5d677d12016-05-29 16:52:39 -07002277 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002278 auto iter = surfaceMap.find(streams.data.i32[i]);
2279 if (iter != surfaceMap.end()) {
2280 const std::vector<size_t>& surfaces = iter->second;
2281 for (const auto& surface : surfaces) {
2282 if (stream->isConsumerConfigurationDeferred(surface)) {
2283 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2284 "due to deferred consumer", stream->getId(), surface);
2285 return NULL;
2286 }
2287 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002288 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002289 }
2290
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002291 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002292 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2293 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002294 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002295 // Check if stream prepare is blocking requests.
2296 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002297 CLOGE("Request references an output stream that's being prepared!");
2298 return NULL;
2299 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002300
2301 newRequest->mOutputStreams.push(stream);
2302 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002303 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002304 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002305
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002306 auto rotateAndCropEntry =
2307 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2308 if (rotateAndCropEntry.count > 0 &&
2309 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2310 newRequest->mRotateAndCropAuto = true;
2311 } else {
2312 newRequest->mRotateAndCropAuto = false;
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002313 }
2314
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002315 return newRequest;
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002316}
2317
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002318void Camera3Device::cancelStreamsConfigurationLocked() {
2319 int res = OK;
2320 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2321 res = mInputStream->cancelConfiguration();
2322 if (res != OK) {
2323 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2324 mInputStream->getId(), strerror(-res), res);
2325 }
2326 }
2327
2328 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002329 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002330 if (outputStream->isConfiguring()) {
2331 res = outputStream->cancelConfiguration();
2332 if (res != OK) {
2333 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2334 outputStream->getId(), strerror(-res), res);
2335 }
2336 }
2337 }
2338
2339 // Return state to that at start of call, so that future configures
2340 // properly clean things up
2341 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2342 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002343
2344 res = mPreparerThread->resume();
2345 if (res != OK) {
2346 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2347 }
2348}
2349
Emilian Peev0d0191e2020-04-21 17:01:18 -07002350bool Camera3Device::checkAbandonedStreamsLocked() {
2351 if ((mInputStream.get() != nullptr) && (mInputStream->isAbandoned())) {
2352 return true;
2353 }
2354
2355 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2356 auto stream = mOutputStreams[i];
2357 if ((stream.get() != nullptr) && (stream->isAbandoned())) {
2358 return true;
2359 }
2360 }
2361
2362 return false;
2363}
2364
Emilian Peev3bead5f2020-05-28 17:29:08 -07002365bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams, int clientStatusId) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002366 ATRACE_CALL();
2367 bool ret = false;
2368
Jayant Chowdharydfc46592020-01-30 13:09:59 -08002369 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002370 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2371
2372 Mutex::Autolock l(mLock);
Emilian Peev0d0191e2020-04-21 17:01:18 -07002373 if (checkAbandonedStreamsLocked()) {
2374 ALOGW("%s: Abandoned stream detected, session parameters can't be applied correctly!",
2375 __FUNCTION__);
2376 return true;
2377 }
2378
Emilian Peev3bead5f2020-05-28 17:29:08 -07002379 status_t rc = NO_ERROR;
2380 bool markClientActive = false;
2381 if (mStatus == STATUS_ACTIVE) {
2382 markClientActive = true;
2383 mPauseStateNotify = true;
2384 mStatusTracker->markComponentIdle(clientStatusId, Fence::NO_FENCE);
2385
2386 rc = internalPauseAndWaitLocked(maxExpectedDuration);
2387 }
2388
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002389 if (rc == NO_ERROR) {
2390 mNeedConfig = true;
2391 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2392 if (rc == NO_ERROR) {
2393 ret = true;
2394 mPauseStateNotify = false;
2395 //Moving to active state while holding 'mLock' is important.
2396 //There could be pending calls to 'create-/deleteStream' which
2397 //will trigger another stream configuration while the already
2398 //present streams end up with outstanding buffers that will
2399 //not get drained.
2400 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002401 } else if (rc == DEAD_OBJECT) {
2402 // DEAD_OBJECT can be returned if either the consumer surface is
2403 // abandoned, or the HAL has died.
2404 // - If the HAL has died, configureStreamsLocked call will set
2405 // device to error state,
2406 // - If surface is abandoned, we should not set device to error
2407 // state.
2408 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002409 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002410 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002411 }
2412 } else {
2413 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2414 }
2415
Emilian Peev3bead5f2020-05-28 17:29:08 -07002416 if (markClientActive) {
2417 mStatusTracker->markComponentActive(clientStatusId);
2418 }
2419
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002420 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002421}
2422
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002423status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002424 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002425 ATRACE_CALL();
2426 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002427
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002428 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002429 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002430 return INVALID_OPERATION;
2431 }
2432
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002433 if (operatingMode < 0) {
2434 CLOGE("Invalid operating mode: %d", operatingMode);
2435 return BAD_VALUE;
2436 }
2437
2438 bool isConstrainedHighSpeed =
2439 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2440 operatingMode;
2441
2442 if (mOperatingMode != operatingMode) {
2443 mNeedConfig = true;
2444 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2445 mOperatingMode = operatingMode;
2446 }
2447
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002448 // In case called from configureStreams, abort queued input buffers not belonging to
2449 // any pending requests.
2450 if (mInputStream != NULL && notifyRequestThread) {
2451 while (true) {
2452 camera3_stream_buffer_t inputBuffer;
2453 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2454 /*respectHalLimit*/ false);
2455 if (res != OK) {
2456 // Exhausted acquiring all input buffers.
2457 break;
2458 }
2459
2460 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2461 res = mInputStream->returnInputBuffer(inputBuffer);
2462 if (res != OK) {
2463 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2464 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2465 }
2466 }
2467 }
2468
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002469 if (!mNeedConfig) {
2470 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2471 return OK;
2472 }
2473
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002474 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2475 // adding a dummy stream instead.
2476 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2477 if (mOutputStreams.size() == 0) {
2478 addDummyStreamLocked();
2479 } else {
2480 tryRemoveDummyStreamLocked();
2481 }
2482
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002483 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002484 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002485
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002486 mPreparerThread->pause();
2487
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002488 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002489 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002490 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2491
2492 Vector<camera3_stream_t*> streams;
2493 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002494 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002495
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002496
2497 if (mInputStream != NULL) {
2498 camera3_stream_t *inputStream;
2499 inputStream = mInputStream->startConfiguration();
2500 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002501 CLOGE("Can't start input stream configuration");
2502 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002503 return INVALID_OPERATION;
2504 }
2505 streams.add(inputStream);
2506 }
2507
2508 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002509
2510 // Don't configure bidi streams twice, nor add them twice to the list
2511 if (mOutputStreams[i].get() ==
2512 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2513
2514 config.num_streams--;
2515 continue;
2516 }
2517
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002518 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002519 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002520 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002521 CLOGE("Can't start output stream configuration");
2522 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002523 return INVALID_OPERATION;
2524 }
2525 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002526
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002527 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002528 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2529 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002530 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2531 bufferSizes[k] = static_cast<uint32_t>(
2532 getJpegBufferSize(outputStream->width, outputStream->height));
2533 } else if (outputStream->data_space ==
2534 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2535 bufferSizes[k] = outputStream->width * outputStream->height;
2536 } else {
2537 ALOGW("%s: Blob dataSpace %d not supported",
2538 __FUNCTION__, outputStream->data_space);
2539 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002540 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002541 }
2542
2543 config.streams = streams.editArray();
2544
2545 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002546 // max_buffers, usage, and priv fields, as well as data_space and format
2547 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002548
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002549 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002550 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002551 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002552
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002553 if (res == BAD_VALUE) {
2554 // HAL rejected this set of streams as unsupported, clean up config
2555 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002556 CLOGE("Set of requested inputs/outputs not supported by HAL");
2557 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002558 return BAD_VALUE;
2559 } else if (res != OK) {
2560 // Some other kind of error from configure_streams - this is not
2561 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002562 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2563 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002564 return res;
2565 }
2566
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002567 // Finish all stream configuration immediately.
2568 // TODO: Try to relax this later back to lazy completion, which should be
2569 // faster
2570
Igor Murashkin073f8572013-05-02 14:59:28 -07002571 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002572 bool streamReConfigured = false;
2573 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002574 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002575 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002576 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002577 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002578 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2579 return DEAD_OBJECT;
2580 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002581 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002582 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002583 if (streamReConfigured) {
2584 mInterface->onStreamReConfigured(mInputStream->getId());
2585 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002586 }
2587
2588 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002589 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002590 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002591 bool streamReConfigured = false;
2592 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002593 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002594 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002595 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002596 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002597 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2598 return DEAD_OBJECT;
2599 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002600 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002601 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002602 if (streamReConfigured) {
2603 mInterface->onStreamReConfigured(outputStream->getId());
2604 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002605 }
2606 }
2607
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002608 // Request thread needs to know to avoid using repeat-last-settings protocol
2609 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002610 if (notifyRequestThread) {
2611 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2612 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002613
Zhijun He90f7c372016-08-16 16:19:43 -07002614 char value[PROPERTY_VALUE_MAX];
2615 property_get("camera.fifo.disable", value, "0");
2616 int32_t disableFifo = atoi(value);
2617 if (disableFifo != 1) {
2618 // Boost priority of request thread to SCHED_FIFO.
2619 pid_t requestThreadTid = mRequestThread->getTid();
2620 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002621 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002622 if (res != OK) {
2623 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2624 strerror(-res), res);
2625 } else {
2626 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2627 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002628 }
2629
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002630 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002631 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2632 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2633 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2634 sessionParams.unlock(newSessionParams);
2635 mSessionParams.unlock(currentSessionParams);
2636 if (updateSessionParams) {
2637 mSessionParams = sessionParams;
2638 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002639
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002640 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002641
Ruben Brunk183f0562015-08-12 12:55:02 -07002642 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2643 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002644
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002645 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002646
Zhijun He0a210512014-07-24 13:45:15 -07002647 // tear down the deleted streams after configure streams.
2648 mDeletedStreams.clear();
2649
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002650 auto rc = mPreparerThread->resume();
2651 if (rc != OK) {
2652 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2653 return rc;
2654 }
2655
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002656 if (mDummyStreamId == NO_STREAM) {
2657 mRequestBufferSM.onStreamsConfigured();
2658 }
2659
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002660 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002661}
2662
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002663status_t Camera3Device::addDummyStreamLocked() {
2664 ATRACE_CALL();
2665 status_t res;
2666
2667 if (mDummyStreamId != NO_STREAM) {
2668 // Should never be adding a second dummy stream when one is already
2669 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002670 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2671 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002672 return INVALID_OPERATION;
2673 }
2674
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002675 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002676
2677 sp<Camera3OutputStreamInterface> dummyStream =
2678 new Camera3DummyStream(mNextStreamId);
2679
2680 res = mOutputStreams.add(mNextStreamId, dummyStream);
2681 if (res < 0) {
2682 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2683 return res;
2684 }
2685
2686 mDummyStreamId = mNextStreamId;
2687 mNextStreamId++;
2688
2689 return OK;
2690}
2691
2692status_t Camera3Device::tryRemoveDummyStreamLocked() {
2693 ATRACE_CALL();
2694 status_t res;
2695
2696 if (mDummyStreamId == NO_STREAM) return OK;
2697 if (mOutputStreams.size() == 1) return OK;
2698
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002699 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002700
2701 // Ok, have a dummy stream and there's at least one other output stream,
2702 // so remove the dummy
2703
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002704 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2705 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002706 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2707 return INVALID_OPERATION;
2708 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002709 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002710
2711 // Free up the stream endpoint so that it can be used by some other stream
2712 res = deletedStream->disconnect();
2713 if (res != OK) {
2714 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2715 // fall through since we want to still list the stream as deleted.
2716 }
2717 mDeletedStreams.add(deletedStream);
2718 mDummyStreamId = NO_STREAM;
2719
2720 return res;
2721}
2722
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002723void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002724 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002725 Mutex::Autolock l(mLock);
2726 va_list args;
2727 va_start(args, fmt);
2728
2729 setErrorStateLockedV(fmt, args);
2730
2731 va_end(args);
2732}
2733
2734void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002735 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002736 Mutex::Autolock l(mLock);
2737 setErrorStateLockedV(fmt, args);
2738}
2739
2740void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2741 va_list args;
2742 va_start(args, fmt);
2743
2744 setErrorStateLockedV(fmt, args);
2745
2746 va_end(args);
2747}
2748
2749void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002750 // Print out all error messages to log
2751 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002752 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002753
2754 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002755 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002756
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002757 mErrorCause = errorCause;
2758
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002759 if (mRequestThread != nullptr) {
2760 mRequestThread->setPaused(true);
2761 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002762 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002763
2764 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002765 sp<NotificationListener> listener = mListener.promote();
2766 if (listener != NULL) {
2767 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002768 CaptureResultExtras());
2769 }
2770
2771 // Save stack trace. View by dumping it later.
2772 CameraTraces::saveTrace();
2773 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002774}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002775
2776/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002777 * In-flight request management
2778 */
2779
Jianing Weicb0652e2014-03-12 18:29:36 -07002780status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002781 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002782 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002783 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002784 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08002785 const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002786 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002787 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002788
2789 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002790 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002791 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002792 rotateAndCropAuto, cameraIdsWithZoom, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002793 if (res < 0) return res;
2794
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002795 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002796 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2797 // avoid a deadlock during reprocess requests.
2798 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002799 if (mStatusTracker != nullptr) {
2800 mStatusTracker->markComponentActive(mInFlightStatusId);
2801 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002802 }
2803
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002804 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002805 return OK;
2806}
2807
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002808void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002809 // Indicate idle inFlightMap to the status tracker
2810 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002811 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002812 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2813 // avoid a deadlock during reprocess requests.
2814 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002815 if (mStatusTracker != nullptr) {
2816 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2817 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002818 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002819 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002820}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002821
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002822void Camera3Device::checkInflightMapLengthLocked() {
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002823 // Sanity check - if we have too many in-flight frames with long total inflight duration,
2824 // something has likely gone wrong. This might still be legit only if application send in
2825 // a long burst of long exposure requests.
2826 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2827 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2828 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2829 mInFlightMap.size(), mExpectedInflightDuration);
2830 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2831 kInFlightWarnLimitHighSpeed) {
2832 CLOGW("In-flight list too large for high speed configuration: %zu,"
2833 "total inflight duration %" PRIu64,
2834 mInFlightMap.size(), mExpectedInflightDuration);
2835 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002836 }
2837}
2838
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002839void Camera3Device::onInflightMapFlushedLocked() {
2840 mExpectedInflightDuration = 0;
2841}
2842
2843void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Jayant Chowdharyd4776262020-06-23 23:45:57 -07002844 ATRACE_HFR_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002845 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2846 mInFlightMap.removeItemsAt(idx, 1);
2847
2848 onInflightEntryRemovedLocked(duration);
2849}
2850
2851
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002852void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002853 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002854 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002855 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002856 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002857 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002858 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002859
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002860 FlushInflightReqStates states {
2861 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
2862 listener, *this, *mInterface, *this};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002863
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002864 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002865}
2866
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002867CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002868 ALOGV("%s", __FUNCTION__);
2869
Igor Murashkin1e479c02013-09-06 16:55:14 -07002870 CameraMetadata retVal;
2871
2872 if (mRequestThread != NULL) {
2873 retVal = mRequestThread->getLatestRequest();
2874 }
2875
Igor Murashkin1e479c02013-09-06 16:55:14 -07002876 return retVal;
2877}
2878
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002879void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002880 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2881 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2882
2883 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2884 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002885}
2886
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002887/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002888 * HalInterface inner class methods
2889 */
2890
Yifan Hongf79b5542017-04-11 14:44:25 -07002891Camera3Device::HalInterface::HalInterface(
2892 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002893 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002894 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002895 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002896 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08002897 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002898 mIsReconfigurationQuerySupported(true),
2899 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002900 // Check with hardware service manager if we can downcast these interfaces
2901 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002902 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
2903 if (castResult_3_6.isOk()) {
2904 mHidlSession_3_6 = castResult_3_6;
2905 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002906 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
2907 if (castResult_3_5.isOk()) {
2908 mHidlSession_3_5 = castResult_3_5;
2909 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002910 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
2911 if (castResult_3_4.isOk()) {
2912 mHidlSession_3_4 = castResult_3_4;
2913 }
2914 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
2915 if (castResult_3_3.isOk()) {
2916 mHidlSession_3_3 = castResult_3_3;
2917 }
2918}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002919
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002920Camera3Device::HalInterface::HalInterface() :
2921 mUseHalBufManager(false),
2922 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002923
2924Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002925 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002926 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002927 mUseHalBufManager(other.mUseHalBufManager),
2928 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002929
2930bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01002931 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002932}
2933
2934void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002935 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00002936 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00002937 mHidlSession_3_4.clear();
2938 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002939 mHidlSession.clear();
2940}
2941
2942status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2943 camera3_request_template_t templateId,
2944 /*out*/ camera_metadata_t **requestTemplate) {
2945 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
2946 if (!valid()) return INVALID_OPERATION;
2947 status_t res = OK;
2948
Emilian Peev31abd0a2017-05-11 18:37:46 +01002949 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002950
2951 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01002952 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002953 status = s;
2954 if (status == common::V1_0::Status::OK) {
2955 const camera_metadata *r =
2956 reinterpret_cast<const camera_metadata_t*>(request.data());
2957 size_t expectedSize = request.size();
2958 int ret = validate_camera_metadata_structure(r, &expectedSize);
2959 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
2960 *requestTemplate = clone_camera_metadata(r);
2961 if (*requestTemplate == nullptr) {
2962 ALOGE("%s: Unable to clone camera metadata received from HAL",
2963 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01002964 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002965 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002966 } else {
2967 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
2968 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01002969 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002970 }
2971 };
2972 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08002973 RequestTemplate id;
2974 switch (templateId) {
2975 case CAMERA3_TEMPLATE_PREVIEW:
2976 id = RequestTemplate::PREVIEW;
2977 break;
2978 case CAMERA3_TEMPLATE_STILL_CAPTURE:
2979 id = RequestTemplate::STILL_CAPTURE;
2980 break;
2981 case CAMERA3_TEMPLATE_VIDEO_RECORD:
2982 id = RequestTemplate::VIDEO_RECORD;
2983 break;
2984 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
2985 id = RequestTemplate::VIDEO_SNAPSHOT;
2986 break;
2987 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
2988 id = RequestTemplate::ZERO_SHUTTER_LAG;
2989 break;
2990 case CAMERA3_TEMPLATE_MANUAL:
2991 id = RequestTemplate::MANUAL;
2992 break;
2993 default:
2994 // Unknown template ID, or this HAL is too old to support it
2995 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002996 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08002997 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002998
Emilian Peev31abd0a2017-05-11 18:37:46 +01002999 if (!err.isOk()) {
3000 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3001 res = DEAD_OBJECT;
3002 } else {
3003 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003004 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003005
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003006 return res;
3007}
3008
Emilian Peev4ec17882019-01-24 17:16:58 -08003009bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
3010 CameraMetadata& newSessionParams) {
3011 // We do reconfiguration by default;
3012 bool ret = true;
3013 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
3014 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
3015 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
3016 oldSessionParams.getAndLock());
3017 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
3018 newSessionParams.getAndLock());
3019 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
3020 get_camera_metadata_size(oldSessioMeta));
3021 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
3022 get_camera_metadata_size(newSessioMeta));
3023 hardware::camera::common::V1_0::Status callStatus;
3024 bool required;
3025 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
3026 bool requiredFlag) {
3027 callStatus = s;
3028 required = requiredFlag;
3029 };
3030 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
3031 oldSessionParams.unlock(oldSessioMeta);
3032 newSessionParams.unlock(newSessioMeta);
3033 if (err.isOk()) {
3034 switch (callStatus) {
3035 case hardware::camera::common::V1_0::Status::OK:
3036 ret = required;
3037 break;
3038 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3039 mIsReconfigurationQuerySupported = false;
3040 ret = true;
3041 break;
3042 default:
3043 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3044 ret = true;
3045 }
3046 } else {
3047 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3048 ret = true;
3049 }
3050 }
3051
3052 return ret;
3053}
3054
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003055status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003056 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003057 ATRACE_NAME("CameraHal::configureStreams");
3058 if (!valid()) return INVALID_OPERATION;
3059 status_t res = OK;
3060
Emilian Peev31abd0a2017-05-11 18:37:46 +01003061 // Convert stream config to HIDL
3062 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003063 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3064 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3065 requestedConfiguration3_2.streams.resize(config->num_streams);
3066 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003067 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003068 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3069 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003070 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003071
Emilian Peev31abd0a2017-05-11 18:37:46 +01003072 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3073 cam3stream->setBufferFreedListener(this);
3074 int streamId = cam3stream->getId();
3075 StreamType streamType;
3076 switch (src->stream_type) {
3077 case CAMERA3_STREAM_OUTPUT:
3078 streamType = StreamType::OUTPUT;
3079 break;
3080 case CAMERA3_STREAM_INPUT:
3081 streamType = StreamType::INPUT;
3082 break;
3083 default:
3084 ALOGE("%s: Stream %d: Unsupported stream type %d",
3085 __FUNCTION__, streamId, config->streams[i]->stream_type);
3086 return BAD_VALUE;
3087 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003088 dst3_2.id = streamId;
3089 dst3_2.streamType = streamType;
3090 dst3_2.width = src->width;
3091 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003092 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003093 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003094 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3095 // to HAL are original, not the overriden ones.
3096 if (mHidlSession_3_5 != nullptr) {
3097 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3098 cam3stream->getOriginalFormat() : src->format);
3099 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3100 cam3stream->getOriginalDataSpace() : src->data_space);
3101 } else {
3102 dst3_2.format = mapToPixelFormat(src->format);
3103 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3104 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003105 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003106 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003107 if (src->physical_camera_id != nullptr) {
3108 dst3_4.physicalCameraId = src->physical_camera_id;
3109 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003110
3111 activeStreams.insert(streamId);
3112 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003113 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003114 }
3115 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003116 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003117
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003118 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003119 res = mapToStreamConfigurationMode(
3120 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003121 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003122 if (res != OK) {
3123 return res;
3124 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003125 requestedConfiguration3_2.operationMode = operationMode;
3126 requestedConfiguration3_4.operationMode = operationMode;
3127 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003128 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3129 get_camera_metadata_size(sessionParams));
3130
Emilian Peev31abd0a2017-05-11 18:37:46 +01003131 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003132 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003133 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003134 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003135 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003136
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003137 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003138 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3139 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003140 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003141 };
3142
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003143 auto configStream36Cb = [&status, &finalConfiguration3_6]
3144 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3145 finalConfiguration3_6 = halConfiguration;
3146 status = s;
3147 };
3148
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003149 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3150 (hardware::Return<void>& err) -> status_t {
3151 if (!err.isOk()) {
3152 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3153 return DEAD_OBJECT;
3154 }
3155 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3156 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3157 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3158 }
3159 return OK;
3160 };
3161
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003162 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3163 (hardware::Return<void>& err) -> status_t {
3164 if (!err.isOk()) {
3165 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3166 return DEAD_OBJECT;
3167 }
3168 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3169 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3170 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3171 }
3172 return OK;
3173 };
3174
Shuzhen Wang92653952019-05-07 15:11:43 -07003175 // See which version of HAL we have
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003176 if (mHidlSession_3_6 != nullptr) {
3177 ALOGV("%s: v3.6 device found", __FUNCTION__);
3178 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3179 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3180 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3181 auto err = mHidlSession_3_6->configureStreams_3_6(
3182 requestedConfiguration3_5, configStream36Cb);
3183 res = postprocConfigStream36(err);
3184 if (res != OK) {
3185 return res;
3186 }
3187 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003188 ALOGV("%s: v3.5 device found", __FUNCTION__);
3189 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3190 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3191 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3192 auto err = mHidlSession_3_5->configureStreams_3_5(
3193 requestedConfiguration3_5, configStream34Cb);
3194 res = postprocConfigStream34(err);
3195 if (res != OK) {
3196 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003197 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003198 } else if (mHidlSession_3_4 != nullptr) {
3199 // We do; use v3.4 for the call
3200 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003201 auto err = mHidlSession_3_4->configureStreams_3_4(
3202 requestedConfiguration3_4, configStream34Cb);
3203 res = postprocConfigStream34(err);
3204 if (res != OK) {
3205 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003206 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003207 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003208 // We do; use v3.3 for the call
3209 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003210 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003211 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003212 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003213 finalConfiguration = halConfiguration;
3214 status = s;
3215 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003216 if (!err.isOk()) {
3217 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3218 return DEAD_OBJECT;
3219 }
3220 } else {
3221 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3222 ALOGV("%s: v3.2 device found", __FUNCTION__);
3223 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003224 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003225 [&status, &finalConfiguration_3_2]
3226 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3227 finalConfiguration_3_2 = halConfiguration;
3228 status = s;
3229 });
3230 if (!err.isOk()) {
3231 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3232 return DEAD_OBJECT;
3233 }
3234 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3235 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3236 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3237 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003238 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003239 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003240 }
3241
3242 if (status != common::V1_0::Status::OK ) {
3243 return CameraProviderManager::mapToStatusT(status);
3244 }
3245
3246 // And convert output stream configuration from HIDL
3247
3248 for (size_t i = 0; i < config->num_streams; i++) {
3249 camera3_stream_t *dst = config->streams[i];
3250 int streamId = Camera3Stream::cast(dst)->getId();
3251
3252 // Start scan at i, with the assumption that the stream order matches
3253 size_t realIdx = i;
3254 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003255 size_t halStreamCount = finalConfiguration.streams.size();
3256 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003257 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003258 found = true;
3259 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003260 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003261 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003262 }
3263 if (!found) {
3264 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3265 __FUNCTION__, streamId);
3266 return INVALID_OPERATION;
3267 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003268 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003269 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003270
Emilian Peev710c1422017-08-30 11:19:38 +01003271 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003272 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3273 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3274
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003275 if (mHidlSession_3_6 != nullptr) {
3276 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3277 }
3278
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003279 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003280 dstStream->setFormatOverride(false);
3281 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003282 if (dst->format != overrideFormat) {
3283 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3284 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003285 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003286 if (dst->data_space != overrideDataSpace) {
3287 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3288 streamId, dst->format);
3289 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003290 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003291 bool needFormatOverride =
3292 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3293 bool needDataspaceOverride =
3294 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003295 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003296 dstStream->setFormatOverride(needFormatOverride);
3297 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003298 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003299 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003300 }
3301
Emilian Peev31abd0a2017-05-11 18:37:46 +01003302 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003303 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003304 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003305 __FUNCTION__, streamId);
3306 return INVALID_OPERATION;
3307 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003308 dstStream->setUsage(
3309 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003310 } else {
3311 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003312 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003313 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3314 __FUNCTION__, streamId);
3315 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003316 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003317 dstStream->setUsage(
3318 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003319 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003320 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003321 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003322
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003323 return res;
3324}
3325
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003326status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003327 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003328 /*out*/std::vector<native_handle_t*>* handlesCreated,
3329 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003330 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003331 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3332 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3333 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003334 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003335 }
3336
3337 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003338
3339 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003340
3341 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003342 if (request->input_buffer != nullptr) {
3343 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3344 buffer_handle_t buf = *(request->input_buffer->buffer);
3345 auto pair = getBufferId(buf, streamId);
3346 bool isNewBuffer = pair.first;
3347 uint64_t bufferId = pair.second;
3348 captureRequest->inputBuffer.streamId = streamId;
3349 captureRequest->inputBuffer.bufferId = bufferId;
3350 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3351 captureRequest->inputBuffer.status = BufferStatus::OK;
3352 native_handle_t *acquireFence = nullptr;
3353 if (request->input_buffer->acquire_fence != -1) {
3354 acquireFence = native_handle_create(1,0);
3355 acquireFence->data[0] = request->input_buffer->acquire_fence;
3356 handlesCreated->push_back(acquireFence);
3357 }
3358 captureRequest->inputBuffer.acquireFence = acquireFence;
3359 captureRequest->inputBuffer.releaseFence = nullptr;
3360
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003361 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003362 request->input_buffer->buffer);
3363 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003364 } else {
3365 captureRequest->inputBuffer.streamId = -1;
3366 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3367 }
3368
3369 captureRequest->outputBuffers.resize(request->num_output_buffers);
3370 for (size_t i = 0; i < request->num_output_buffers; i++) {
3371 const camera3_stream_buffer_t *src = request->output_buffers + i;
3372 StreamBuffer &dst = captureRequest->outputBuffers[i];
3373 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003374 if (src->buffer != nullptr) {
3375 buffer_handle_t buf = *(src->buffer);
3376 auto pair = getBufferId(buf, streamId);
3377 bool isNewBuffer = pair.first;
3378 dst.bufferId = pair.second;
3379 dst.buffer = isNewBuffer ? buf : nullptr;
3380 native_handle_t *acquireFence = nullptr;
3381 if (src->acquire_fence != -1) {
3382 acquireFence = native_handle_create(1,0);
3383 acquireFence->data[0] = src->acquire_fence;
3384 handlesCreated->push_back(acquireFence);
3385 }
3386 dst.acquireFence = acquireFence;
3387 } else if (mUseHalBufManager) {
3388 // HAL buffer management path
3389 dst.bufferId = BUFFER_ID_NO_BUFFER;
3390 dst.buffer = nullptr;
3391 dst.acquireFence = nullptr;
3392 } else {
3393 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3394 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003395 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003396 dst.streamId = streamId;
3397 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003398 dst.releaseFence = nullptr;
3399
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003400 // Output buffers are empty when using HAL buffer manager
3401 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003402 mBufferRecords.pushInflightBuffer(
3403 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003404 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003405 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003406 }
3407 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003408 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003409}
3410
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003411void Camera3Device::HalInterface::cleanupNativeHandles(
3412 std::vector<native_handle_t*> *handles, bool closeFd) {
3413 if (handles == nullptr) {
3414 return;
3415 }
3416 if (closeFd) {
3417 for (auto& handle : *handles) {
3418 native_handle_close(handle);
3419 }
3420 }
3421 for (auto& handle : *handles) {
3422 native_handle_delete(handle);
3423 }
3424 handles->clear();
3425 return;
3426}
3427
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003428status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3429 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3430 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3431 if (!valid()) return INVALID_OPERATION;
3432
Emilian Peevaebbe412018-01-15 13:53:24 +00003433 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3434 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3435 if (castResult_3_4.isOk()) {
3436 hidlSession_3_4 = castResult_3_4;
3437 }
3438
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003439 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003440 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003441 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003442 if (hidlSession_3_4 != nullptr) {
3443 captureRequests_3_4.resize(batchSize);
3444 } else {
3445 captureRequests.resize(batchSize);
3446 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003447 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003448 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003449
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003450 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003451 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003452 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003453 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003454 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003455 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003456 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3457 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003458 }
3459 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003460 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003461 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003462 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003463 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003464 }
3465
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003466 std::vector<device::V3_2::BufferCache> cachesToRemove;
3467 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003468 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003469 for (auto& pair : mFreedBuffers) {
3470 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003471 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003472 cachesToRemove.push_back({pair.first, pair.second});
3473 }
3474 }
3475 mFreedBuffers.clear();
3476 }
3477
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003478 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3479 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003480
3481 // Write metadata to FMQ.
3482 for (size_t i = 0; i < batchSize; i++) {
3483 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003484 device::V3_2::CaptureRequest* captureRequest;
3485 if (hidlSession_3_4 != nullptr) {
3486 captureRequest = &captureRequests_3_4[i].v3_2;
3487 } else {
3488 captureRequest = &captureRequests[i];
3489 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003490
3491 if (request->settings != nullptr) {
3492 size_t settingsSize = get_camera_metadata_size(request->settings);
3493 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3494 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3495 captureRequest->settings.resize(0);
3496 captureRequest->fmqSettingsSize = settingsSize;
3497 } else {
3498 if (mRequestMetadataQueue != nullptr) {
3499 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3500 }
3501 captureRequest->settings.setToExternal(
3502 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3503 get_camera_metadata_size(request->settings));
3504 captureRequest->fmqSettingsSize = 0u;
3505 }
3506 } else {
3507 // A null request settings maps to a size-0 CameraMetadata
3508 captureRequest->settings.resize(0);
3509 captureRequest->fmqSettingsSize = 0u;
3510 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003511
3512 if (hidlSession_3_4 != nullptr) {
3513 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3514 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003515 if (request->physcam_settings != nullptr) {
3516 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3517 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3518 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3519 settingsSize)) {
3520 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3521 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3522 settingsSize;
3523 } else {
3524 if (mRequestMetadataQueue != nullptr) {
3525 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3526 }
3527 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3528 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3529 request->physcam_settings[j])),
3530 get_camera_metadata_size(request->physcam_settings[j]));
3531 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003532 }
Emilian Peev00420d22018-02-05 21:33:13 +00003533 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003534 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003535 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003536 }
3537 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3538 request->physcam_id[j];
3539 }
3540 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003541 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003542
3543 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003544 auto resultCallback =
3545 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3546 status = s;
3547 *numRequestProcessed = n;
3548 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003549 if (hidlSession_3_4 != nullptr) {
3550 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003551 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003552 } else {
3553 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003554 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003555 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003556 if (!err.isOk()) {
3557 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003558 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003559 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003560
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003561 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3562 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3563 __FUNCTION__, *numRequestProcessed, batchSize);
3564 status = common::V1_0::Status::INTERNAL_ERROR;
3565 }
3566
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003567 res = CameraProviderManager::mapToStatusT(status);
3568 if (res == OK) {
3569 if (mHidlSession->isRemote()) {
3570 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3571 // sent to camera HAL processes)
3572 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3573 } else {
3574 // In passthrough mode the FDs are now owned by HAL
3575 cleanupNativeHandles(&handlesCreated);
3576 }
3577 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003578 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003579 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003580 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003581 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003582}
3583
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003584status_t Camera3Device::HalInterface::flush() {
3585 ATRACE_NAME("CameraHal::flush");
3586 if (!valid()) return INVALID_OPERATION;
3587 status_t res = OK;
3588
Emilian Peev31abd0a2017-05-11 18:37:46 +01003589 auto err = mHidlSession->flush();
3590 if (!err.isOk()) {
3591 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3592 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003593 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003594 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003595 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003596
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003597 return res;
3598}
3599
Emilian Peev31abd0a2017-05-11 18:37:46 +01003600status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003601 ATRACE_NAME("CameraHal::dump");
3602 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003603
Emilian Peev31abd0a2017-05-11 18:37:46 +01003604 // Handled by CameraProviderManager::dump
3605
3606 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003607}
3608
3609status_t Camera3Device::HalInterface::close() {
3610 ATRACE_NAME("CameraHal::close()");
3611 if (!valid()) return INVALID_OPERATION;
3612 status_t res = OK;
3613
Emilian Peev31abd0a2017-05-11 18:37:46 +01003614 auto err = mHidlSession->close();
3615 // Interface will be dead shortly anyway, so don't log errors
3616 if (!err.isOk()) {
3617 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003618 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003619
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003620 return res;
3621}
3622
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003623void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3624 ATRACE_NAME("CameraHal::signalPipelineDrain");
3625 if (!valid() || mHidlSession_3_5 == nullptr) {
3626 ALOGE("%s called on invalid camera!", __FUNCTION__);
3627 return;
3628 }
3629
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003630 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003631 if (!err.isOk()) {
3632 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3633 return;
3634 }
3635}
3636
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003637status_t Camera3Device::HalInterface::switchToOffline(
3638 const std::vector<int32_t>& streamsToKeep,
3639 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003640 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3641 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003642 ATRACE_NAME("CameraHal::switchToOffline");
3643 if (!valid() || mHidlSession_3_6 == nullptr) {
3644 ALOGE("%s called on invalid camera!", __FUNCTION__);
3645 return INVALID_OPERATION;
3646 }
3647
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003648 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3649 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003650 return INVALID_OPERATION;
3651 }
3652
3653 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003654 auto resultCallback =
3655 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3656 status = s;
3657 *offlineSessionInfo = info;
3658 *offlineSession = session;
3659 };
3660 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3661
3662 if (!err.isOk()) {
3663 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3664 return DEAD_OBJECT;
3665 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003666
3667 status_t ret = CameraProviderManager::mapToStatusT(status);
3668 if (ret != OK) {
3669 return ret;
3670 }
3671
3672 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3673 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3674 // returns from switchToOffline.
3675
3676
3677 // Validate buffer caches
3678 std::vector<int32_t> streams;
3679 streams.reserve(offlineSessionInfo->offlineStreams.size());
3680 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3681 int32_t id = offlineStream.id;
3682 streams.push_back(id);
3683 // Verify buffer caches
3684 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3685 offlineStream.circulatingBufferIds.end());
3686 if (!verifyBufferIds(id, bufIds)) {
3687 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3688 return UNKNOWN_ERROR;
3689 }
3690 }
3691
3692 // Move buffer records
3693 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3694 bufferRecords->takeInflightBufferMap(mBufferRecords);
3695 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3696 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003697}
3698
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003699void Camera3Device::HalInterface::getInflightBufferKeys(
3700 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003701 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003702 return;
3703}
3704
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003705void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3706 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003707 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003708 return;
3709}
3710
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003711bool Camera3Device::HalInterface::verifyBufferIds(
3712 int32_t streamId, std::vector<uint64_t>& bufIds) {
3713 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003714}
3715
3716status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003717 int32_t frameNumber, int32_t streamId,
3718 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003719 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003720}
3721
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003722status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003723 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003724 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003725}
3726
3727// Find and pop a buffer_handle_t based on bufferId
3728status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003729 uint64_t bufferId,
3730 /*out*/ buffer_handle_t** buffer,
3731 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003732 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003733}
3734
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003735std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3736 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003737 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003738}
3739
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003740void Camera3Device::HalInterface::onBufferFreed(
3741 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003742 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3743 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3744 if (bufferId != BUFFER_ID_NO_BUFFER) {
3745 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003746 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003747}
3748
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003749void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003750 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3751 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3752 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003753 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3754 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003755}
3756
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003757/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003758 * RequestThread inner class methods
3759 */
3760
3761Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003762 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003763 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3764 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003765 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003766 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003767 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003768 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003769 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003770 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003771 mReconfigured(false),
3772 mDoPause(false),
3773 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003774 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003775 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003776 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003777 mCurrentAfTriggerId(0),
3778 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003779 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003780 mRepeatingLastFrameNumber(
3781 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003782 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003783 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003784 mRequestLatency(kRequestLatencyBinSize),
3785 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003786 mLatestSessionParams(sessionParamKeys.size()),
3787 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003788 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003789}
3790
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003791Camera3Device::RequestThread::~RequestThread() {}
3792
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003793void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003794 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003795 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003796 Mutex::Autolock l(mRequestLock);
3797 mListener = listener;
3798}
3799
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003800void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3801 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003802 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003803 Mutex::Autolock l(mRequestLock);
3804 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003805 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003806 // Prepare video stream for high speed recording.
3807 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003808 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003809}
3810
Jianing Wei90e59c92014-03-12 18:29:36 -07003811status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003812 List<sp<CaptureRequest> > &requests,
3813 /*out*/
3814 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003815 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003816 Mutex::Autolock l(mRequestLock);
3817 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3818 ++it) {
3819 mRequestQueue.push_back(*it);
3820 }
3821
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003822 if (lastFrameNumber != NULL) {
3823 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3824 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3825 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3826 *lastFrameNumber);
3827 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003828
Jianing Wei90e59c92014-03-12 18:29:36 -07003829 unpauseForNewRequests();
3830
3831 return OK;
3832}
3833
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003834
3835status_t Camera3Device::RequestThread::queueTrigger(
3836 RequestTrigger trigger[],
3837 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003838 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003839 Mutex::Autolock l(mTriggerMutex);
3840 status_t ret;
3841
3842 for (size_t i = 0; i < count; ++i) {
3843 ret = queueTriggerLocked(trigger[i]);
3844
3845 if (ret != OK) {
3846 return ret;
3847 }
3848 }
3849
3850 return OK;
3851}
3852
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003853const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3854 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003855 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003856 if (d != nullptr) return d->mId;
3857 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003858}
3859
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003860status_t Camera3Device::RequestThread::queueTriggerLocked(
3861 RequestTrigger trigger) {
3862
3863 uint32_t tag = trigger.metadataTag;
3864 ssize_t index = mTriggerMap.indexOfKey(tag);
3865
3866 switch (trigger.getTagType()) {
3867 case TYPE_BYTE:
3868 // fall-through
3869 case TYPE_INT32:
3870 break;
3871 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003872 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3873 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003874 return INVALID_OPERATION;
3875 }
3876
3877 /**
3878 * Collect only the latest trigger, since we only have 1 field
3879 * in the request settings per trigger tag, and can't send more than 1
3880 * trigger per request.
3881 */
3882 if (index != NAME_NOT_FOUND) {
3883 mTriggerMap.editValueAt(index) = trigger;
3884 } else {
3885 mTriggerMap.add(tag, trigger);
3886 }
3887
3888 return OK;
3889}
3890
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003891status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003892 const RequestList &requests,
3893 /*out*/
3894 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003895 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003896 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003897 if (lastFrameNumber != NULL) {
3898 *lastFrameNumber = mRepeatingLastFrameNumber;
3899 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003900 mRepeatingRequests.clear();
3901 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3902 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003903
3904 unpauseForNewRequests();
3905
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003906 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003907 return OK;
3908}
3909
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003910bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003911 if (mRepeatingRequests.empty()) {
3912 return false;
3913 }
3914 int32_t requestId = requestIn->mResultExtras.requestId;
3915 const RequestList &repeatRequests = mRepeatingRequests;
3916 // All repeating requests are guaranteed to have same id so only check first quest
3917 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3918 return (firstRequest->mResultExtras.requestId == requestId);
3919}
3920
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003921status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003922 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003923 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003924 return clearRepeatingRequestsLocked(lastFrameNumber);
3925
3926}
3927
3928status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003929 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003930 if (lastFrameNumber != NULL) {
3931 *lastFrameNumber = mRepeatingLastFrameNumber;
3932 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003933 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003934 return OK;
3935}
3936
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003937status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003938 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003939 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003940 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003941 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003942
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003943 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003944
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003945 // Send errors for all requests pending in the request queue, including
3946 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003947 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003948 if (listener != NULL) {
3949 for (RequestList::iterator it = mRequestQueue.begin();
3950 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003951 // Abort the input buffers for reprocess requests.
3952 if ((*it)->mInputStream != NULL) {
3953 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003954 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3955 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003956 if (res != OK) {
3957 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3958 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3959 } else {
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07003960 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003961 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3962 if (res != OK) {
3963 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3964 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3965 }
3966 }
3967 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003968 // Set the frame number this request would have had, if it
3969 // had been submitted; this frame number will not be reused.
3970 // The requestId and burstId fields were set when the request was
3971 // submitted originally (in convertMetadataListToRequestListLocked)
3972 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003973 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003974 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003975 }
3976 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003977 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003978
3979 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003980 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003981 if (lastFrameNumber != NULL) {
3982 *lastFrameNumber = mRepeatingLastFrameNumber;
3983 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003984 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003985 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003986 return OK;
3987}
3988
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003989status_t Camera3Device::RequestThread::flush() {
3990 ATRACE_CALL();
3991 Mutex::Autolock l(mFlushLock);
3992
Emilian Peev08dd2452017-04-06 16:55:14 +01003993 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003994}
3995
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003996void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003997 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003998 Mutex::Autolock l(mPauseLock);
3999 mDoPause = paused;
4000 mDoPauseSignal.signal();
4001}
4002
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004003status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4004 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004005 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004006 Mutex::Autolock l(mLatestRequestMutex);
4007 status_t res;
4008 while (mLatestRequestId != requestId) {
4009 nsecs_t startTime = systemTime();
4010
4011 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4012 if (res != OK) return res;
4013
4014 timeout -= (systemTime() - startTime);
4015 }
4016
4017 return OK;
4018}
4019
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004020void Camera3Device::RequestThread::requestExit() {
4021 // Call parent to set up shutdown
4022 Thread::requestExit();
4023 // The exit from any possible waits
4024 mDoPauseSignal.signal();
4025 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004026
4027 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4028 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004029}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004030
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004031void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004032 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004033 bool surfaceAbandoned = false;
4034 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004035 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004036 {
4037 Mutex::Autolock l(mRequestLock);
4038 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4039 // repeating requests.
4040 for (const auto& request : mRepeatingRequests) {
4041 for (const auto& s : request->mOutputStreams) {
4042 if (s->isAbandoned()) {
4043 surfaceAbandoned = true;
4044 clearRepeatingRequestsLocked(&lastFrameNumber);
4045 break;
4046 }
4047 }
4048 if (surfaceAbandoned) {
4049 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004050 }
4051 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004052 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004053 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004054
4055 if (listener != NULL && surfaceAbandoned) {
4056 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004057 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004058}
4059
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004060bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004061 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004062 status_t res;
4063 size_t batchSize = mNextRequests.size();
4064 std::vector<camera3_capture_request_t*> requests(batchSize);
4065 uint32_t numRequestProcessed = 0;
4066 for (size_t i = 0; i < batchSize; i++) {
4067 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004068 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004069 }
4070
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004071 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4072
4073 bool triggerRemoveFailed = false;
4074 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4075 for (size_t i = 0; i < numRequestProcessed; i++) {
4076 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4077 nextRequest.submitted = true;
4078
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004079 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004080
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004081 if (!triggerRemoveFailed) {
4082 // Remove any previously queued triggers (after unlock)
4083 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4084 if (removeTriggerRes != OK) {
4085 triggerRemoveFailed = true;
4086 triggerFailedRequest = nextRequest;
4087 }
4088 }
4089 }
4090
4091 if (triggerRemoveFailed) {
4092 SET_ERR("RequestThread: Unable to remove triggers "
4093 "(capture request %d, HAL device: %s (%d)",
4094 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4095 cleanUpFailedRequests(/*sendRequestError*/ false);
4096 return false;
4097 }
4098
4099 if (res != OK) {
4100 // Should only get a failure here for malformed requests or device-level
4101 // errors, so consider all errors fatal. Bad metadata failures should
4102 // come through notify.
4103 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4104 mNextRequests[numRequestProcessed].halRequest.frame_number,
4105 strerror(-res), res);
4106 cleanUpFailedRequests(/*sendRequestError*/ false);
4107 return false;
4108 }
4109 return true;
4110}
4111
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004112nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4113 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4114 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4115 find_camera_metadata_ro_entry(request,
4116 ANDROID_CONTROL_AE_MODE,
4117 &e);
4118 if (e.count == 0) return maxExpectedDuration;
4119
4120 switch (e.data.u8[0]) {
4121 case ANDROID_CONTROL_AE_MODE_OFF:
4122 find_camera_metadata_ro_entry(request,
4123 ANDROID_SENSOR_EXPOSURE_TIME,
4124 &e);
4125 if (e.count > 0) {
4126 maxExpectedDuration = e.data.i64[0];
4127 }
4128 find_camera_metadata_ro_entry(request,
4129 ANDROID_SENSOR_FRAME_DURATION,
4130 &e);
4131 if (e.count > 0) {
4132 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4133 }
4134 break;
4135 default:
4136 find_camera_metadata_ro_entry(request,
4137 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4138 &e);
4139 if (e.count > 1) {
4140 maxExpectedDuration = 1e9 / e.data.u8[0];
4141 }
4142 break;
4143 }
4144
4145 return maxExpectedDuration;
4146}
4147
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004148bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4149 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4150 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4151 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4152 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4153 return true;
4154 }
4155
4156 return false;
4157}
4158
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004159void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4160 // Update the latest request sent to HAL
4161 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4162 Mutex::Autolock al(mLatestRequestMutex);
4163
4164 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4165 mLatestRequest.acquire(cloned);
4166
4167 mLatestPhysicalRequest.clear();
4168 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
4169 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
4170 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
4171 CameraMetadata(cloned));
4172 }
4173
4174 sp<Camera3Device> parent = mParent.promote();
4175 if (parent != NULL) {
4176 parent->monitorMetadata(TagMonitor::REQUEST,
4177 nextRequest.halRequest.frame_number,
4178 0, mLatestRequest, mLatestPhysicalRequest);
4179 }
4180 }
4181
4182 if (nextRequest.halRequest.settings != NULL) {
4183 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4184 nextRequest.halRequest.settings);
4185 }
4186
4187 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4188}
4189
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004190bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4191 ATRACE_CALL();
4192 bool updatesDetected = false;
4193
Emilian Peev4ec17882019-01-24 17:16:58 -08004194 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004195 for (auto tag : mSessionParamKeys) {
4196 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004197 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004198
4199 if (entry.count > 0) {
4200 bool isDifferent = false;
4201 if (lastEntry.count > 0) {
4202 // Have a last value, compare to see if changed
4203 if (lastEntry.type == entry.type &&
4204 lastEntry.count == entry.count) {
4205 // Same type and count, compare values
4206 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4207 size_t entryBytes = bytesPerValue * lastEntry.count;
4208 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4209 if (cmp != 0) {
4210 isDifferent = true;
4211 }
4212 } else {
4213 // Count or type has changed
4214 isDifferent = true;
4215 }
4216 } else {
4217 // No last entry, so always consider to be different
4218 isDifferent = true;
4219 }
4220
4221 if (isDifferent) {
4222 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004223 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4224 updatesDetected = true;
4225 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004226 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004227 }
4228 } else if (lastEntry.count > 0) {
4229 // Value has been removed
4230 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004231 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004232 updatesDetected = true;
4233 }
4234 }
4235
Emilian Peev4ec17882019-01-24 17:16:58 -08004236 bool reconfigureRequired;
4237 if (updatesDetected) {
4238 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4239 updatedParams);
4240 mLatestSessionParams = updatedParams;
4241 } else {
4242 reconfigureRequired = false;
4243 }
4244
4245 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004246}
4247
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004248bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004249 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004250 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004251 // Any function called from threadLoop() must not hold mInterfaceLock since
4252 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4253 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004254
4255 // Handle paused state.
4256 if (waitIfPaused()) {
4257 return true;
4258 }
4259
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004260 // Wait for the next batch of requests.
4261 waitForNextRequestBatch();
4262 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004263 return true;
4264 }
4265
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004266 // Get the latest request ID, if any
4267 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004268 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004269 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004270 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004271 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004272 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004273 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4274 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004275 }
4276
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004277 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4278 // or a single request from streaming or burst. In either case the first element
4279 // should contain the latest camera settings that we need to check for any session
4280 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004281 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004282 res = OK;
4283
4284 //Input stream buffers are already acquired at this point so an input stream
4285 //will not be able to move to idle state unless we force it.
4286 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4287 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4288 if (res != OK) {
4289 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4290 cleanUpFailedRequests(/*sendRequestError*/ false);
4291 return false;
4292 }
4293 }
4294
4295 if (res == OK) {
Emilian Peev3bead5f2020-05-28 17:29:08 -07004296 sp<Camera3Device> parent = mParent.promote();
4297 if (parent != nullptr) {
4298 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams, mStatusId);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004299 }
Emilian Peev3bead5f2020-05-28 17:29:08 -07004300 setPaused(false);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004301
4302 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4303 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4304 if (res != OK) {
4305 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4306 cleanUpFailedRequests(/*sendRequestError*/ false);
4307 return false;
4308 }
4309 }
4310 }
4311 }
4312
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004313 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004314 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004315 if (res == TIMED_OUT) {
4316 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004317 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004318 // Check if any stream is abandoned.
4319 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004320 return true;
4321 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004322 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004323 return false;
4324 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004325
Zhijun Hecc27e112013-10-03 16:12:43 -07004326 // Inform waitUntilRequestProcessed thread of a new request ID
4327 {
4328 Mutex::Autolock al(mLatestRequestMutex);
4329
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004330 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004331 mLatestRequestSignal.signal();
4332 }
4333
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004334 // Submit a batch of requests to HAL.
4335 // Use flush lock only when submitting multilple requests in a batch.
4336 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4337 // which may take a long time to finish so synchronizing flush() and
4338 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4339 // For now, only synchronize for high speed recording and we should figure something out for
4340 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004341 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004342
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004343 if (useFlushLock) {
4344 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004345 }
4346
Zhijun Hef0645c12016-08-02 00:58:11 -07004347 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004348 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004349
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004350 sp<Camera3Device> parent = mParent.promote();
4351 if (parent != nullptr) {
4352 parent->mRequestBufferSM.onSubmittingRequest();
4353 }
4354
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004355 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004356 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004357 submitRequestSuccess = sendRequestsBatch();
4358
Shuzhen Wang686f6442017-06-20 16:16:04 -07004359 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4360 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004361
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004362 if (useFlushLock) {
4363 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004364 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004365
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004366 // Unset as current request
4367 {
4368 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004369 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004370 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004371 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004372
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004373 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004374}
4375
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004376status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004377 ATRACE_CALL();
4378
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004379 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004380 for (size_t i = 0; i < mNextRequests.size(); i++) {
4381 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004382 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4383 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4384 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4385
4386 // Prepare a request to HAL
4387 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4388
4389 // Insert any queued triggers (before metadata is locked)
4390 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004391 if (res < 0) {
4392 SET_ERR("RequestThread: Unable to insert triggers "
4393 "(capture request %d, HAL device: %s (%d)",
4394 halRequest->frame_number, strerror(-res), res);
4395 return INVALID_OPERATION;
4396 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004397
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004398 int triggerCount = res;
4399 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4400 mPrevTriggers = triggerCount;
4401
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004402 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
4403
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004404 // If the request is the same as last, or we had triggers last time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004405 bool newRequest =
4406 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004407 // Request settings are all the same within one batch, so only treat the first
4408 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004409 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004410 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004411 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004412 /**
4413 * HAL workaround:
4414 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4415 */
4416 res = addDummyTriggerIds(captureRequest);
4417 if (res != OK) {
4418 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4419 "(capture request %d, HAL device: %s (%d)",
4420 halRequest->frame_number, strerror(-res), res);
4421 return INVALID_OPERATION;
4422 }
4423
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004424 {
4425 // Correct metadata regions for distortion correction if enabled
4426 sp<Camera3Device> parent = mParent.promote();
4427 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004428 List<PhysicalCameraSettings>::iterator it;
4429 for (it = captureRequest->mSettingsList.begin();
4430 it != captureRequest->mSettingsList.end(); it++) {
4431 if (parent->mDistortionMappers.find(it->cameraId) ==
4432 parent->mDistortionMappers.end()) {
4433 continue;
4434 }
4435 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4436 &(it->metadata));
4437 if (res != OK) {
4438 SET_ERR("RequestThread: Unable to correct capture requests "
4439 "for lens distortion for request %d: %s (%d)",
4440 halRequest->frame_number, strerror(-res), res);
4441 return INVALID_OPERATION;
4442 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004443 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004444
4445 for (it = captureRequest->mSettingsList.begin();
4446 it != captureRequest->mSettingsList.end(); it++) {
4447 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4448 parent->mZoomRatioMappers.end()) {
4449 continue;
4450 }
4451
4452 camera_metadata_entry_t e = it->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
4453 if (e.count > 0 && e.data.f[0] != 1.0f) {
4454 cameraIdsWithZoom.insert(it->cameraId);
4455 }
4456
4457 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4458 &(it->metadata));
4459 if (res != OK) {
4460 SET_ERR("RequestThread: Unable to correct capture requests "
4461 "for zoom ratio for request %d: %s (%d)",
4462 halRequest->frame_number, strerror(-res), res);
4463 return INVALID_OPERATION;
4464 }
4465 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004466 if (captureRequest->mRotateAndCropAuto) {
4467 for (it = captureRequest->mSettingsList.begin();
4468 it != captureRequest->mSettingsList.end(); it++) {
4469 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4470 if (mapper != parent->mRotateAndCropMappers.end()) {
4471 res = mapper->second.updateCaptureRequest(&(it->metadata));
4472 if (res != OK) {
4473 SET_ERR("RequestThread: Unable to correct capture requests "
4474 "for rotate-and-crop for request %d: %s (%d)",
4475 halRequest->frame_number, strerror(-res), res);
4476 return INVALID_OPERATION;
4477 }
4478 }
4479 }
4480 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004481 }
4482 }
4483
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004484 /**
4485 * The request should be presorted so accesses in HAL
4486 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4487 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004488 captureRequest->mSettingsList.begin()->metadata.sort();
4489 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004490 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004491 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004492 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4493
4494 IF_ALOGV() {
4495 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4496 find_camera_metadata_ro_entry(
4497 halRequest->settings,
4498 ANDROID_CONTROL_AF_TRIGGER,
4499 &e
4500 );
4501 if (e.count > 0) {
4502 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4503 __FUNCTION__,
4504 halRequest->frame_number,
4505 e.data.u8[0]);
4506 }
4507 }
4508 } else {
4509 // leave request.settings NULL to indicate 'reuse latest given'
4510 ALOGVV("%s: Request settings are REUSED",
4511 __FUNCTION__);
4512 }
4513
Emilian Peevaebbe412018-01-15 13:53:24 +00004514 if (captureRequest->mSettingsList.size() > 1) {
4515 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4516 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004517 if (newRequest) {
4518 halRequest->physcam_settings =
4519 new const camera_metadata* [halRequest->num_physcam_settings];
4520 } else {
4521 halRequest->physcam_settings = nullptr;
4522 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004523 auto it = ++captureRequest->mSettingsList.begin();
4524 size_t i = 0;
4525 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4526 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004527 if (newRequest) {
4528 it->metadata.sort();
4529 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4530 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004531 }
4532 }
4533
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004534 uint32_t totalNumBuffers = 0;
4535
4536 // Fill in buffers
4537 if (captureRequest->mInputStream != NULL) {
4538 halRequest->input_buffer = &captureRequest->mInputBuffer;
4539 totalNumBuffers += 1;
4540 } else {
4541 halRequest->input_buffer = NULL;
4542 }
4543
4544 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4545 captureRequest->mOutputStreams.size());
4546 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004547 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004548
4549 sp<Camera3Device> parent = mParent.promote();
4550 if (parent == NULL) {
4551 // Should not happen, and nowhere to send errors to, so just log it
4552 CLOGE("RequestThread: Parent is gone");
4553 return INVALID_OPERATION;
4554 }
4555 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4556
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004557 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004558 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004559 sp<Camera3OutputStreamInterface> outputStream =
4560 captureRequest->mOutputStreams.editItemAt(j);
4561 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004562
4563 // Prepare video buffers for high speed recording on the first video request.
4564 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4565 // Only try to prepare video stream on the first video request.
4566 mPrepareVideoStream = false;
4567
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004568 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4569 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004570 while (res == NOT_ENOUGH_DATA) {
4571 res = outputStream->prepareNextBuffer();
4572 }
4573 if (res != OK) {
4574 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4575 __FUNCTION__, strerror(-res), res);
4576 outputStream->cancelPrepare();
4577 }
4578 }
4579
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004580 std::vector<size_t> uniqueSurfaceIds;
4581 res = outputStream->getUniqueSurfaceIds(
4582 captureRequest->mOutputSurfaces[streamId],
4583 &uniqueSurfaceIds);
4584 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4585 if (res != OK && res != INVALID_OPERATION) {
4586 ALOGE("%s: failed to query stream %d unique surface IDs",
4587 __FUNCTION__, streamId);
4588 return res;
4589 }
4590 if (res == OK) {
4591 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4592 }
4593
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004594 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004595 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004596 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004597 return TIMED_OUT;
4598 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004599 // HAL will request buffer through requestStreamBuffer API
4600 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
4601 buffer.stream = outputStream->asHalStream();
4602 buffer.buffer = nullptr;
4603 buffer.status = CAMERA3_BUFFER_STATUS_OK;
4604 buffer.acquire_fence = -1;
4605 buffer.release_fence = -1;
4606 } else {
4607 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4608 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004609 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004610 if (res != OK) {
4611 // Can't get output buffer from gralloc queue - this could be due to
4612 // abandoned queue or other consumer misbehavior, so not a fatal
4613 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004614 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004615 " %s (%d)", strerror(-res), res);
4616
4617 return TIMED_OUT;
4618 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004619 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004620
4621 {
4622 sp<Camera3Device> parent = mParent.promote();
4623 if (parent != nullptr) {
4624 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4625 for (const auto& settings : captureRequest->mSettingsList) {
4626 if ((streamCameraId.isEmpty() &&
4627 parent->getId() == settings.cameraId.c_str()) ||
4628 streamCameraId == settings.cameraId.c_str()) {
4629 outputStream->fireBufferRequestForFrameNumber(
4630 captureRequest->mResultExtras.frameNumber,
4631 settings.metadata);
4632 }
4633 }
4634 }
4635 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004636
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004637 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4638
4639 if (!physicalCameraId.isEmpty()) {
4640 // Physical stream isn't supported for input request.
4641 if (halRequest->input_buffer) {
4642 CLOGE("Physical stream is not supported for input request");
4643 return INVALID_OPERATION;
4644 }
4645 requestedPhysicalCameras.insert(physicalCameraId);
4646 }
4647 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004648 }
4649 totalNumBuffers += halRequest->num_output_buffers;
4650
4651 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004652 // If this request list is for constrained high speed recording (not
4653 // preview), and the current request is not the last one in the batch,
4654 // do not send callback to the app.
4655 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004656 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004657 hasCallback = false;
4658 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004659 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004660 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01004661 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4662 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4663 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4664 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4665 isStillCapture = true;
4666 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4667 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004668
4669 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
4670 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4671 isZslCapture = true;
4672 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004673 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004674 res = parent->registerInFlight(halRequest->frame_number,
4675 totalNumBuffers, captureRequest->mResultExtras,
4676 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004677 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004678 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004679 requestedPhysicalCameras, isStillCapture, isZslCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004680 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004681 (mUseHalBufManager) ? uniqueSurfaceIdMap :
4682 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004683 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4684 ", burstId = %" PRId32 ".",
4685 __FUNCTION__,
4686 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4687 captureRequest->mResultExtras.burstId);
4688 if (res != OK) {
4689 SET_ERR("RequestThread: Unable to register new in-flight request:"
4690 " %s (%d)", strerror(-res), res);
4691 return INVALID_OPERATION;
4692 }
4693 }
4694
4695 return OK;
4696}
4697
Igor Murashkin1e479c02013-09-06 16:55:14 -07004698CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004699 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004700 Mutex::Autolock al(mLatestRequestMutex);
4701
4702 ALOGV("RequestThread::%s", __FUNCTION__);
4703
4704 return mLatestRequest;
4705}
4706
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004707bool Camera3Device::RequestThread::isStreamPending(
4708 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004709 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004710 Mutex::Autolock l(mRequestLock);
4711
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004712 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004713 if (!nextRequest.submitted) {
4714 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4715 if (stream == s) return true;
4716 }
4717 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004718 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004719 }
4720
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004721 for (const auto& request : mRequestQueue) {
4722 for (const auto& s : request->mOutputStreams) {
4723 if (stream == s) return true;
4724 }
4725 if (stream == request->mInputStream) return true;
4726 }
4727
4728 for (const auto& request : mRepeatingRequests) {
4729 for (const auto& s : request->mOutputStreams) {
4730 if (stream == s) return true;
4731 }
4732 if (stream == request->mInputStream) return true;
4733 }
4734
4735 return false;
4736}
Jianing Weicb0652e2014-03-12 18:29:36 -07004737
Emilian Peev40ead602017-09-26 15:46:36 +01004738bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4739 ATRACE_CALL();
4740 Mutex::Autolock l(mRequestLock);
4741
4742 for (const auto& nextRequest : mNextRequests) {
4743 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4744 if (s.first == streamId) {
4745 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4746 if (it != s.second.end()) {
4747 return true;
4748 }
4749 }
4750 }
4751 }
4752
4753 for (const auto& request : mRequestQueue) {
4754 for (const auto& s : request->mOutputSurfaces) {
4755 if (s.first == streamId) {
4756 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4757 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004758 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004759 }
4760 }
4761 }
4762 }
4763
4764 for (const auto& request : mRepeatingRequests) {
4765 for (const auto& s : request->mOutputSurfaces) {
4766 if (s.first == streamId) {
4767 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4768 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004769 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004770 }
4771 }
4772 }
4773 }
4774
4775 return false;
4776}
4777
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004778void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4779 if (!mUseHalBufManager) {
4780 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4781 return;
4782 }
4783
4784 Mutex::Autolock pl(mPauseLock);
4785 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004786 mInterface->signalPipelineDrain(streamIds);
4787 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004788 }
4789 // If request thread is still busy, wait until paused then notify HAL
4790 mNotifyPipelineDrain = true;
4791 mStreamIdsToBeDrained = streamIds;
4792}
4793
Yin-Chia Yehfe70f2d2020-07-28 00:17:58 -07004794void Camera3Device::RequestThread::resetPipelineDrain() {
4795 Mutex::Autolock pl(mPauseLock);
4796 mNotifyPipelineDrain = false;
4797 mStreamIdsToBeDrained.clear();
4798}
4799
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004800void Camera3Device::RequestThread::clearPreviousRequest() {
4801 Mutex::Autolock l(mRequestLock);
4802 mPrevRequest.clear();
4803}
4804
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004805status_t Camera3Device::RequestThread::switchToOffline(
4806 const std::vector<int32_t>& streamsToKeep,
4807 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004808 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4809 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004810 Mutex::Autolock l(mRequestLock);
4811 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
4812
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004813 // Wait until request thread is fully stopped
4814 // TBD: check if request thread is being paused by other APIs (shouldn't be)
4815
4816 // We could also check for mRepeatingRequests.empty(), but the API interface
4817 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
4818 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004819 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4820 while (!queueEmpty) {
4821 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
4822 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004823 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004824 return res;
4825 } else if (res != OK) {
4826 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
4827 __FUNCTION__, strerror(-res), res);
4828 return res;
4829 }
4830 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4831 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004832
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004833 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004834 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004835}
4836
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004837status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4838 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4839 ATRACE_CALL();
4840 Mutex::Autolock l(mTriggerMutex);
4841 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4842 return BAD_VALUE;
4843 }
4844 mRotateAndCropOverride = rotateAndCropValue;
4845 return OK;
4846}
4847
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004848nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004849 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004850 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004851 return mExpectedInflightDuration > kMinInflightDuration ?
4852 mExpectedInflightDuration : kMinInflightDuration;
4853}
4854
Emilian Peevaebbe412018-01-15 13:53:24 +00004855void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4856 camera3_capture_request_t *halRequest) {
4857 if ((request == nullptr) || (halRequest == nullptr)) {
4858 ALOGE("%s: Invalid request!", __FUNCTION__);
4859 return;
4860 }
4861
4862 if (halRequest->num_physcam_settings > 0) {
4863 if (halRequest->physcam_id != nullptr) {
4864 delete [] halRequest->physcam_id;
4865 halRequest->physcam_id = nullptr;
4866 }
4867 if (halRequest->physcam_settings != nullptr) {
4868 auto it = ++(request->mSettingsList.begin());
4869 size_t i = 0;
4870 for (; it != request->mSettingsList.end(); it++, i++) {
4871 it->metadata.unlock(halRequest->physcam_settings[i]);
4872 }
4873 delete [] halRequest->physcam_settings;
4874 halRequest->physcam_settings = nullptr;
4875 }
4876 }
4877}
4878
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004879void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4880 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004881 return;
4882 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004883
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004884 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004885 // Skip the ones that have been submitted successfully.
4886 if (nextRequest.submitted) {
4887 continue;
4888 }
4889
4890 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4891 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4892 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4893
4894 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004895 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004896 }
4897
Emilian Peevaebbe412018-01-15 13:53:24 +00004898 cleanupPhysicalSettings(captureRequest, halRequest);
4899
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004900 if (captureRequest->mInputStream != NULL) {
4901 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4902 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4903 }
4904
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004905 // No output buffer can be returned when using HAL buffer manager
4906 if (!mUseHalBufManager) {
4907 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4908 //Buffers that failed processing could still have
4909 //valid acquire fence.
4910 int acquireFence = (*outputBuffers)[i].acquire_fence;
4911 if (0 <= acquireFence) {
4912 close(acquireFence);
4913 outputBuffers->editItemAt(i).acquire_fence = -1;
4914 }
4915 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4916 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
4917 /*timestampIncreasing*/true, std::vector<size_t> (),
4918 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004919 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004920 }
4921
4922 if (sendRequestError) {
4923 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004924 sp<NotificationListener> listener = mListener.promote();
4925 if (listener != NULL) {
4926 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004927 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004928 captureRequest->mResultExtras);
4929 }
4930 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004931
4932 // Remove yet-to-be submitted inflight request from inflightMap
4933 {
4934 sp<Camera3Device> parent = mParent.promote();
4935 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004936 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004937 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4938 if (idx >= 0) {
4939 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4940 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4941 parent->removeInFlightMapEntryLocked(idx);
4942 }
4943 }
4944 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004945 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004946
4947 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004948 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004949}
4950
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004951void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004952 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004953 // Optimized a bit for the simple steady-state case (single repeating
4954 // request), to avoid putting that request in the queue temporarily.
4955 Mutex::Autolock l(mRequestLock);
4956
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004957 assert(mNextRequests.empty());
4958
4959 NextRequest nextRequest;
4960 nextRequest.captureRequest = waitForNextRequestLocked();
4961 if (nextRequest.captureRequest == nullptr) {
4962 return;
4963 }
4964
4965 nextRequest.halRequest = camera3_capture_request_t();
4966 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004967 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004968
4969 // Wait for additional requests
4970 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4971
4972 for (size_t i = 1; i < batchSize; i++) {
4973 NextRequest additionalRequest;
4974 additionalRequest.captureRequest = waitForNextRequestLocked();
4975 if (additionalRequest.captureRequest == nullptr) {
4976 break;
4977 }
4978
4979 additionalRequest.halRequest = camera3_capture_request_t();
4980 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004981 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004982 }
4983
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004984 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004985 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004986 mNextRequests.size(), batchSize);
4987 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004988 }
4989
4990 return;
4991}
4992
4993sp<Camera3Device::CaptureRequest>
4994 Camera3Device::RequestThread::waitForNextRequestLocked() {
4995 status_t res;
4996 sp<CaptureRequest> nextRequest;
4997
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004998 while (mRequestQueue.empty()) {
4999 if (!mRepeatingRequests.empty()) {
5000 // Always atomically enqueue all requests in a repeating request
5001 // list. Guarantees a complete in-sequence set of captures to
5002 // application.
5003 const RequestList &requests = mRepeatingRequests;
5004 RequestList::const_iterator firstRequest =
5005 requests.begin();
5006 nextRequest = *firstRequest;
5007 mRequestQueue.insert(mRequestQueue.end(),
5008 ++firstRequest,
5009 requests.end());
5010 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005011
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005012 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005013
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005014 break;
5015 }
5016
5017 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5018
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005019 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5020 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005021 Mutex::Autolock pl(mPauseLock);
5022 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005023 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005024 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005025 if (mNotifyPipelineDrain) {
5026 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5027 mNotifyPipelineDrain = false;
5028 mStreamIdsToBeDrained.clear();
5029 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005030 // Let the tracker know
5031 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5032 if (statusTracker != 0) {
5033 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5034 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005035 sp<Camera3Device> parent = mParent.promote();
5036 if (parent != nullptr) {
5037 parent->mRequestBufferSM.onRequestThreadPaused();
5038 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005039 }
5040 // Stop waiting for now and let thread management happen
5041 return NULL;
5042 }
5043 }
5044
5045 if (nextRequest == NULL) {
5046 // Don't have a repeating request already in hand, so queue
5047 // must have an entry now.
5048 RequestList::iterator firstRequest =
5049 mRequestQueue.begin();
5050 nextRequest = *firstRequest;
5051 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005052 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5053 sp<NotificationListener> listener = mListener.promote();
5054 if (listener != NULL) {
5055 listener->notifyRequestQueueEmpty();
5056 }
5057 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005058 }
5059
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005060 // In case we've been unpaused by setPaused clearing mDoPause, need to
5061 // update internal pause state (capture/setRepeatingRequest unpause
5062 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005063 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005064 if (mPaused) {
5065 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5066 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5067 if (statusTracker != 0) {
5068 statusTracker->markComponentActive(mStatusId);
5069 }
5070 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005071 mPaused = false;
5072
5073 // Check if we've reconfigured since last time, and reset the preview
5074 // request if so. Can't use 'NULL request == repeat' across configure calls.
5075 if (mReconfigured) {
5076 mPrevRequest.clear();
5077 mReconfigured = false;
5078 }
5079
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005080 if (nextRequest != NULL) {
5081 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005082 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5083 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005084
5085 // Since RequestThread::clear() removes buffers from the input stream,
5086 // get the right buffer here before unlocking mRequestLock
5087 if (nextRequest->mInputStream != NULL) {
5088 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5089 if (res != OK) {
5090 // Can't get input buffer from gralloc queue - this could be due to
5091 // disconnected queue or other producer misbehavior, so not a fatal
5092 // error
5093 ALOGE("%s: Can't get input buffer, skipping request:"
5094 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005095
5096 sp<NotificationListener> listener = mListener.promote();
5097 if (listener != NULL) {
5098 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005099 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005100 nextRequest->mResultExtras);
5101 }
5102 return NULL;
5103 }
5104 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005105 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005106
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005107 return nextRequest;
5108}
5109
5110bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005111 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005112 status_t res;
5113 Mutex::Autolock l(mPauseLock);
5114 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005115 if (mPaused == false) {
5116 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005117 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005118 if (mNotifyPipelineDrain) {
5119 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5120 mNotifyPipelineDrain = false;
5121 mStreamIdsToBeDrained.clear();
5122 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005123 // Let the tracker know
5124 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5125 if (statusTracker != 0) {
5126 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5127 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005128 sp<Camera3Device> parent = mParent.promote();
5129 if (parent != nullptr) {
5130 parent->mRequestBufferSM.onRequestThreadPaused();
5131 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005132 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005133
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005134 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005135 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005136 return true;
5137 }
5138 }
5139 // We don't set mPaused to false here, because waitForNextRequest needs
5140 // to further manage the paused state in case of starvation.
5141 return false;
5142}
5143
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005144void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005145 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005146 // With work to do, mark thread as unpaused.
5147 // If paused by request (setPaused), don't resume, to avoid
5148 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005149 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005150 Mutex::Autolock p(mPauseLock);
5151 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005152 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5153 if (mPaused) {
5154 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5155 if (statusTracker != 0) {
5156 statusTracker->markComponentActive(mStatusId);
5157 }
5158 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005159 mPaused = false;
5160 }
5161}
5162
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005163void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5164 sp<Camera3Device> parent = mParent.promote();
5165 if (parent != NULL) {
5166 va_list args;
5167 va_start(args, fmt);
5168
5169 parent->setErrorStateV(fmt, args);
5170
5171 va_end(args);
5172 }
5173}
5174
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005175status_t Camera3Device::RequestThread::insertTriggers(
5176 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005177 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005178 Mutex::Autolock al(mTriggerMutex);
5179
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005180 sp<Camera3Device> parent = mParent.promote();
5181 if (parent == NULL) {
5182 CLOGE("RequestThread: Parent is gone");
5183 return DEAD_OBJECT;
5184 }
5185
Emilian Peevaebbe412018-01-15 13:53:24 +00005186 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005187 size_t count = mTriggerMap.size();
5188
5189 for (size_t i = 0; i < count; ++i) {
5190 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005191 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005192
5193 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5194 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5195 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005196 if (isAeTrigger) {
5197 request->mResultExtras.precaptureTriggerId = triggerId;
5198 mCurrentPreCaptureTriggerId = triggerId;
5199 } else {
5200 request->mResultExtras.afTriggerId = triggerId;
5201 mCurrentAfTriggerId = triggerId;
5202 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005203 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005204 }
5205
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005206 camera_metadata_entry entry = metadata.find(tag);
5207
5208 if (entry.count > 0) {
5209 /**
5210 * Already has an entry for this trigger in the request.
5211 * Rewrite it with our requested trigger value.
5212 */
5213 RequestTrigger oldTrigger = trigger;
5214
5215 oldTrigger.entryValue = entry.data.u8[0];
5216
5217 mTriggerReplacedMap.add(tag, oldTrigger);
5218 } else {
5219 /**
5220 * More typical, no trigger entry, so we just add it
5221 */
5222 mTriggerRemovedMap.add(tag, trigger);
5223 }
5224
5225 status_t res;
5226
5227 switch (trigger.getTagType()) {
5228 case TYPE_BYTE: {
5229 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5230 res = metadata.update(tag,
5231 &entryValue,
5232 /*count*/1);
5233 break;
5234 }
5235 case TYPE_INT32:
5236 res = metadata.update(tag,
5237 &trigger.entryValue,
5238 /*count*/1);
5239 break;
5240 default:
5241 ALOGE("%s: Type not supported: 0x%x",
5242 __FUNCTION__,
5243 trigger.getTagType());
5244 return INVALID_OPERATION;
5245 }
5246
5247 if (res != OK) {
5248 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5249 ", value %d", __FUNCTION__, trigger.getTagName(),
5250 trigger.entryValue);
5251 return res;
5252 }
5253
5254 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5255 trigger.getTagName(),
5256 trigger.entryValue);
5257 }
5258
5259 mTriggerMap.clear();
5260
5261 return count;
5262}
5263
5264status_t Camera3Device::RequestThread::removeTriggers(
5265 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005266 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005267 Mutex::Autolock al(mTriggerMutex);
5268
Emilian Peevaebbe412018-01-15 13:53:24 +00005269 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005270
5271 /**
5272 * Replace all old entries with their old values.
5273 */
5274 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5275 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5276
5277 status_t res;
5278
5279 uint32_t tag = trigger.metadataTag;
5280 switch (trigger.getTagType()) {
5281 case TYPE_BYTE: {
5282 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5283 res = metadata.update(tag,
5284 &entryValue,
5285 /*count*/1);
5286 break;
5287 }
5288 case TYPE_INT32:
5289 res = metadata.update(tag,
5290 &trigger.entryValue,
5291 /*count*/1);
5292 break;
5293 default:
5294 ALOGE("%s: Type not supported: 0x%x",
5295 __FUNCTION__,
5296 trigger.getTagType());
5297 return INVALID_OPERATION;
5298 }
5299
5300 if (res != OK) {
5301 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5302 ", trigger value %d", __FUNCTION__,
5303 trigger.getTagName(), trigger.entryValue);
5304 return res;
5305 }
5306 }
5307 mTriggerReplacedMap.clear();
5308
5309 /**
5310 * Remove all new entries.
5311 */
5312 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5313 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5314 status_t res = metadata.erase(trigger.metadataTag);
5315
5316 if (res != OK) {
5317 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5318 ", trigger value %d", __FUNCTION__,
5319 trigger.getTagName(), trigger.entryValue);
5320 return res;
5321 }
5322 }
5323 mTriggerRemovedMap.clear();
5324
5325 return OK;
5326}
5327
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005328status_t Camera3Device::RequestThread::addDummyTriggerIds(
5329 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005330 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005331 static const int32_t dummyTriggerId = 1;
5332 status_t res;
5333
Emilian Peevaebbe412018-01-15 13:53:24 +00005334 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005335
5336 // If AF trigger is active, insert a dummy AF trigger ID if none already
5337 // exists
5338 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5339 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5340 if (afTrigger.count > 0 &&
5341 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5342 afId.count == 0) {
5343 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5344 if (res != OK) return res;
5345 }
5346
5347 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5348 // if none already exists
5349 camera_metadata_entry pcTrigger =
5350 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5351 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5352 if (pcTrigger.count > 0 &&
5353 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5354 pcId.count == 0) {
5355 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5356 &dummyTriggerId, 1);
5357 if (res != OK) return res;
5358 }
5359
5360 return OK;
5361}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005362
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005363bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5364 const sp<CaptureRequest> &request) {
5365 ATRACE_CALL();
5366
5367 if (request->mRotateAndCropAuto) {
5368 Mutex::Autolock l(mTriggerMutex);
5369 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5370
5371 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5372 if (rotateAndCropEntry.count > 0) {
5373 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5374 return false;
5375 } else {
5376 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5377 return true;
5378 }
5379 } else {
5380 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5381 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5382 &rotateAndCrop_u8, 1);
5383 return true;
5384 }
5385 }
5386 return false;
5387}
5388
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005389/**
5390 * PreparerThread inner class methods
5391 */
5392
5393Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005394 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005395 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005396}
5397
5398Camera3Device::PreparerThread::~PreparerThread() {
5399 Thread::requestExitAndWait();
5400 if (mCurrentStream != nullptr) {
5401 mCurrentStream->cancelPrepare();
5402 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5403 mCurrentStream.clear();
5404 }
5405 clear();
5406}
5407
Ruben Brunkc78ac262015-08-13 17:58:46 -07005408status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005409 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005410 status_t res;
5411
5412 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005413 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005414
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005415 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005416 if (res == OK) {
5417 // No preparation needed, fire listener right off
5418 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005419 if (listener != NULL) {
5420 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005421 }
5422 return OK;
5423 } else if (res != NOT_ENOUGH_DATA) {
5424 return res;
5425 }
5426
5427 // Need to prepare, start up thread if necessary
5428 if (!mActive) {
5429 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5430 // isn't running
5431 Thread::requestExitAndWait();
5432 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5433 if (res != OK) {
5434 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005435 if (listener != NULL) {
5436 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005437 }
5438 return res;
5439 }
5440 mCancelNow = false;
5441 mActive = true;
5442 ALOGV("%s: Preparer stream started", __FUNCTION__);
5443 }
5444
5445 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005446 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005447 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5448
5449 return OK;
5450}
5451
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005452void Camera3Device::PreparerThread::pause() {
5453 ATRACE_CALL();
5454
5455 Mutex::Autolock l(mLock);
5456
5457 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5458 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5459 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5460 int currentMaxCount = mCurrentMaxCount;
5461 mPendingStreams.clear();
5462 mCancelNow = true;
5463 while (mActive) {
5464 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5465 if (res == TIMED_OUT) {
5466 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5467 return;
5468 } else if (res != OK) {
5469 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5470 return;
5471 }
5472 }
5473
5474 //Check whether the prepare thread was able to complete the current
5475 //stream. In case work is still pending emplace it along with the rest
5476 //of the streams in the pending list.
5477 if (currentStream != nullptr) {
5478 if (!mCurrentPrepareComplete) {
5479 pendingStreams.emplace(currentMaxCount, currentStream);
5480 }
5481 }
5482
5483 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5484 for (const auto& it : mPendingStreams) {
5485 it.second->cancelPrepare();
5486 }
5487}
5488
5489status_t Camera3Device::PreparerThread::resume() {
5490 ATRACE_CALL();
5491 status_t res;
5492
5493 Mutex::Autolock l(mLock);
5494 sp<NotificationListener> listener = mListener.promote();
5495
5496 if (mActive) {
5497 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5498 return NO_INIT;
5499 }
5500
5501 auto it = mPendingStreams.begin();
5502 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005503 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005504 if (res == OK) {
5505 if (listener != NULL) {
5506 listener->notifyPrepared(it->second->getId());
5507 }
5508 it = mPendingStreams.erase(it);
5509 } else if (res != NOT_ENOUGH_DATA) {
5510 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5511 res, strerror(-res));
5512 it = mPendingStreams.erase(it);
5513 } else {
5514 it++;
5515 }
5516 }
5517
5518 if (mPendingStreams.empty()) {
5519 return OK;
5520 }
5521
5522 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5523 if (res != OK) {
5524 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5525 __FUNCTION__, res, strerror(-res));
5526 return res;
5527 }
5528 mCancelNow = false;
5529 mActive = true;
5530 ALOGV("%s: Preparer stream started", __FUNCTION__);
5531
5532 return OK;
5533}
5534
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005535status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005536 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005537 Mutex::Autolock l(mLock);
5538
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005539 for (const auto& it : mPendingStreams) {
5540 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005541 }
5542 mPendingStreams.clear();
5543 mCancelNow = true;
5544
5545 return OK;
5546}
5547
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005548void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005549 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005550 Mutex::Autolock l(mLock);
5551 mListener = listener;
5552}
5553
5554bool Camera3Device::PreparerThread::threadLoop() {
5555 status_t res;
5556 {
5557 Mutex::Autolock l(mLock);
5558 if (mCurrentStream == nullptr) {
5559 // End thread if done with work
5560 if (mPendingStreams.empty()) {
5561 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5562 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5563 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5564 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005565 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005566 return false;
5567 }
5568
5569 // Get next stream to prepare
5570 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005571 mCurrentStream = it->second;
5572 mCurrentMaxCount = it->first;
5573 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005574 mPendingStreams.erase(it);
5575 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5576 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5577 } else if (mCancelNow) {
5578 mCurrentStream->cancelPrepare();
5579 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5580 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5581 mCurrentStream.clear();
5582 mCancelNow = false;
5583 return true;
5584 }
5585 }
5586
5587 res = mCurrentStream->prepareNextBuffer();
5588 if (res == NOT_ENOUGH_DATA) return true;
5589 if (res != OK) {
5590 // Something bad happened; try to recover by cancelling prepare and
5591 // signalling listener anyway
5592 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5593 mCurrentStream->getId(), res, strerror(-res));
5594 mCurrentStream->cancelPrepare();
5595 }
5596
5597 // This stream has finished, notify listener
5598 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005599 sp<NotificationListener> listener = mListener.promote();
5600 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005601 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5602 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005603 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005604 }
5605
5606 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5607 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005608 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005609
5610 return true;
5611}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005612
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005613status_t Camera3Device::RequestBufferStateMachine::initialize(
5614 sp<camera3::StatusTracker> statusTracker) {
5615 if (statusTracker == nullptr) {
5616 ALOGE("%s: statusTracker is null", __FUNCTION__);
5617 return BAD_VALUE;
5618 }
5619
5620 std::lock_guard<std::mutex> lock(mLock);
5621 mStatusTracker = statusTracker;
5622 mRequestBufferStatusId = statusTracker->addComponent();
5623 return OK;
5624}
5625
5626bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5627 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005628 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005629 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005630 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005631 return true;
5632 }
5633 return false;
5634}
5635
5636void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5637 std::lock_guard<std::mutex> lock(mLock);
5638 if (!mRequestBufferOngoing) {
5639 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5640 return;
5641 }
5642 mRequestBufferOngoing = false;
5643 if (mStatus == RB_STATUS_PENDING_STOP) {
5644 checkSwitchToStopLocked();
5645 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005646 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005647}
5648
5649void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5650 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005651 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005652 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005653 return;
5654}
5655
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005656void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005657 std::lock_guard<std::mutex> lock(mLock);
5658 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005659 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5660 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005661 mInflightMapEmpty = false;
5662 if (mStatus == RB_STATUS_STOPPED) {
5663 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005664 }
5665 return;
5666}
5667
5668void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5669 std::lock_guard<std::mutex> lock(mLock);
5670 mRequestThreadPaused = true;
5671 if (mStatus == RB_STATUS_PENDING_STOP) {
5672 checkSwitchToStopLocked();
5673 }
5674 return;
5675}
5676
5677void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5678 std::lock_guard<std::mutex> lock(mLock);
5679 mInflightMapEmpty = true;
5680 if (mStatus == RB_STATUS_PENDING_STOP) {
5681 checkSwitchToStopLocked();
5682 }
5683 return;
5684}
5685
5686void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5687 std::lock_guard<std::mutex> lock(mLock);
5688 if (!checkSwitchToStopLocked()) {
5689 mStatus = RB_STATUS_PENDING_STOP;
5690 }
5691 return;
5692}
5693
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005694bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5695 std::lock_guard<std::mutex> lock(mLock);
5696 if (mRequestBufferOngoing) {
5697 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5698 __FUNCTION__);
5699 return false;
5700 }
5701 mSwitchedToOffline = true;
5702 mInflightMapEmpty = true;
5703 mRequestThreadPaused = true;
5704 mStatus = RB_STATUS_STOPPED;
5705 return true;
5706}
5707
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005708void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5709 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5710 if (statusTracker != nullptr) {
5711 if (active) {
5712 statusTracker->markComponentActive(mRequestBufferStatusId);
5713 } else {
5714 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5715 }
5716 }
5717}
5718
5719bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5720 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5721 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005722 return true;
5723 }
5724 return false;
5725}
5726
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005727bool Camera3Device::startRequestBuffer() {
5728 return mRequestBufferSM.startRequestBuffer();
5729}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005730
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005731void Camera3Device::endRequestBuffer() {
5732 mRequestBufferSM.endRequestBuffer();
5733}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005734
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005735nsecs_t Camera3Device::getWaitDuration() {
5736 return kBaseGetBufferWait + getExpectedInFlightDuration();
5737}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005738
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005739void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5740 mInterface->getInflightBufferKeys(out);
5741}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005742
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005743void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5744 mInterface->getInflightRequestBufferKeys(out);
5745}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005746
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005747std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5748 std::vector<sp<Camera3StreamInterface>> ret;
5749 bool hasInputStream = mInputStream != nullptr;
5750 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5751 if (hasInputStream) {
5752 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005753 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005754 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5755 ret.push_back(mOutputStreams[i]);
5756 }
5757 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5758 ret.push_back(mDeletedStreams[i]);
5759 }
5760 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005761}
5762
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005763status_t Camera3Device::switchToOffline(
5764 const std::vector<int32_t>& streamsToKeep,
5765 /*out*/ sp<CameraOfflineSessionBase>* session) {
5766 ATRACE_CALL();
5767 if (session == nullptr) {
5768 ALOGE("%s: session must not be null", __FUNCTION__);
5769 return BAD_VALUE;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005770 }
5771
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005772 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005773
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005774 bool hasInputStream = mInputStream != nullptr;
5775 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
5776 bool inputStreamSupportsOffline = hasInputStream ?
5777 mInputStream->getOfflineProcessingSupport() : false;
5778 auto outputStreamIds = mOutputStreams.getStreamIds();
5779 auto streamIds = outputStreamIds;
5780 if (hasInputStream) {
5781 streamIds.push_back(mInputStream->getId());
5782 }
5783
5784 // Check all streams in streamsToKeep supports offline mode
5785 for (auto id : streamsToKeep) {
5786 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5787 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
5788 return BAD_VALUE;
5789 } else if (id == inputStreamId) {
5790 if (!inputStreamSupportsOffline) {
5791 ALOGE("%s: input stream %d cannot be switched to offline",
5792 __FUNCTION__, id);
5793 return BAD_VALUE;
5794 }
5795 } else {
5796 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
5797 if (!stream->getOfflineProcessingSupport()) {
5798 ALOGE("%s: output stream %d cannot be switched to offline",
5799 __FUNCTION__, id);
5800 return BAD_VALUE;
5801 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005802 }
5803 }
5804
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005805 // TODO: block surface sharing and surface group streams until we can support them
5806
5807 // Stop repeating request, wait until all remaining requests are submitted, then call into
5808 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005809 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
5810 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005811 camera3::BufferRecords bufferRecords;
5812 status_t ret = mRequestThread->switchToOffline(
5813 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005814
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005815 if (ret != OK) {
5816 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
5817 return ret;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005818 }
5819
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005820 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
5821 if (!succ) {
5822 SET_ERR("HAL must not be calling requestStreamBuffers call");
5823 // TODO: block ALL callbacks from HAL till app configured new streams?
5824 return UNKNOWN_ERROR;
5825 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005826
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005827 // Verify offlineSessionInfo
5828 std::vector<int32_t> offlineStreamIds;
5829 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
5830 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5831 // verify stream IDs
5832 int32_t id = offlineStream.id;
5833 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5834 SET_ERR("stream ID %d not found!", id);
5835 return UNKNOWN_ERROR;
5836 }
5837
5838 // When not using HAL buf manager, only allow streams requested by app to be preserved
5839 if (!mUseHalBufManager) {
5840 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
5841 SET_ERR("stream ID %d must not be switched to offline!", id);
5842 return UNKNOWN_ERROR;
5843 }
5844 }
5845
5846 offlineStreamIds.push_back(id);
5847 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
5848 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
5849 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
5850 // Verify number of outstanding buffers
5851 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
5852 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
5853 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
5854 return UNKNOWN_ERROR;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005855 }
5856 }
5857
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005858 // Verify all streams to be deleted don't have any outstanding buffers
5859 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5860 inputStreamId) == offlineStreamIds.end()) {
5861 if (mInputStream->hasOutstandingBuffers()) {
5862 SET_ERR("Input stream %d still has %zu outstanding buffer!",
5863 inputStreamId, mInputStream->getOutstandingBuffersCount());
5864 return UNKNOWN_ERROR;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005865 }
5866 }
5867
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005868 for (const auto& outStreamId : outputStreamIds) {
5869 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5870 outStreamId) == offlineStreamIds.end()) {
5871 auto outStream = mOutputStreams.get(outStreamId);
5872 if (outStream->hasOutstandingBuffers()) {
5873 SET_ERR("Output stream %d still has %zu outstanding buffer!",
5874 outStreamId, outStream->getOutstandingBuffersCount());
5875 return UNKNOWN_ERROR;
5876 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005877 }
5878 }
5879
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005880 InFlightRequestMap offlineReqs;
5881 // Verify inflight requests and their pending buffers
5882 {
5883 std::lock_guard<std::mutex> l(mInFlightLock);
5884 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
5885 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
5886 if (idx == NAME_NOT_FOUND) {
5887 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
5888 return UNKNOWN_ERROR;
5889 }
5890
5891 const auto& inflightReq = mInFlightMap.valueAt(idx);
5892 // TODO: check specific stream IDs
5893 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
5894 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
5895 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
5896 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
5897 return UNKNOWN_ERROR;
5898 }
5899 offlineReqs.add(offlineReq.frameNumber, inflightReq);
5900 }
5901 }
5902
5903 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005904 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005905 camera3::StreamSet offlineStreamSet;
5906 sp<camera3::Camera3Stream> inputStream;
5907 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5908 int32_t id = offlineStream.id;
5909 if (mInputStream != nullptr && id == mInputStream->getId()) {
5910 inputStream = mInputStream;
5911 } else {
5912 offlineStreamSet.add(id, mOutputStreams.get(id));
5913 }
5914 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005915
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005916 // TODO: check if we need to lock before copying states
5917 // though technically no other thread should be talking to Camera3Device at this point
5918 Camera3OfflineStates offlineStates(
5919 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
Shuzhen Wangb7b42652020-05-07 11:59:02 -07005920 mUsePartialResult, mNumPartialResults, mLastCompletedRegularFrameNumber,
5921 mLastCompletedReprocessFrameNumber, mLastCompletedZslFrameNumber,
5922 mNextResultFrameNumber, mNextReprocessResultFrameNumber,
5923 mNextZslStillResultFrameNumber, mNextShutterFrameNumber,
5924 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
5925 mDeviceInfo, mPhysicalDeviceInfoMap, mDistortionMappers,
5926 mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005927
5928 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
5929 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
5930
5931 // Delete all streams that has been transferred to offline session
5932 Mutex::Autolock l(mLock);
5933 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5934 int32_t id = offlineStream.id;
5935 if (mInputStream != nullptr && id == mInputStream->getId()) {
5936 mInputStream.clear();
5937 } else {
5938 mOutputStreams.remove(id);
5939 }
5940 }
5941
5942 // disconnect all other streams and switch to UNCONFIGURED state
5943 if (mInputStream != nullptr) {
5944 ret = mInputStream->disconnect();
5945 if (ret != OK) {
5946 SET_ERR_L("disconnect input stream failed!");
5947 return UNKNOWN_ERROR;
5948 }
5949 }
5950
5951 for (auto streamId : mOutputStreams.getStreamIds()) {
5952 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
5953 ret = stream->disconnect();
5954 if (ret != OK) {
5955 SET_ERR_L("disconnect output stream %d failed!", streamId);
5956 return UNKNOWN_ERROR;
5957 }
5958 }
5959
5960 mInputStream.clear();
5961 mOutputStreams.clear();
5962 mNeedConfig = true;
5963 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
5964 mOperatingMode = NO_MODE;
5965 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005966 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005967
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005968 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005969 // TO be done by CameraDeviceClient/Camera3OfflineSession
5970 // register the offline client to camera service
5971 // Setup result passthing threads etc
5972 // Initialize offline session so HAL can start sending callback to it (result Fmq)
5973 // TODO: check how many onIdle callback will be sent
5974 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005975}
5976
Emilian Peevcc0b7952020-01-07 13:54:47 -08005977void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5978 ATRACE_CALL();
5979
5980 if (offlineStreamIds == nullptr) {
5981 return;
5982 }
5983
5984 Mutex::Autolock il(mInterfaceLock);
5985
5986 auto streamIds = mOutputStreams.getStreamIds();
5987 bool hasInputStream = mInputStream != nullptr;
5988 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5989 offlineStreamIds->push_back(mInputStream->getId());
5990 }
5991
5992 for (const auto & streamId : streamIds) {
5993 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5994 // Streams that use the camera buffer manager are currently not supported in
5995 // offline mode
5996 if (stream->getOfflineProcessingSupport() &&
5997 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5998 offlineStreamIds->push_back(streamId);
5999 }
6000 }
6001}
6002
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08006003status_t Camera3Device::setRotateAndCropAutoBehavior(
6004 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
6005 ATRACE_CALL();
6006 Mutex::Autolock il(mInterfaceLock);
6007 Mutex::Autolock l(mLock);
6008 if (mRequestThread == nullptr) {
6009 return INVALID_OPERATION;
6010 }
6011 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006012}
6013
6014}; // namespace android