blob: 2d46122626abf40461ace5ae8305ba62a802542f [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080052#include <android/hardware/camera2/ICameraDeviceUser.h>
53
Igor Murashkinff3e31d2013-10-23 16:40:06 -070054#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070055#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070056#include "device3/Camera3Device.h"
57#include "device3/Camera3OutputStream.h"
58#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070059#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070060#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070061#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070062#include "utils/CameraThreadState.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080063
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -080064#include <algorithm>
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080065#include <tuple>
66
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080068using namespace android::hardware::camera;
69using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080070
71namespace android {
72
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080073Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080074 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080075 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070076 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070077 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070078 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070079 mUsePartialResult(false),
80 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080081 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070082 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070083 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070084 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070085 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070086 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070087 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000088 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010089 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070090 mLastTemplateId(-1),
91 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080092{
93 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080094 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080095}
96
97Camera3Device::~Camera3Device()
98{
99 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800100 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700101 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102}
103
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800104const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800105 return mId;
106}
107
Emilian Peevbd8c5032018-02-14 23:05:40 +0000108status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800109 ATRACE_CALL();
110 Mutex::Autolock il(mInterfaceLock);
111 Mutex::Autolock l(mLock);
112
113 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
114 if (mStatus != STATUS_UNINITIALIZED) {
115 CLOGE("Already initialized!");
116 return INVALID_OPERATION;
117 }
118 if (manager == nullptr) return INVALID_OPERATION;
119
120 sp<ICameraDeviceSession> session;
121 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800122 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 /*out*/ &session);
124 ATRACE_END();
125 if (res != OK) {
126 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
127 return res;
128 }
129
Steven Moreland5ff9c912017-03-09 23:13:00 -0800130 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800131 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700132 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800133 session->close();
134 return res;
135 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800136 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800137
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700138 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700139 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700140 if (isLogical) {
141 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700142 res = manager->getCameraCharacteristics(
143 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700144 if (res != OK) {
145 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
146 physicalId.c_str(), strerror(-res), res);
147 session->close();
148 return res;
149 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700150
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800151 bool usePrecorrectArray =
152 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
153 if (usePrecorrectArray) {
154 res = mDistortionMappers[physicalId].setupStaticInfo(
155 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700156 if (res != OK) {
157 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
158 "correction", physicalId.c_str());
159 session->close();
160 return res;
161 }
162 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800163
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800164 mZoomRatioMappers[physicalId] = ZoomRatioMapper(
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800165 &mPhysicalDeviceInfoMap[physicalId],
166 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700167 }
168 }
169
Yifan Hongf79b5542017-04-11 14:44:25 -0700170 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700171 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
172 [&queue](const auto& descriptor) {
173 queue = std::make_shared<RequestMetadataQueue>(descriptor);
174 if (!queue->isValid() || queue->availableToWrite() <= 0) {
175 ALOGE("HAL returns empty request metadata fmq, not use it");
176 queue = nullptr;
177 // don't use the queue onwards.
178 }
179 });
180 if (!requestQueueRet.isOk()) {
181 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
182 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700183 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700184 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700185
186 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700187 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700188 [&resQueue](const auto& descriptor) {
189 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
190 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700191 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700192 resQueue = nullptr;
193 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700194 }
195 });
196 if (!resultQueueRet.isOk()) {
197 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
198 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700199 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700200 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700201 IF_ALOGV() {
202 session->interfaceChain([](
203 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
204 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800205 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700206 ALOGV(" %s", iface.c_str());
207 }
208 });
209 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700210
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800211 camera_metadata_entry bufMgrMode =
212 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
213 if (bufMgrMode.count > 0) {
214 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
215 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
216 }
217
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700218 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
219 for (size_t i = 0; i < capabilities.count; i++) {
220 uint8_t capability = capabilities.data.u8[i];
221 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
222 mSupportOfflineProcessing = true;
223 }
224 }
225
226 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000227 std::string providerType;
228 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000229 mTagMonitor.initialize(mVendorTagId);
230 if (!monitorTags.isEmpty()) {
231 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
232 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800233
Shuzhen Wang268a1362018-10-16 16:32:59 -0700234 // Metadata tags needs fixup for monochrome camera device version less
235 // than 3.5.
236 hardware::hidl_version maxVersion{0,0};
237 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
238 if (res != OK) {
239 ALOGE("%s: Error in getting camera device version id: %s (%d)",
240 __FUNCTION__, strerror(-res), res);
241 return res;
242 }
243 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
244 maxVersion.get_major(), maxVersion.get_minor());
245
246 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700247 for (size_t i = 0; i < capabilities.count; i++) {
248 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700249 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
250 isMonochrome = true;
251 }
252 }
253 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
254
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800255 return initializeCommonLocked();
256}
257
258status_t Camera3Device::initializeCommonLocked() {
259
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700260 /** Start up status tracker thread */
261 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800262 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700263 if (res != OK) {
264 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
265 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800266 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700267 mStatusTracker.clear();
268 return res;
269 }
270
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700271 /** Register in-flight map to the status tracker */
272 mInFlightStatusId = mStatusTracker->addComponent();
273
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700274 if (mUseHalBufManager) {
275 res = mRequestBufferSM.initialize(mStatusTracker);
276 if (res != OK) {
277 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
278 strerror(-res), res);
279 mInterface->close();
280 mStatusTracker.clear();
281 return res;
282 }
283 }
284
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800285 /** Create buffer manager */
286 mBufferManager = new Camera3BufferManager();
287
288 Vector<int32_t> sessionParamKeys;
289 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
290 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
291 if (sessionKeysEntry.count > 0) {
292 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
293 }
294
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700295 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700296 mRequestThread = new RequestThread(
297 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800298 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800299 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700300 SET_ERR_L("Unable to start request queue thread: %s (%d)",
301 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800302 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800303 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800304 return res;
305 }
306
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700307 mPreparerThread = new PreparerThread();
308
Ruben Brunk183f0562015-08-12 12:55:02 -0700309 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800310 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700311 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700312 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700313 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800314
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800315 // Measure the clock domain offset between camera and video/hw_composer
316 camera_metadata_entry timestampSource =
317 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
318 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
319 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
320 mTimestampOffset = getMonoToBoottimeOffset();
321 }
322
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700323 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100324 camera_metadata_entry partialResultsCount =
325 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
326 if (partialResultsCount.count > 0) {
327 mNumPartialResults = partialResultsCount.data.i32[0];
328 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700329 }
330
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700331 camera_metadata_entry configs =
332 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
333 for (uint32_t i = 0; i < configs.count; i += 4) {
334 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
335 configs.data.i32[i + 3] ==
336 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
337 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
338 configs.data.i32[i + 2]));
339 }
340 }
341
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800342 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
343 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700344 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700345 if (res != OK) {
346 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
347 return res;
348 }
349 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800350
Shuzhen Wang1c834da2019-12-18 11:17:03 -0800351 mZoomRatioMappers[mId.c_str()] = ZoomRatioMapper(&mDeviceInfo,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800352 mSupportNativeZoomRatio, usePrecorrectArray);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800353
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800354 if (RotateAndCropMapper::isNeeded(&mDeviceInfo)) {
355 mRotateAndCropMappers.emplace(mId.c_str(), &mDeviceInfo);
356 }
357
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800358 return OK;
359}
360
361status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700362 return disconnectImpl();
363}
364
365status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800366 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700367 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800368
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700369 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700370 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700371 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800372 Mutex::Autolock il(mInterfaceLock);
373 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
374 {
375 Mutex::Autolock l(mLock);
376 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700377
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800378 if (mStatus == STATUS_ACTIVE ||
379 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
380 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700381 if (res != OK) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800382 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700383 // Continue to close device even in case of error
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800384 } else {
385 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
386 if (res != OK) {
387 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
388 maxExpectedDuration);
389 // Continue to close device even in case of error
390 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700391 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700392 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800393
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800394 if (mStatus == STATUS_ERROR) {
395 CLOGE("Shutting down in an error state");
396 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700397
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800398 if (mStatusTracker != NULL) {
399 mStatusTracker->requestExit();
400 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700401
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800402 if (mRequestThread != NULL) {
403 mRequestThread->requestExit();
404 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700405
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800406 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
407 for (size_t i = 0; i < mOutputStreams.size(); i++) {
408 streams.push_back(mOutputStreams[i]);
409 }
410 if (mInputStream != nullptr) {
411 streams.push_back(mInputStream);
412 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700413 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700414 }
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800415 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
416 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700417 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
418 // HAL may be in a bad state, so waiting for request thread
419 // (which may be stuck in the HAL processCaptureRequest call)
420 // could be dangerous.
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800421 // give up mInterfaceLock here and then lock it again. Could this lead
422 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700423 mRequestThread->join();
424 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700425 {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800426 Mutex::Autolock il(mInterfaceLock);
427 if (mStatusTracker != NULL) {
428 mStatusTracker->join();
429 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800430
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800431 HalInterface* interface;
432 {
433 Mutex::Autolock l(mLock);
434 mRequestThread.clear();
435 Mutex::Autolock stLock(mTrackerLock);
436 mStatusTracker.clear();
437 interface = mInterface.get();
438 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700439
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800440 // Call close without internal mutex held, as the HAL close may need to
441 // wait on assorted callbacks,etc, to complete before it can return.
442 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700443
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800444 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800445
Jayant Chowdhary646c31b2020-01-30 13:09:59 -0800446 {
447 Mutex::Autolock l(mLock);
448 mInterface->clear();
449 mOutputStreams.clear();
450 mInputStream.clear();
451 mDeletedStreams.clear();
452 mBufferManager.clear();
453 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
454 }
455
456 for (auto& weakStream : streams) {
457 sp<Camera3StreamInterface> stream = weakStream.promote();
458 if (stream != nullptr) {
459 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
460 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
461 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700462 }
463 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700464 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700465 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800466}
467
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700468// For dumping/debugging only -
469// try to acquire a lock a few times, eventually give up to proceed with
470// debug/dump operations
471bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
472 bool gotLock = false;
473 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
474 if (lock.tryLock() == NO_ERROR) {
475 gotLock = true;
476 break;
477 } else {
478 usleep(kDumpSleepDuration);
479 }
480 }
481 return gotLock;
482}
483
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700484Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
485 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100486 const int STREAM_CONFIGURATION_SIZE = 4;
487 const int STREAM_FORMAT_OFFSET = 0;
488 const int STREAM_WIDTH_OFFSET = 1;
489 const int STREAM_HEIGHT_OFFSET = 2;
490 const int STREAM_IS_INPUT_OFFSET = 3;
491 camera_metadata_ro_entry_t availableStreamConfigs =
492 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
493 if (availableStreamConfigs.count == 0 ||
494 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
495 return Size(0, 0);
496 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700497
Emilian Peev08dd2452017-04-06 16:55:14 +0100498 // Get max jpeg size (area-wise).
499 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
500 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
501 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
502 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
503 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
504 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
505 && format == HAL_PIXEL_FORMAT_BLOB &&
506 (width * height > maxJpegWidth * maxJpegHeight)) {
507 maxJpegWidth = width;
508 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700509 }
510 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100511
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700512 return Size(maxJpegWidth, maxJpegHeight);
513}
514
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800515nsecs_t Camera3Device::getMonoToBoottimeOffset() {
516 // try three times to get the clock offset, choose the one
517 // with the minimum gap in measurements.
518 const int tries = 3;
519 nsecs_t bestGap, measured;
520 for (int i = 0; i < tries; ++i) {
521 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
522 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
523 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
524 const nsecs_t gap = tmono2 - tmono;
525 if (i == 0 || gap < bestGap) {
526 bestGap = gap;
527 measured = tbase - ((tmono + tmono2) >> 1);
528 }
529 }
530 return measured;
531}
532
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800533hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
534 int frameworkFormat) {
535 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
536}
537
538DataspaceFlags Camera3Device::mapToHidlDataspace(
539 android_dataspace dataSpace) {
540 return dataSpace;
541}
542
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700543BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100544 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700545 return usage;
546}
547
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800548StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
549 switch (rotation) {
550 case CAMERA3_STREAM_ROTATION_0:
551 return StreamRotation::ROTATION_0;
552 case CAMERA3_STREAM_ROTATION_90:
553 return StreamRotation::ROTATION_90;
554 case CAMERA3_STREAM_ROTATION_180:
555 return StreamRotation::ROTATION_180;
556 case CAMERA3_STREAM_ROTATION_270:
557 return StreamRotation::ROTATION_270;
558 }
559 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
560 return StreamRotation::ROTATION_0;
561}
562
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800563status_t Camera3Device::mapToStreamConfigurationMode(
564 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
565 if (mode == nullptr) return BAD_VALUE;
566 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
567 switch(operationMode) {
568 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
569 *mode = StreamConfigurationMode::NORMAL_MODE;
570 break;
571 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
572 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
573 break;
574 default:
575 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
576 return BAD_VALUE;
577 }
578 } else {
579 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800580 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800581 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800582}
583
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800584int Camera3Device::mapToFrameworkFormat(
585 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
586 return static_cast<uint32_t>(pixelFormat);
587}
588
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700589android_dataspace Camera3Device::mapToFrameworkDataspace(
590 DataspaceFlags dataSpace) {
591 return static_cast<android_dataspace>(dataSpace);
592}
593
Emilian Peev050f5dc2017-05-18 14:43:56 +0100594uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700595 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700596 return usage;
597}
598
Emilian Peev050f5dc2017-05-18 14:43:56 +0100599uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700600 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700601 return usage;
602}
603
Zhijun Hef7da0962014-04-24 13:27:56 -0700604ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700605 // Get max jpeg size (area-wise).
606 Size maxJpegResolution = getMaxJpegResolution();
607 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800608 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
609 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700610 return BAD_VALUE;
611 }
612
Zhijun Hef7da0962014-04-24 13:27:56 -0700613 // Get max jpeg buffer size
614 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700615 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
616 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800617 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
618 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700619 return BAD_VALUE;
620 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700621 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800622 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700623
624 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700625 float scaleFactor = ((float) (width * height)) /
626 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800627 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
628 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700629 if (jpegBufferSize > maxJpegBufferSize) {
630 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700631 }
632
633 return jpegBufferSize;
634}
635
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700636ssize_t Camera3Device::getPointCloudBufferSize() const {
637 const int FLOATS_PER_POINT=4;
638 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
639 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800640 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
641 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700642 return BAD_VALUE;
643 }
644 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
645 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
646 return maxBytesForPointCloud;
647}
648
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800649ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800650 const int PER_CONFIGURATION_SIZE = 3;
651 const int WIDTH_OFFSET = 0;
652 const int HEIGHT_OFFSET = 1;
653 const int SIZE_OFFSET = 2;
654 camera_metadata_ro_entry rawOpaqueSizes =
655 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800656 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800657 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800658 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
659 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800660 return BAD_VALUE;
661 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700662
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800663 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
664 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
665 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
666 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
667 }
668 }
669
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800670 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
671 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800672 return BAD_VALUE;
673}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700674
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800675status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
676 ATRACE_CALL();
677 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700678
679 // Try to lock, but continue in case of failure (to avoid blocking in
680 // deadlocks)
681 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
682 bool gotLock = tryLockSpinRightRound(mLock);
683
684 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800685 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
686 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700687 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800688 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
689 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700690
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800691 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700692
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800693 String16 templatesOption("-t");
694 int n = args.size();
695 for (int i = 0; i < n; i++) {
696 if (args[i] == templatesOption) {
697 dumpTemplates = true;
698 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000699 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700700 if (i + 1 < n) {
701 String8 monitorTags = String8(args[i + 1]);
702 if (monitorTags == "off") {
703 mTagMonitor.disableMonitoring();
704 } else {
705 mTagMonitor.parseTagsToMonitor(monitorTags);
706 }
707 } else {
708 mTagMonitor.disableMonitoring();
709 }
710 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800711 }
712
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800713 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800714
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800715 const char *status =
716 mStatus == STATUS_ERROR ? "ERROR" :
717 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700718 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
719 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800720 mStatus == STATUS_ACTIVE ? "ACTIVE" :
721 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700722
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800723 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700724 if (mStatus == STATUS_ERROR) {
725 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
726 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800727 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800728 const char *mode =
729 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
730 mOperatingMode == static_cast<int>(
731 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
732 "CUSTOM";
733 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800734
735 if (mInputStream != NULL) {
736 write(fd, lines.string(), lines.size());
737 mInputStream->dump(fd, args);
738 } else {
739 lines.appendFormat(" No input stream.\n");
740 write(fd, lines.string(), lines.size());
741 }
742 for (size_t i = 0; i < mOutputStreams.size(); i++) {
743 mOutputStreams[i]->dump(fd,args);
744 }
745
Zhijun He431503c2016-03-07 17:30:16 -0800746 if (mBufferManager != NULL) {
747 lines = String8(" Camera3 Buffer Manager:\n");
748 write(fd, lines.string(), lines.size());
749 mBufferManager->dump(fd, args);
750 }
Zhijun He125684a2015-12-26 15:07:30 -0800751
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700752 lines = String8(" In-flight requests:\n");
753 if (mInFlightMap.size() == 0) {
754 lines.append(" None\n");
755 } else {
756 for (size_t i = 0; i < mInFlightMap.size(); i++) {
757 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700758 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700759 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800760 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700761 r.numBuffersLeft);
762 }
763 }
764 write(fd, lines.string(), lines.size());
765
Shuzhen Wang686f6442017-06-20 16:16:04 -0700766 if (mRequestThread != NULL) {
767 mRequestThread->dumpCaptureRequestLatency(fd,
768 " ProcessCaptureRequest latency histogram:");
769 }
770
Igor Murashkin1e479c02013-09-06 16:55:14 -0700771 {
772 lines = String8(" Last request sent:\n");
773 write(fd, lines.string(), lines.size());
774
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700775 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700776 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
777 }
778
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800779 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800780 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800781 "TEMPLATE_PREVIEW",
782 "TEMPLATE_STILL_CAPTURE",
783 "TEMPLATE_VIDEO_RECORD",
784 "TEMPLATE_VIDEO_SNAPSHOT",
785 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800786 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800787 };
788
789 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800790 camera_metadata_t *templateRequest = nullptr;
791 mInterface->constructDefaultRequestSettings(
792 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800793 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800794 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800795 lines.append(" Not supported\n");
796 write(fd, lines.string(), lines.size());
797 } else {
798 write(fd, lines.string(), lines.size());
799 dump_indented_camera_metadata(templateRequest,
800 fd, /*verbosity*/2, /*indentation*/8);
801 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800802 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800803 }
804 }
805
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700806 mTagMonitor.dumpMonitoredMetadata(fd);
807
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800808 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800809 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800810 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800811 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800812 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800813
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700814 if (gotLock) mLock.unlock();
815 if (gotInterfaceLock) mInterfaceLock.unlock();
816
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800817 return OK;
818}
819
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800820const CameraMetadata& Camera3Device::infoPhysical(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800821 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800822 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
823 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700824 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800825 mStatus == STATUS_ERROR ?
826 "when in error state" : "before init");
827 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700828 if (physicalId.isEmpty()) {
829 return mDeviceInfo;
830 } else {
831 std::string id(physicalId.c_str());
832 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
833 return mPhysicalDeviceInfoMap.at(id);
834 } else {
835 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
836 return mDeviceInfo;
837 }
838 }
839}
840
841const CameraMetadata& Camera3Device::info() const {
842 String8 emptyId;
Emilian Peevfaa4bde2020-01-23 12:19:37 -0800843 return infoPhysical(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800844}
845
Jianing Wei90e59c92014-03-12 18:29:36 -0700846status_t Camera3Device::checkStatusOkToCaptureLocked() {
847 switch (mStatus) {
848 case STATUS_ERROR:
849 CLOGE("Device has encountered a serious error");
850 return INVALID_OPERATION;
851 case STATUS_UNINITIALIZED:
852 CLOGE("Device not initialized");
853 return INVALID_OPERATION;
854 case STATUS_UNCONFIGURED:
855 case STATUS_CONFIGURED:
856 case STATUS_ACTIVE:
857 // OK
858 break;
859 default:
860 SET_ERR_L("Unexpected status: %d", mStatus);
861 return INVALID_OPERATION;
862 }
863 return OK;
864}
865
866status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000867 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700868 const std::list<const SurfaceMap> &surfaceMaps,
869 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700870 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700871 if (requestList == NULL) {
872 CLOGE("requestList cannot be NULL.");
873 return BAD_VALUE;
874 }
875
Jianing Weicb0652e2014-03-12 18:29:36 -0700876 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000877 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700878 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
879 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
880 ++metadataIt, ++surfaceMapIt) {
881 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700882 if (newRequest == 0) {
883 CLOGE("Can't create capture request");
884 return BAD_VALUE;
885 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700886
Shuzhen Wang9d066012016-09-30 11:30:20 -0700887 newRequest->mRepeating = repeating;
888
Jianing Weicb0652e2014-03-12 18:29:36 -0700889 // Setup burst Id and request Id
890 newRequest->mResultExtras.burstId = burstId++;
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800891 auto requestIdEntry = metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID);
892 if (requestIdEntry.count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700893 CLOGE("RequestID does not exist in metadata");
894 return BAD_VALUE;
895 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -0800896 newRequest->mResultExtras.requestId = requestIdEntry.data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700897
Jianing Wei90e59c92014-03-12 18:29:36 -0700898 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700899
900 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700901 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700902 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
903 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
904 return BAD_VALUE;
905 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700906
907 // Setup batch size if this is a high speed video recording request.
908 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
909 auto firstRequest = requestList->begin();
910 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
911 if (outputStream->isVideoStream()) {
912 (*firstRequest)->mBatchSize = requestList->size();
913 break;
914 }
915 }
916 }
917
Jianing Wei90e59c92014-03-12 18:29:36 -0700918 return OK;
919}
920
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800921status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800922 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800923
Emilian Peevaebbe412018-01-15 13:53:24 +0000924 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700925 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000926 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700927
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800928 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700929}
930
Emilian Peevaebbe412018-01-15 13:53:24 +0000931void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700932 std::list<const SurfaceMap>& surfaceMaps,
933 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000934 PhysicalCameraSettingsList requestList;
935 requestList.push_back({std::string(getId().string()), request});
936 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700937
938 SurfaceMap surfaceMap;
939 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
940 // With no surface list passed in, stream and surface will have 1-to-1
941 // mapping. So the surface index is 0 for each stream in the surfaceMap.
942 for (size_t i = 0; i < streams.count; i++) {
943 surfaceMap[streams.data.i32[i]].push_back(0);
944 }
945 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800946}
947
Jianing Wei90e59c92014-03-12 18:29:36 -0700948status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000949 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700950 const std::list<const SurfaceMap> &surfaceMaps,
951 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700952 /*out*/
953 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700954 ATRACE_CALL();
955 Mutex::Autolock il(mInterfaceLock);
956 Mutex::Autolock l(mLock);
957
958 status_t res = checkStatusOkToCaptureLocked();
959 if (res != OK) {
960 // error logged by previous call
961 return res;
962 }
963
964 RequestList requestList;
965
Shuzhen Wang0129d522016-10-30 22:43:41 -0700966 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
967 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700968 if (res != OK) {
969 // error logged by previous call
970 return res;
971 }
972
973 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700974 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700975 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700976 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700977 }
978
979 if (res == OK) {
980 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
981 if (res != OK) {
982 SET_ERR_L("Can't transition to active in %f seconds!",
983 kActiveTimeout/1e9);
984 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800985 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700986 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700987 } else {
988 CLOGE("Cannot queue request. Impossible.");
989 return BAD_VALUE;
990 }
991
992 return res;
993}
994
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700995hardware::Return<void> Camera3Device::requestStreamBuffers(
996 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
997 requestStreamBuffers_cb _hidl_cb) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -0800998 RequestBufferStates states {
999 mId, mRequestBufferInterfaceLock, mUseHalBufManager, mOutputStreams,
1000 *this, *mInterface, *this};
1001 camera3::requestStreamBuffers(states, bufReqs, _hidl_cb);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001002 return hardware::Void();
1003}
1004
1005hardware::Return<void> Camera3Device::returnStreamBuffers(
1006 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001007 ReturnBufferStates states {
1008 mId, mUseHalBufManager, mOutputStreams, *mInterface};
1009 camera3::returnStreamBuffers(states, buffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001010 return hardware::Void();
1011}
1012
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001013hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001014 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001015 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001016 // Ideally we should grab mLock, but that can lead to deadlock, and
1017 // it's not super important to get up to date value of mStatus for this
1018 // warning print, hence skipping the lock here
1019 if (mStatus == STATUS_ERROR) {
1020 // Per API contract, HAL should act as closed after device error
1021 // But mStatus can be set to error by framework as well, so just log
1022 // a warning here.
1023 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001024 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001025
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001026 sp<NotificationListener> listener;
1027 {
1028 std::lock_guard<std::mutex> l(mOutputLock);
1029 listener = mListener.promote();
1030 }
1031
Yifan Honga640c5a2017-04-12 16:30:31 -07001032 if (mProcessCaptureResultLock.tryLock() != OK) {
1033 // This should never happen; it indicates a wrong client implementation
1034 // that doesn't follow the contract. But, we can be tolerant here.
1035 ALOGE("%s: callback overlapped! waiting 1s...",
1036 __FUNCTION__);
1037 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1038 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1039 __FUNCTION__);
1040 // really don't know what to do, so bail out.
1041 return hardware::Void();
1042 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001043 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001044 CaptureOutputStates states {
1045 mId,
1046 mInFlightLock, mInFlightMap,
1047 mOutputLock, mResultQueue, mResultSignal,
1048 mNextShutterFrameNumber,
1049 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1050 mNextResultFrameNumber,
1051 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1052 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1053 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001054 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1055 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001056 };
1057
Yifan Honga640c5a2017-04-12 16:30:31 -07001058 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001059 processOneCaptureResultLocked(states, result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001060 }
1061 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001062 return hardware::Void();
1063}
1064
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001065// Only one processCaptureResult should be called at a time, so
1066// the locks won't block. The locks are present here simply to enforce this.
1067hardware::Return<void> Camera3Device::processCaptureResult(
1068 const hardware::hidl_vec<
1069 hardware::camera::device::V3_2::CaptureResult>& results) {
1070 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1071
1072 // Ideally we should grab mLock, but that can lead to deadlock, and
1073 // it's not super important to get up to date value of mStatus for this
1074 // warning print, hence skipping the lock here
1075 if (mStatus == STATUS_ERROR) {
1076 // Per API contract, HAL should act as closed after device error
1077 // But mStatus can be set to error by framework as well, so just log
1078 // a warning here.
1079 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1080 }
1081
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001082 sp<NotificationListener> listener;
1083 {
1084 std::lock_guard<std::mutex> l(mOutputLock);
1085 listener = mListener.promote();
1086 }
1087
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001088 if (mProcessCaptureResultLock.tryLock() != OK) {
1089 // This should never happen; it indicates a wrong client implementation
1090 // that doesn't follow the contract. But, we can be tolerant here.
1091 ALOGE("%s: callback overlapped! waiting 1s...",
1092 __FUNCTION__);
1093 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1094 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1095 __FUNCTION__);
1096 // really don't know what to do, so bail out.
1097 return hardware::Void();
1098 }
1099 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001100
1101 CaptureOutputStates states {
1102 mId,
1103 mInFlightLock, mInFlightMap,
1104 mOutputLock, mResultQueue, mResultSignal,
1105 mNextShutterFrameNumber,
1106 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1107 mNextResultFrameNumber,
1108 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1109 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1110 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001111 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1112 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001113 };
1114
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001115 for (const auto& result : results) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001116 processOneCaptureResultLocked(states, result, noPhysMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001117 }
1118 mProcessCaptureResultLock.unlock();
1119 return hardware::Void();
1120}
1121
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001122hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001123 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001124 // Ideally we should grab mLock, but that can lead to deadlock, and
1125 // it's not super important to get up to date value of mStatus for this
1126 // warning print, hence skipping the lock here
1127 if (mStatus == STATUS_ERROR) {
1128 // Per API contract, HAL should act as closed after device error
1129 // But mStatus can be set to error by framework as well, so just log
1130 // a warning here.
1131 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001132 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001133
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001134 sp<NotificationListener> listener;
1135 {
1136 std::lock_guard<std::mutex> l(mOutputLock);
1137 listener = mListener.promote();
1138 }
1139
1140 CaptureOutputStates states {
1141 mId,
1142 mInFlightLock, mInFlightMap,
1143 mOutputLock, mResultQueue, mResultSignal,
1144 mNextShutterFrameNumber,
1145 mNextReprocessShutterFrameNumber, mNextZslStillShutterFrameNumber,
1146 mNextResultFrameNumber,
1147 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
1148 mUseHalBufManager, mUsePartialResult, mNeedFixupMonochromeTags,
1149 mNumPartialResults, mVendorTagId, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08001150 mResultMetadataQueue, mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers,
1151 mTagMonitor, mInputStream, mOutputStreams, listener, *this, *this, *mInterface
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001152 };
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001153 for (const auto& msg : msgs) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001154 camera3::notify(states, msg);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001155 }
1156 return hardware::Void();
1157}
1158
Emilian Peevaebbe412018-01-15 13:53:24 +00001159status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001160 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001161 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001162 ATRACE_CALL();
1163
Emilian Peevaebbe412018-01-15 13:53:24 +00001164 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001165}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001166
Jianing Weicb0652e2014-03-12 18:29:36 -07001167status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1168 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001169 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001170
Emilian Peevaebbe412018-01-15 13:53:24 +00001171 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001172 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001173 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001174
Emilian Peevaebbe412018-01-15 13:53:24 +00001175 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001176 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001177}
1178
Emilian Peevaebbe412018-01-15 13:53:24 +00001179status_t Camera3Device::setStreamingRequestList(
1180 const List<const PhysicalCameraSettingsList> &requestsList,
1181 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001182 ATRACE_CALL();
1183
Emilian Peevaebbe412018-01-15 13:53:24 +00001184 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001185}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001186
1187sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001188 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001189 status_t res;
1190
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001191 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001192 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1193 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001194 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1195 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001196 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001197 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001198 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001199 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001200 } else if (mStatus == STATUS_UNCONFIGURED) {
1201 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001202 CLOGE("No streams configured");
1203 return NULL;
1204 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001205 }
1206
Shuzhen Wang0129d522016-10-30 22:43:41 -07001207 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001208 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001209}
1210
Jianing Weicb0652e2014-03-12 18:29:36 -07001211status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001212 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001213 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001214 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001215
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001216 switch (mStatus) {
1217 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001218 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001219 return INVALID_OPERATION;
1220 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001221 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001223 case STATUS_UNCONFIGURED:
1224 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225 case STATUS_ACTIVE:
1226 // OK
1227 break;
1228 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001229 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001230 return INVALID_OPERATION;
1231 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001232 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001233
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001234 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001235}
1236
1237status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1238 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001239 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001240
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001241 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001242}
1243
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001244status_t Camera3Device::createInputStream(
1245 uint32_t width, uint32_t height, int format, int *id) {
1246 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001247 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001248 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001249 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001250 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1251 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001252
1253 status_t res;
1254 bool wasActive = false;
1255
1256 switch (mStatus) {
1257 case STATUS_ERROR:
1258 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1259 return INVALID_OPERATION;
1260 case STATUS_UNINITIALIZED:
1261 ALOGE("%s: Device not initialized", __FUNCTION__);
1262 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001263 case STATUS_UNCONFIGURED:
1264 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001265 // OK
1266 break;
1267 case STATUS_ACTIVE:
1268 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001269 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001270 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001271 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001272 return res;
1273 }
1274 wasActive = true;
1275 break;
1276 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001277 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001278 return INVALID_OPERATION;
1279 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001280 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001281
1282 if (mInputStream != 0) {
1283 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1284 return INVALID_OPERATION;
1285 }
1286
1287 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1288 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001289 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001290
1291 mInputStream = newStream;
1292
1293 *id = mNextStreamId++;
1294
1295 // Continue captures if active at start
1296 if (wasActive) {
1297 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001298 // Reuse current operating mode and session parameters for new stream config
1299 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001300 if (res != OK) {
1301 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1302 __FUNCTION__, mNextStreamId, strerror(-res), res);
1303 return res;
1304 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001305 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001306 }
1307
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001308 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001309 return OK;
1310}
1311
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001312status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001313 uint32_t width, uint32_t height, int format,
1314 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001315 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001316 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001317 ATRACE_CALL();
1318
1319 if (consumer == nullptr) {
1320 ALOGE("%s: consumer must not be null", __FUNCTION__);
1321 return BAD_VALUE;
1322 }
1323
1324 std::vector<sp<Surface>> consumers;
1325 consumers.push_back(consumer);
1326
1327 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001328 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1329 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001330}
1331
1332status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1333 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1334 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001335 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001336 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001337 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001338
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001339 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001340 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001341 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001342 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001343 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1344 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1345 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001346
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001347 status_t res;
1348 bool wasActive = false;
1349
1350 switch (mStatus) {
1351 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001352 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001353 return INVALID_OPERATION;
1354 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001355 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001356 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001357 case STATUS_UNCONFIGURED:
1358 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001359 // OK
1360 break;
1361 case STATUS_ACTIVE:
1362 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001363 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001364 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001365 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001366 return res;
1367 }
1368 wasActive = true;
1369 break;
1370 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001371 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001372 return INVALID_OPERATION;
1373 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001374 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001375
1376 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001377
Shuzhen Wang0129d522016-10-30 22:43:41 -07001378 if (consumers.size() == 0 && !hasDeferredConsumer) {
1379 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1380 return BAD_VALUE;
1381 }
Zhijun He5d677d12016-05-29 16:52:39 -07001382
Shuzhen Wang0129d522016-10-30 22:43:41 -07001383 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001384 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1385 return BAD_VALUE;
1386 }
1387
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001388 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001389 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001390 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001391 blobBufferSize = getPointCloudBufferSize();
1392 if (blobBufferSize <= 0) {
1393 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1394 return BAD_VALUE;
1395 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001396 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1397 blobBufferSize = width * height;
1398 } else {
1399 blobBufferSize = getJpegBufferSize(width, height);
1400 if (blobBufferSize <= 0) {
1401 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1402 return BAD_VALUE;
1403 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001404 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001405 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001406 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001407 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001408 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1409 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1410 if (rawOpaqueBufferSize <= 0) {
1411 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1412 return BAD_VALUE;
1413 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001414 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001415 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001416 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001417 } else if (isShared) {
1418 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1419 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001420 mTimestampOffset, physicalCameraId, streamSetId,
1421 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001422 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001423 newStream = new Camera3OutputStream(mNextStreamId,
1424 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001425 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001426 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001427 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001428 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001429 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001430 }
Emilian Peev40ead602017-09-26 15:46:36 +01001431
1432 size_t consumerCount = consumers.size();
1433 for (size_t i = 0; i < consumerCount; i++) {
1434 int id = newStream->getSurfaceId(consumers[i]);
1435 if (id < 0) {
1436 SET_ERR_L("Invalid surface id");
1437 return BAD_VALUE;
1438 }
1439 if (surfaceIds != nullptr) {
1440 surfaceIds->push_back(id);
1441 }
1442 }
1443
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001444 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001445
Emilian Peev08dd2452017-04-06 16:55:14 +01001446 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001447
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001448 res = mOutputStreams.add(mNextStreamId, newStream);
1449 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001450 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001451 return res;
1452 }
1453
1454 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001455 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456
1457 // Continue captures if active at start
1458 if (wasActive) {
1459 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001460 // Reuse current operating mode and session parameters for new stream config
1461 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001462 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001463 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1464 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001465 return res;
1466 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001467 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001468 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001469 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001471}
1472
Emilian Peev710c1422017-08-30 11:19:38 +01001473status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001474 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001475 if (nullptr == streamInfo) {
1476 return BAD_VALUE;
1477 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001478 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001479 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001480
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 switch (mStatus) {
1482 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001483 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 return INVALID_OPERATION;
1485 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001486 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001487 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001488 case STATUS_UNCONFIGURED:
1489 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001490 case STATUS_ACTIVE:
1491 // OK
1492 break;
1493 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001494 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 return INVALID_OPERATION;
1496 }
1497
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001498 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1499 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001500 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001501 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502 }
1503
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001504 streamInfo->width = stream->getWidth();
1505 streamInfo->height = stream->getHeight();
1506 streamInfo->format = stream->getFormat();
1507 streamInfo->dataSpace = stream->getDataSpace();
1508 streamInfo->formatOverridden = stream->isFormatOverridden();
1509 streamInfo->originalFormat = stream->getOriginalFormat();
1510 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1511 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001512 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001513}
1514
1515status_t Camera3Device::setStreamTransform(int id,
1516 int transform) {
1517 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001518 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001519 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001520
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 switch (mStatus) {
1522 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001523 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001524 return INVALID_OPERATION;
1525 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001526 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001527 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001528 case STATUS_UNCONFIGURED:
1529 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530 case STATUS_ACTIVE:
1531 // OK
1532 break;
1533 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001534 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001535 return INVALID_OPERATION;
1536 }
1537
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001538 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1539 if (stream == nullptr) {
1540 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001541 return BAD_VALUE;
1542 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001543 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001544}
1545
1546status_t Camera3Device::deleteStream(int id) {
1547 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001548 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001549 Mutex::Autolock l(mLock);
1550 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001551
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001552 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001553
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 // CameraDevice semantics require device to already be idle before
1555 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001556 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001557 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001558 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001559 }
1560
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001561 if (mStatus == STATUS_ERROR) {
1562 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1563 __FUNCTION__, mId.string());
1564 return -EBUSY;
1565 }
1566
Igor Murashkin2fba5842013-04-22 14:03:54 -07001567 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001568 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 if (mInputStream != NULL && id == mInputStream->getId()) {
1570 deletedStream = mInputStream;
1571 mInputStream.clear();
1572 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001573 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001574 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 return BAD_VALUE;
1576 }
Zhijun He5f446352014-01-22 09:49:33 -08001577 }
1578
1579 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001580 if (stream != nullptr) {
1581 deletedStream = stream;
1582 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583 }
1584
1585 // Free up the stream endpoint so that it can be used by some other stream
1586 res = deletedStream->disconnect();
1587 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001588 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001589 // fall through since we want to still list the stream as deleted.
1590 }
1591 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001592 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593
1594 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001595}
1596
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001597status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001598 ATRACE_CALL();
1599 ALOGV("%s: E", __FUNCTION__);
1600
1601 Mutex::Autolock il(mInterfaceLock);
1602 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001603
Emilian Peev811d2952018-05-25 11:08:40 +01001604 // In case the client doesn't include any session parameter, try a
1605 // speculative configuration using the values from the last cached
1606 // default request.
1607 if (sessionParams.isEmpty() &&
1608 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1609 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1610 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1611 mLastTemplateId);
1612 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1613 operatingMode);
1614 }
1615
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001616 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1617}
1618
1619status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1620 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001621 //Filter out any incoming session parameters
1622 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001623 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1624 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001625 CameraMetadata filteredParams(availableSessionKeys.count);
1626 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1627 filteredParams.getAndLock());
1628 set_camera_metadata_vendor_id(meta, mVendorTagId);
1629 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001630 if (availableSessionKeys.count > 0) {
1631 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1632 camera_metadata_ro_entry entry = params.find(
1633 availableSessionKeys.data.i32[i]);
1634 if (entry.count > 0) {
1635 filteredParams.update(entry);
1636 }
1637 }
1638 }
1639
1640 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001641}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001642
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001643status_t Camera3Device::getInputBufferProducer(
1644 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001645 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001646 Mutex::Autolock il(mInterfaceLock);
1647 Mutex::Autolock l(mLock);
1648
1649 if (producer == NULL) {
1650 return BAD_VALUE;
1651 } else if (mInputStream == NULL) {
1652 return INVALID_OPERATION;
1653 }
1654
1655 return mInputStream->getInputBufferProducer(producer);
1656}
1657
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001658status_t Camera3Device::createDefaultRequest(int templateId,
1659 CameraMetadata *request) {
1660 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001661 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001662
1663 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1664 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001665 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001666 return BAD_VALUE;
1667 }
1668
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001669 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001670
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001671 {
1672 Mutex::Autolock l(mLock);
1673 switch (mStatus) {
1674 case STATUS_ERROR:
1675 CLOGE("Device has encountered a serious error");
1676 return INVALID_OPERATION;
1677 case STATUS_UNINITIALIZED:
1678 CLOGE("Device is not initialized!");
1679 return INVALID_OPERATION;
1680 case STATUS_UNCONFIGURED:
1681 case STATUS_CONFIGURED:
1682 case STATUS_ACTIVE:
1683 // OK
1684 break;
1685 default:
1686 SET_ERR_L("Unexpected status: %d", mStatus);
1687 return INVALID_OPERATION;
1688 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001689
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001690 if (!mRequestTemplateCache[templateId].isEmpty()) {
1691 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001692 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001693 return OK;
1694 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001695 }
1696
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001697 camera_metadata_t *rawRequest;
1698 status_t res = mInterface->constructDefaultRequestSettings(
1699 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001700
1701 {
1702 Mutex::Autolock l(mLock);
1703 if (res == BAD_VALUE) {
1704 ALOGI("%s: template %d is not supported on this camera device",
1705 __FUNCTION__, templateId);
1706 return res;
1707 } else if (res != OK) {
1708 CLOGE("Unable to construct request template %d: %s (%d)",
1709 templateId, strerror(-res), res);
1710 return res;
1711 }
1712
1713 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1714 mRequestTemplateCache[templateId].acquire(rawRequest);
1715
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08001716 // Override the template request with zoomRatioMapper
1717 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
1718 &mRequestTemplateCache[templateId]);
1719 if (res != OK) {
1720 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
1721 templateId, strerror(-res), res);
1722 return res;
1723 }
1724
Shuzhen Wangd25dc972020-03-24 17:11:43 -07001725 // Fill in JPEG_QUALITY if not available
1726 if (!mRequestTemplateCache[templateId].exists(ANDROID_JPEG_QUALITY)) {
1727 static const uint8_t kDefaultJpegQuality = 95;
1728 mRequestTemplateCache[templateId].update(ANDROID_JPEG_QUALITY,
1729 &kDefaultJpegQuality, 1);
1730 }
1731
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001732 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001733 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001734 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001735 return OK;
1736}
1737
1738status_t Camera3Device::waitUntilDrained() {
1739 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001740 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001741 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001742 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001743
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001744 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001745}
1746
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001747status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001748 switch (mStatus) {
1749 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001750 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001751 ALOGV("%s: Already idle", __FUNCTION__);
1752 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001753 case STATUS_CONFIGURED:
1754 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001755 case STATUS_ERROR:
1756 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001757 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001758 break;
1759 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001760 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001761 return INVALID_OPERATION;
1762 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001763 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1764 maxExpectedDuration);
1765 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001766 if (res != OK) {
1767 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1768 res);
1769 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001770 return res;
1771}
1772
Ruben Brunk183f0562015-08-12 12:55:02 -07001773
1774void Camera3Device::internalUpdateStatusLocked(Status status) {
1775 mStatus = status;
1776 mRecentStatusUpdates.add(mStatus);
1777 mStatusChanged.broadcast();
1778}
1779
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001780void Camera3Device::pauseStateNotify(bool enable) {
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08001781 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001782 Mutex::Autolock l(mLock);
1783
1784 mPauseStateNotify = enable;
1785}
1786
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001787// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001788status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08001789 if (mRequestThread.get() != nullptr) {
1790 mRequestThread->setPaused(true);
1791 } else {
1792 return NO_INIT;
1793 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001794
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001795 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1796 maxExpectedDuration);
1797 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001798 if (res != OK) {
1799 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001800 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001801 }
1802
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001803 return res;
1804}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001805
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001806// Resume after internalPauseAndWaitLocked
1807status_t Camera3Device::internalResumeLocked() {
1808 status_t res;
1809
1810 mRequestThread->setPaused(false);
1811
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001812 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1813 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001814 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1815 if (res != OK) {
1816 SET_ERR_L("Can't transition to active in %f seconds!",
1817 kActiveTimeout/1e9);
1818 }
1819 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001820 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001821}
1822
Ruben Brunk183f0562015-08-12 12:55:02 -07001823status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001824 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001825
1826 size_t startIndex = 0;
1827 if (mStatusWaiters == 0) {
1828 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1829 // this status list
1830 mRecentStatusUpdates.clear();
1831 } else {
1832 // If other threads are waiting on updates to this status list, set the position of the
1833 // first element that this list will check rather than clearing the list.
1834 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001835 }
1836
Ruben Brunk183f0562015-08-12 12:55:02 -07001837 mStatusWaiters++;
1838
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001839 if (!active && mUseHalBufManager) {
1840 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001841 if (mStatus == STATUS_ACTIVE) {
1842 mRequestThread->signalPipelineDrain(streamIds);
1843 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001844 mRequestBufferSM.onWaitUntilIdle();
1845 }
1846
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001847 bool stateSeen = false;
1848 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001849 if (active == (mStatus == STATUS_ACTIVE)) {
1850 // Desired state is current
1851 break;
1852 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001853
1854 res = mStatusChanged.waitRelative(mLock, timeout);
1855 if (res != OK) break;
1856
Ruben Brunk183f0562015-08-12 12:55:02 -07001857 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1858 // transitions.
1859 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1860 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1861 __FUNCTION__);
1862
1863 // Encountered desired state since we began waiting
1864 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001865 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1866 stateSeen = true;
1867 break;
1868 }
1869 }
1870 } while (!stateSeen);
1871
Ruben Brunk183f0562015-08-12 12:55:02 -07001872 mStatusWaiters--;
1873
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001874 return res;
1875}
1876
1877
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001878status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001879 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001880 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001881
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001882 if (listener != NULL && mListener != NULL) {
1883 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1884 }
1885 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001886 mRequestThread->setNotificationListener(listener);
1887 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001888
1889 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001890}
1891
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001892bool Camera3Device::willNotify3A() {
1893 return false;
1894}
1895
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001896status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001897 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001898 std::unique_lock<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001899
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001900 while (mResultQueue.empty()) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001901 auto st = mResultSignal.wait_for(l, std::chrono::nanoseconds(timeout));
1902 if (st == std::cv_status::timeout) {
1903 return TIMED_OUT;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001904 }
1905 }
1906 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001907}
1908
Jianing Weicb0652e2014-03-12 18:29:36 -07001909status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001910 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08001911 std::lock_guard<std::mutex> l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001912
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001913 if (mResultQueue.empty()) {
1914 return NOT_ENOUGH_DATA;
1915 }
1916
Jianing Weicb0652e2014-03-12 18:29:36 -07001917 if (frame == NULL) {
1918 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1919 return BAD_VALUE;
1920 }
1921
1922 CaptureResult &result = *(mResultQueue.begin());
1923 frame->mResultExtras = result.mResultExtras;
1924 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001925 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001926 mResultQueue.erase(mResultQueue.begin());
1927
1928 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001929}
1930
1931status_t Camera3Device::triggerAutofocus(uint32_t id) {
1932 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001933 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001934
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001935 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1936 // Mix-in this trigger into the next request and only the next request.
1937 RequestTrigger trigger[] = {
1938 {
1939 ANDROID_CONTROL_AF_TRIGGER,
1940 ANDROID_CONTROL_AF_TRIGGER_START
1941 },
1942 {
1943 ANDROID_CONTROL_AF_TRIGGER_ID,
1944 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001945 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001946 };
1947
1948 return mRequestThread->queueTrigger(trigger,
1949 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001950}
1951
1952status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1953 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001954 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001955
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001956 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1957 // Mix-in this trigger into the next request and only the next request.
1958 RequestTrigger trigger[] = {
1959 {
1960 ANDROID_CONTROL_AF_TRIGGER,
1961 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1962 },
1963 {
1964 ANDROID_CONTROL_AF_TRIGGER_ID,
1965 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001966 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001967 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001968
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001969 return mRequestThread->queueTrigger(trigger,
1970 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001971}
1972
1973status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1974 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001975 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001976
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001977 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1978 // Mix-in this trigger into the next request and only the next request.
1979 RequestTrigger trigger[] = {
1980 {
1981 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1982 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1983 },
1984 {
1985 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1986 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001987 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001988 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001989
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001990 return mRequestThread->queueTrigger(trigger,
1991 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001992}
1993
Jianing Weicb0652e2014-03-12 18:29:36 -07001994status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001995 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001996 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001997 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07001998
Zhijun He7ef20392014-04-21 16:04:17 -07001999 {
2000 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002001
2002 // b/116514106 "disconnect()" can get called twice for the same device. The
2003 // camera device will not be initialized during the second run.
2004 if (mStatus == STATUS_UNINITIALIZED) {
2005 return OK;
2006 }
2007
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002008 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002009 }
2010
Emilian Peev08dd2452017-04-06 16:55:14 +01002011 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002012}
2013
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002014status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002015 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2016}
2017
2018status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002019 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002020 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002021 Mutex::Autolock il(mInterfaceLock);
2022 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002023
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002024 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2025 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002026 CLOGE("Stream %d does not exist", streamId);
2027 return BAD_VALUE;
2028 }
2029
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002030 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002031 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002032 return BAD_VALUE;
2033 }
2034
2035 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002036 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002037 return BAD_VALUE;
2038 }
2039
Ruben Brunkc78ac262015-08-13 17:58:46 -07002040 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002041}
2042
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002043status_t Camera3Device::tearDown(int streamId) {
2044 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002045 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002046 Mutex::Autolock il(mInterfaceLock);
2047 Mutex::Autolock l(mLock);
2048
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002049 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2050 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002051 CLOGE("Stream %d does not exist", streamId);
2052 return BAD_VALUE;
2053 }
2054
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002055 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2056 CLOGE("Stream %d is a target of a in-progress request", streamId);
2057 return BAD_VALUE;
2058 }
2059
2060 return stream->tearDown();
2061}
2062
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002063status_t Camera3Device::addBufferListenerForStream(int streamId,
2064 wp<Camera3StreamBufferListener> listener) {
2065 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002066 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002067 Mutex::Autolock il(mInterfaceLock);
2068 Mutex::Autolock l(mLock);
2069
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002070 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2071 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002072 CLOGE("Stream %d does not exist", streamId);
2073 return BAD_VALUE;
2074 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002075 stream->addBufferListener(listener);
2076
2077 return OK;
2078}
2079
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002080/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002081 * Methods called by subclasses
2082 */
2083
2084void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002085 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002086 {
2087 // Need mLock to safely update state and synchronize to current
2088 // state of methods in flight.
2089 Mutex::Autolock l(mLock);
2090 // We can get various system-idle notices from the status tracker
2091 // while starting up. Only care about them if we've actually sent
2092 // in some requests recently.
2093 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2094 return;
2095 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002096 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2097 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002098 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002099
2100 // Skip notifying listener if we're doing some user-transparent
2101 // state changes
2102 if (mPauseStateNotify) return;
2103 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002104
2105 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002106 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002107 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002108 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002109 }
2110 if (idle && listener != NULL) {
2111 listener->notifyIdle();
2112 }
2113}
2114
Shuzhen Wang758c2152017-01-10 18:26:18 -08002115status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002116 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002117 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002118 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2119 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002120
2121 if (surfaceIds == nullptr) {
2122 return BAD_VALUE;
2123 }
2124
Zhijun He5d677d12016-05-29 16:52:39 -07002125 Mutex::Autolock il(mInterfaceLock);
2126 Mutex::Autolock l(mLock);
2127
Shuzhen Wang758c2152017-01-10 18:26:18 -08002128 if (consumers.size() == 0) {
2129 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002130 return BAD_VALUE;
2131 }
2132
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002133 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2134 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002135 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002136 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002137 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002138
2139 // isConsumerConfigurationDeferred will be off after setConsumers
2140 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002141 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002142 if (res != OK) {
2143 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2144 return res;
2145 }
2146
Emilian Peev40ead602017-09-26 15:46:36 +01002147 for (auto &consumer : consumers) {
2148 int id = stream->getSurfaceId(consumer);
2149 if (id < 0) {
2150 CLOGE("Invalid surface id!");
2151 return BAD_VALUE;
2152 }
2153 surfaceIds->push_back(id);
2154 }
2155
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002156 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002157 if (!stream->isConfiguring()) {
2158 CLOGE("Stream %d was already fully configured.", streamId);
2159 return INVALID_OPERATION;
2160 }
Zhijun He5d677d12016-05-29 16:52:39 -07002161
Shuzhen Wang0129d522016-10-30 22:43:41 -07002162 res = stream->finishConfiguration();
2163 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002164 // If finishConfiguration fails due to abandoned surface, do not set
2165 // device to error state.
2166 bool isSurfaceAbandoned =
2167 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2168 if (!isSurfaceAbandoned) {
2169 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2170 stream->getId(), strerror(-res), res);
2171 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002172 return res;
2173 }
Zhijun He5d677d12016-05-29 16:52:39 -07002174 }
2175
2176 return OK;
2177}
2178
Emilian Peev40ead602017-09-26 15:46:36 +01002179status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2180 const std::vector<OutputStreamInfo> &outputInfo,
2181 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2182 Mutex::Autolock il(mInterfaceLock);
2183 Mutex::Autolock l(mLock);
2184
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002185 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2186 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002187 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002188 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002189 }
2190
2191 for (const auto &it : removedSurfaceIds) {
2192 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2193 CLOGE("Shared surface still part of a pending request!");
2194 return -EBUSY;
2195 }
2196 }
2197
Emilian Peev40ead602017-09-26 15:46:36 +01002198 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2199 if (res != OK) {
2200 CLOGE("Stream %d failed to update stream (error %d %s) ",
2201 streamId, res, strerror(-res));
2202 if (res == UNKNOWN_ERROR) {
2203 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2204 __FUNCTION__);
2205 }
2206 return res;
2207 }
2208
2209 return res;
2210}
2211
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002212status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2213 Mutex::Autolock il(mInterfaceLock);
2214 Mutex::Autolock l(mLock);
2215
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002216 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2217 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002218 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2219 return BAD_VALUE;
2220 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002221 return stream->dropBuffers(dropping);
2222}
2223
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002224/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002225 * Camera3Device private methods
2226 */
2227
2228sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002229 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002230 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002231
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002232 sp<CaptureRequest> newRequest = new CaptureRequest();
Emilian Peevaebbe412018-01-15 13:53:24 +00002233 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002234
2235 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002236 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002237 if (inputStreams.count > 0) {
2238 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002239 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002240 CLOGE("Request references unknown input stream %d",
2241 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002242 return NULL;
2243 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002244
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002245 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002246 SET_ERR_L("%s: input stream %d is not configured!",
2247 __FUNCTION__, mInputStream->getId());
2248 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002249 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002250 // Check if stream prepare is blocking requests.
2251 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002252 CLOGE("Request references an input stream that's being prepared!");
2253 return NULL;
2254 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002255
2256 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002257 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002258 }
2259
2260 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002261 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002262 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002263 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002264 return NULL;
2265 }
2266
2267 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002268 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2269 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002270 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002271 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002272 return NULL;
2273 }
Zhijun He5d677d12016-05-29 16:52:39 -07002274 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002275 auto iter = surfaceMap.find(streams.data.i32[i]);
2276 if (iter != surfaceMap.end()) {
2277 const std::vector<size_t>& surfaces = iter->second;
2278 for (const auto& surface : surfaces) {
2279 if (stream->isConsumerConfigurationDeferred(surface)) {
2280 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2281 "due to deferred consumer", stream->getId(), surface);
2282 return NULL;
2283 }
2284 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002285 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002286 }
2287
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002288 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002289 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2290 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002291 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002292 // Check if stream prepare is blocking requests.
2293 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002294 CLOGE("Request references an output stream that's being prepared!");
2295 return NULL;
2296 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002297
2298 newRequest->mOutputStreams.push(stream);
2299 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002300 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002301 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002302
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002303 auto rotateAndCropEntry =
2304 newRequest->mSettingsList.begin()->metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
2305 if (rotateAndCropEntry.count > 0 &&
2306 rotateAndCropEntry.data.u8[0] == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
2307 newRequest->mRotateAndCropAuto = true;
2308 } else {
2309 newRequest->mRotateAndCropAuto = false;
2310 }
2311
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002312 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002313}
2314
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002315void Camera3Device::cancelStreamsConfigurationLocked() {
2316 int res = OK;
2317 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2318 res = mInputStream->cancelConfiguration();
2319 if (res != OK) {
2320 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2321 mInputStream->getId(), strerror(-res), res);
2322 }
2323 }
2324
2325 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002326 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002327 if (outputStream->isConfiguring()) {
2328 res = outputStream->cancelConfiguration();
2329 if (res != OK) {
2330 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2331 outputStream->getId(), strerror(-res), res);
2332 }
2333 }
2334 }
2335
2336 // Return state to that at start of call, so that future configures
2337 // properly clean things up
2338 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2339 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002340
2341 res = mPreparerThread->resume();
2342 if (res != OK) {
2343 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2344 }
2345}
2346
2347bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2348 ATRACE_CALL();
2349 bool ret = false;
2350
Jayant Chowdhary646c31b2020-01-30 13:09:59 -08002351 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002352 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2353
2354 Mutex::Autolock l(mLock);
2355 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2356 if (rc == NO_ERROR) {
2357 mNeedConfig = true;
2358 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2359 if (rc == NO_ERROR) {
2360 ret = true;
2361 mPauseStateNotify = false;
2362 //Moving to active state while holding 'mLock' is important.
2363 //There could be pending calls to 'create-/deleteStream' which
2364 //will trigger another stream configuration while the already
2365 //present streams end up with outstanding buffers that will
2366 //not get drained.
2367 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002368 } else if (rc == DEAD_OBJECT) {
2369 // DEAD_OBJECT can be returned if either the consumer surface is
2370 // abandoned, or the HAL has died.
2371 // - If the HAL has died, configureStreamsLocked call will set
2372 // device to error state,
2373 // - If surface is abandoned, we should not set device to error
2374 // state.
2375 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002376 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002377 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002378 }
2379 } else {
2380 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2381 }
2382
2383 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002384}
2385
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002386status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002387 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002388 ATRACE_CALL();
2389 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002390
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002391 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002392 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002393 return INVALID_OPERATION;
2394 }
2395
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002396 if (operatingMode < 0) {
2397 CLOGE("Invalid operating mode: %d", operatingMode);
2398 return BAD_VALUE;
2399 }
2400
2401 bool isConstrainedHighSpeed =
2402 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2403 operatingMode;
2404
2405 if (mOperatingMode != operatingMode) {
2406 mNeedConfig = true;
2407 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2408 mOperatingMode = operatingMode;
2409 }
2410
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002411 // In case called from configureStreams, abort queued input buffers not belonging to
2412 // any pending requests.
2413 if (mInputStream != NULL && notifyRequestThread) {
2414 while (true) {
2415 camera3_stream_buffer_t inputBuffer;
2416 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2417 /*respectHalLimit*/ false);
2418 if (res != OK) {
2419 // Exhausted acquiring all input buffers.
2420 break;
2421 }
2422
2423 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2424 res = mInputStream->returnInputBuffer(inputBuffer);
2425 if (res != OK) {
2426 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2427 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2428 }
2429 }
2430 }
2431
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002432 if (!mNeedConfig) {
2433 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2434 return OK;
2435 }
2436
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002437 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2438 // adding a dummy stream instead.
2439 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2440 if (mOutputStreams.size() == 0) {
2441 addDummyStreamLocked();
2442 } else {
2443 tryRemoveDummyStreamLocked();
2444 }
2445
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002446 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002447 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002448
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002449 mPreparerThread->pause();
2450
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002451 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002452 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002453 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2454
2455 Vector<camera3_stream_t*> streams;
2456 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002457 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002458
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002459
2460 if (mInputStream != NULL) {
2461 camera3_stream_t *inputStream;
2462 inputStream = mInputStream->startConfiguration();
2463 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002464 CLOGE("Can't start input stream configuration");
2465 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002466 return INVALID_OPERATION;
2467 }
2468 streams.add(inputStream);
2469 }
2470
2471 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002472
2473 // Don't configure bidi streams twice, nor add them twice to the list
2474 if (mOutputStreams[i].get() ==
2475 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2476
2477 config.num_streams--;
2478 continue;
2479 }
2480
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002481 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002482 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002483 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002484 CLOGE("Can't start output stream configuration");
2485 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002486 return INVALID_OPERATION;
2487 }
2488 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002489
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002490 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002491 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2492 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002493 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2494 bufferSizes[k] = static_cast<uint32_t>(
2495 getJpegBufferSize(outputStream->width, outputStream->height));
2496 } else if (outputStream->data_space ==
2497 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2498 bufferSizes[k] = outputStream->width * outputStream->height;
2499 } else {
2500 ALOGW("%s: Blob dataSpace %d not supported",
2501 __FUNCTION__, outputStream->data_space);
2502 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002503 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002504 }
2505
2506 config.streams = streams.editArray();
2507
2508 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002509 // max_buffers, usage, and priv fields, as well as data_space and format
2510 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002511
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002512 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002513 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002514 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002515
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002516 if (res == BAD_VALUE) {
2517 // HAL rejected this set of streams as unsupported, clean up config
2518 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002519 CLOGE("Set of requested inputs/outputs not supported by HAL");
2520 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002521 return BAD_VALUE;
2522 } else if (res != OK) {
2523 // Some other kind of error from configure_streams - this is not
2524 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002525 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2526 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002527 return res;
2528 }
2529
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002530 // Finish all stream configuration immediately.
2531 // TODO: Try to relax this later back to lazy completion, which should be
2532 // faster
2533
Igor Murashkin073f8572013-05-02 14:59:28 -07002534 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002535 bool streamReConfigured = false;
2536 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002537 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002538 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002539 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002540 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002541 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2542 return DEAD_OBJECT;
2543 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002544 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002545 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002546 if (streamReConfigured) {
2547 mInterface->onStreamReConfigured(mInputStream->getId());
2548 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002549 }
2550
2551 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002552 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002553 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002554 bool streamReConfigured = false;
2555 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002556 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002557 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002558 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002559 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002560 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2561 return DEAD_OBJECT;
2562 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002563 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002564 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002565 if (streamReConfigured) {
2566 mInterface->onStreamReConfigured(outputStream->getId());
2567 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002568 }
2569 }
2570
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002571 // Request thread needs to know to avoid using repeat-last-settings protocol
2572 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002573 if (notifyRequestThread) {
2574 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2575 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002576
Zhijun He90f7c372016-08-16 16:19:43 -07002577 char value[PROPERTY_VALUE_MAX];
2578 property_get("camera.fifo.disable", value, "0");
2579 int32_t disableFifo = atoi(value);
2580 if (disableFifo != 1) {
2581 // Boost priority of request thread to SCHED_FIFO.
2582 pid_t requestThreadTid = mRequestThread->getTid();
2583 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002584 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002585 if (res != OK) {
2586 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2587 strerror(-res), res);
2588 } else {
2589 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2590 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002591 }
2592
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002593 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002594 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2595 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2596 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2597 sessionParams.unlock(newSessionParams);
2598 mSessionParams.unlock(currentSessionParams);
2599 if (updateSessionParams) {
2600 mSessionParams = sessionParams;
2601 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002602
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002603 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002604
Ruben Brunk183f0562015-08-12 12:55:02 -07002605 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2606 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002607
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002608 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002609
Zhijun He0a210512014-07-24 13:45:15 -07002610 // tear down the deleted streams after configure streams.
2611 mDeletedStreams.clear();
2612
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002613 auto rc = mPreparerThread->resume();
2614 if (rc != OK) {
2615 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2616 return rc;
2617 }
2618
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002619 if (mDummyStreamId == NO_STREAM) {
2620 mRequestBufferSM.onStreamsConfigured();
2621 }
2622
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002623 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002624}
2625
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002626status_t Camera3Device::addDummyStreamLocked() {
2627 ATRACE_CALL();
2628 status_t res;
2629
2630 if (mDummyStreamId != NO_STREAM) {
2631 // Should never be adding a second dummy stream when one is already
2632 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002633 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2634 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002635 return INVALID_OPERATION;
2636 }
2637
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002638 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002639
2640 sp<Camera3OutputStreamInterface> dummyStream =
2641 new Camera3DummyStream(mNextStreamId);
2642
2643 res = mOutputStreams.add(mNextStreamId, dummyStream);
2644 if (res < 0) {
2645 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2646 return res;
2647 }
2648
2649 mDummyStreamId = mNextStreamId;
2650 mNextStreamId++;
2651
2652 return OK;
2653}
2654
2655status_t Camera3Device::tryRemoveDummyStreamLocked() {
2656 ATRACE_CALL();
2657 status_t res;
2658
2659 if (mDummyStreamId == NO_STREAM) return OK;
2660 if (mOutputStreams.size() == 1) return OK;
2661
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002662 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002663
2664 // Ok, have a dummy stream and there's at least one other output stream,
2665 // so remove the dummy
2666
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002667 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2668 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002669 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2670 return INVALID_OPERATION;
2671 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002672 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002673
2674 // Free up the stream endpoint so that it can be used by some other stream
2675 res = deletedStream->disconnect();
2676 if (res != OK) {
2677 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2678 // fall through since we want to still list the stream as deleted.
2679 }
2680 mDeletedStreams.add(deletedStream);
2681 mDummyStreamId = NO_STREAM;
2682
2683 return res;
2684}
2685
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002686void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002687 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002688 Mutex::Autolock l(mLock);
2689 va_list args;
2690 va_start(args, fmt);
2691
2692 setErrorStateLockedV(fmt, args);
2693
2694 va_end(args);
2695}
2696
2697void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002698 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002699 Mutex::Autolock l(mLock);
2700 setErrorStateLockedV(fmt, args);
2701}
2702
2703void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2704 va_list args;
2705 va_start(args, fmt);
2706
2707 setErrorStateLockedV(fmt, args);
2708
2709 va_end(args);
2710}
2711
2712void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002713 // Print out all error messages to log
2714 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002715 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002716
2717 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002718 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002719
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002720 mErrorCause = errorCause;
2721
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002722 if (mRequestThread != nullptr) {
2723 mRequestThread->setPaused(true);
2724 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002725 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002726
2727 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002728 sp<NotificationListener> listener = mListener.promote();
2729 if (listener != NULL) {
2730 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002731 CaptureResultExtras());
2732 }
2733
2734 // Save stack trace. View by dumping it later.
2735 CameraTraces::saveTrace();
2736 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002737}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002738
2739/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002740 * In-flight request management
2741 */
2742
Jianing Weicb0652e2014-03-12 18:29:36 -07002743status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002744 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002745 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002746 std::set<String8>& physicalCameraIds, bool isStillCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002747 bool isZslCapture, bool rotateAndCropAuto, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08002748 const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002749 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002750 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002751
2752 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002753 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07002754 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08002755 rotateAndCropAuto, cameraIdsWithZoom, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002756 if (res < 0) return res;
2757
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002758 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002759 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2760 // avoid a deadlock during reprocess requests.
2761 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002762 if (mStatusTracker != nullptr) {
2763 mStatusTracker->markComponentActive(mInFlightStatusId);
2764 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002765 }
2766
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002767 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002768 return OK;
2769}
2770
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002771void Camera3Device::onInflightEntryRemovedLocked(nsecs_t duration) {
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002772 // Indicate idle inFlightMap to the status tracker
2773 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002774 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01002775 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2776 // avoid a deadlock during reprocess requests.
2777 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002778 if (mStatusTracker != nullptr) {
2779 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2780 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002781 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002782 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002783}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002784
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002785void Camera3Device::checkInflightMapLengthLocked() {
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07002786 // Sanity check - if we have too many in-flight frames with long total inflight duration,
2787 // something has likely gone wrong. This might still be legit only if application send in
2788 // a long burst of long exposure requests.
2789 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
2790 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
2791 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
2792 mInFlightMap.size(), mExpectedInflightDuration);
2793 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2794 kInFlightWarnLimitHighSpeed) {
2795 CLOGW("In-flight list too large for high speed configuration: %zu,"
2796 "total inflight duration %" PRIu64,
2797 mInFlightMap.size(), mExpectedInflightDuration);
2798 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002799 }
2800}
2801
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002802void Camera3Device::onInflightMapFlushedLocked() {
2803 mExpectedInflightDuration = 0;
2804}
2805
2806void Camera3Device::removeInFlightMapEntryLocked(int idx) {
2807 ATRACE_CALL();
2808 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
2809 mInFlightMap.removeItemsAt(idx, 1);
2810
2811 onInflightEntryRemovedLocked(duration);
2812}
2813
2814
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002815void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002816 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002817 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002818 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002819 std::lock_guard<std::mutex> l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002820 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002821 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002822
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002823 FlushInflightReqStates states {
2824 mId, mInFlightLock, mInFlightMap, mUseHalBufManager,
2825 listener, *this, *mInterface, *this};
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002826
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08002827 camera3::flushInflightRequests(states);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002828}
2829
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002830CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07002831 ALOGV("%s", __FUNCTION__);
2832
Igor Murashkin1e479c02013-09-06 16:55:14 -07002833 CameraMetadata retVal;
2834
2835 if (mRequestThread != NULL) {
2836 retVal = mRequestThread->getLatestRequest();
2837 }
2838
Igor Murashkin1e479c02013-09-06 16:55:14 -07002839 return retVal;
2840}
2841
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002842void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07002843 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
2844 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
2845
2846 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
2847 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07002848}
2849
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002850/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002851 * HalInterface inner class methods
2852 */
2853
Yifan Hongf79b5542017-04-11 14:44:25 -07002854Camera3Device::HalInterface::HalInterface(
2855 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002856 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002857 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002858 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002859 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08002860 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002861 mIsReconfigurationQuerySupported(true),
2862 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002863 // Check with hardware service manager if we can downcast these interfaces
2864 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002865 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
2866 if (castResult_3_6.isOk()) {
2867 mHidlSession_3_6 = castResult_3_6;
2868 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07002869 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
2870 if (castResult_3_5.isOk()) {
2871 mHidlSession_3_5 = castResult_3_5;
2872 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002873 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
2874 if (castResult_3_4.isOk()) {
2875 mHidlSession_3_4 = castResult_3_4;
2876 }
2877 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
2878 if (castResult_3_3.isOk()) {
2879 mHidlSession_3_3 = castResult_3_3;
2880 }
2881}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002882
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002883Camera3Device::HalInterface::HalInterface() :
2884 mUseHalBufManager(false),
2885 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002886
2887Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07002888 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08002889 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002890 mUseHalBufManager(other.mUseHalBufManager),
2891 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002892
2893bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01002894 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002895}
2896
2897void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07002898 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00002899 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00002900 mHidlSession_3_4.clear();
2901 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002902 mHidlSession.clear();
2903}
2904
2905status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
2906 camera3_request_template_t templateId,
2907 /*out*/ camera_metadata_t **requestTemplate) {
2908 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
2909 if (!valid()) return INVALID_OPERATION;
2910 status_t res = OK;
2911
Emilian Peev31abd0a2017-05-11 18:37:46 +01002912 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002913
2914 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01002915 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002916 status = s;
2917 if (status == common::V1_0::Status::OK) {
2918 const camera_metadata *r =
2919 reinterpret_cast<const camera_metadata_t*>(request.data());
2920 size_t expectedSize = request.size();
2921 int ret = validate_camera_metadata_structure(r, &expectedSize);
2922 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
2923 *requestTemplate = clone_camera_metadata(r);
2924 if (*requestTemplate == nullptr) {
2925 ALOGE("%s: Unable to clone camera metadata received from HAL",
2926 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01002927 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002928 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002929 } else {
2930 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
2931 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01002932 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002933 }
2934 };
2935 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08002936 RequestTemplate id;
2937 switch (templateId) {
2938 case CAMERA3_TEMPLATE_PREVIEW:
2939 id = RequestTemplate::PREVIEW;
2940 break;
2941 case CAMERA3_TEMPLATE_STILL_CAPTURE:
2942 id = RequestTemplate::STILL_CAPTURE;
2943 break;
2944 case CAMERA3_TEMPLATE_VIDEO_RECORD:
2945 id = RequestTemplate::VIDEO_RECORD;
2946 break;
2947 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
2948 id = RequestTemplate::VIDEO_SNAPSHOT;
2949 break;
2950 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
2951 id = RequestTemplate::ZERO_SHUTTER_LAG;
2952 break;
2953 case CAMERA3_TEMPLATE_MANUAL:
2954 id = RequestTemplate::MANUAL;
2955 break;
2956 default:
2957 // Unknown template ID, or this HAL is too old to support it
2958 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002959 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08002960 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08002961
Emilian Peev31abd0a2017-05-11 18:37:46 +01002962 if (!err.isOk()) {
2963 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
2964 res = DEAD_OBJECT;
2965 } else {
2966 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002967 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01002968
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002969 return res;
2970}
2971
Emilian Peev4ec17882019-01-24 17:16:58 -08002972bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
2973 CameraMetadata& newSessionParams) {
2974 // We do reconfiguration by default;
2975 bool ret = true;
2976 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
2977 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
2978 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
2979 oldSessionParams.getAndLock());
2980 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
2981 newSessionParams.getAndLock());
2982 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
2983 get_camera_metadata_size(oldSessioMeta));
2984 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
2985 get_camera_metadata_size(newSessioMeta));
2986 hardware::camera::common::V1_0::Status callStatus;
2987 bool required;
2988 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
2989 bool requiredFlag) {
2990 callStatus = s;
2991 required = requiredFlag;
2992 };
2993 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
2994 oldSessionParams.unlock(oldSessioMeta);
2995 newSessionParams.unlock(newSessioMeta);
2996 if (err.isOk()) {
2997 switch (callStatus) {
2998 case hardware::camera::common::V1_0::Status::OK:
2999 ret = required;
3000 break;
3001 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
3002 mIsReconfigurationQuerySupported = false;
3003 ret = true;
3004 break;
3005 default:
3006 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
3007 ret = true;
3008 }
3009 } else {
3010 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
3011 ret = true;
3012 }
3013 }
3014
3015 return ret;
3016}
3017
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003018status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003019 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003020 ATRACE_NAME("CameraHal::configureStreams");
3021 if (!valid()) return INVALID_OPERATION;
3022 status_t res = OK;
3023
Emilian Peev31abd0a2017-05-11 18:37:46 +01003024 // Convert stream config to HIDL
3025 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003026 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3027 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3028 requestedConfiguration3_2.streams.resize(config->num_streams);
3029 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003030 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003031 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3032 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003033 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003034
Emilian Peev31abd0a2017-05-11 18:37:46 +01003035 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3036 cam3stream->setBufferFreedListener(this);
3037 int streamId = cam3stream->getId();
3038 StreamType streamType;
3039 switch (src->stream_type) {
3040 case CAMERA3_STREAM_OUTPUT:
3041 streamType = StreamType::OUTPUT;
3042 break;
3043 case CAMERA3_STREAM_INPUT:
3044 streamType = StreamType::INPUT;
3045 break;
3046 default:
3047 ALOGE("%s: Stream %d: Unsupported stream type %d",
3048 __FUNCTION__, streamId, config->streams[i]->stream_type);
3049 return BAD_VALUE;
3050 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003051 dst3_2.id = streamId;
3052 dst3_2.streamType = streamType;
3053 dst3_2.width = src->width;
3054 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003055 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003056 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07003057 // For HidlSession version 3.5 or newer, the format and dataSpace sent
3058 // to HAL are original, not the overriden ones.
3059 if (mHidlSession_3_5 != nullptr) {
3060 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
3061 cam3stream->getOriginalFormat() : src->format);
3062 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
3063 cam3stream->getOriginalDataSpace() : src->data_space);
3064 } else {
3065 dst3_2.format = mapToPixelFormat(src->format);
3066 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3067 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003068 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003069 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003070 if (src->physical_camera_id != nullptr) {
3071 dst3_4.physicalCameraId = src->physical_camera_id;
3072 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003073
3074 activeStreams.insert(streamId);
3075 // Create Buffer ID map if necessary
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003076 mBufferRecords.tryCreateBufferCache(streamId);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003077 }
3078 // remove BufferIdMap for deleted streams
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003079 mBufferRecords.removeInactiveBufferCaches(activeStreams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003080
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003081 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003082 res = mapToStreamConfigurationMode(
3083 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003084 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003085 if (res != OK) {
3086 return res;
3087 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003088 requestedConfiguration3_2.operationMode = operationMode;
3089 requestedConfiguration3_4.operationMode = operationMode;
3090 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003091 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3092 get_camera_metadata_size(sessionParams));
3093
Emilian Peev31abd0a2017-05-11 18:37:46 +01003094 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003095 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003096 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003097 device::V3_6::HalStreamConfiguration finalConfiguration3_6;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003098 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003099
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003100 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003101 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3102 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003103 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003104 };
3105
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003106 auto configStream36Cb = [&status, &finalConfiguration3_6]
3107 (common::V1_0::Status s, const device::V3_6::HalStreamConfiguration& halConfiguration) {
3108 finalConfiguration3_6 = halConfiguration;
3109 status = s;
3110 };
3111
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003112 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3113 (hardware::Return<void>& err) -> status_t {
3114 if (!err.isOk()) {
3115 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3116 return DEAD_OBJECT;
3117 }
3118 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3119 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3120 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3121 }
3122 return OK;
3123 };
3124
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003125 auto postprocConfigStream36 = [&finalConfiguration, &finalConfiguration3_6]
3126 (hardware::Return<void>& err) -> status_t {
3127 if (!err.isOk()) {
3128 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3129 return DEAD_OBJECT;
3130 }
3131 finalConfiguration.streams.resize(finalConfiguration3_6.streams.size());
3132 for (size_t i = 0; i < finalConfiguration3_6.streams.size(); i++) {
3133 finalConfiguration.streams[i] = finalConfiguration3_6.streams[i].v3_4.v3_3;
3134 }
3135 return OK;
3136 };
3137
Shuzhen Wang92653952019-05-07 15:11:43 -07003138 // See which version of HAL we have
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003139 if (mHidlSession_3_6 != nullptr) {
3140 ALOGV("%s: v3.6 device found", __FUNCTION__);
3141 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3142 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3143 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3144 auto err = mHidlSession_3_6->configureStreams_3_6(
3145 requestedConfiguration3_5, configStream36Cb);
3146 res = postprocConfigStream36(err);
3147 if (res != OK) {
3148 return res;
3149 }
3150 } else if (mHidlSession_3_5 != nullptr) {
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003151 ALOGV("%s: v3.5 device found", __FUNCTION__);
3152 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3153 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3154 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3155 auto err = mHidlSession_3_5->configureStreams_3_5(
3156 requestedConfiguration3_5, configStream34Cb);
3157 res = postprocConfigStream34(err);
3158 if (res != OK) {
3159 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003160 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003161 } else if (mHidlSession_3_4 != nullptr) {
3162 // We do; use v3.4 for the call
3163 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003164 auto err = mHidlSession_3_4->configureStreams_3_4(
3165 requestedConfiguration3_4, configStream34Cb);
3166 res = postprocConfigStream34(err);
3167 if (res != OK) {
3168 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003169 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003170 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003171 // We do; use v3.3 for the call
3172 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003173 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003174 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003175 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003176 finalConfiguration = halConfiguration;
3177 status = s;
3178 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003179 if (!err.isOk()) {
3180 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3181 return DEAD_OBJECT;
3182 }
3183 } else {
3184 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3185 ALOGV("%s: v3.2 device found", __FUNCTION__);
3186 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003187 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003188 [&status, &finalConfiguration_3_2]
3189 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3190 finalConfiguration_3_2 = halConfiguration;
3191 status = s;
3192 });
3193 if (!err.isOk()) {
3194 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3195 return DEAD_OBJECT;
3196 }
3197 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3198 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3199 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3200 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003201 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003202 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003203 }
3204
3205 if (status != common::V1_0::Status::OK ) {
3206 return CameraProviderManager::mapToStatusT(status);
3207 }
3208
3209 // And convert output stream configuration from HIDL
3210
3211 for (size_t i = 0; i < config->num_streams; i++) {
3212 camera3_stream_t *dst = config->streams[i];
3213 int streamId = Camera3Stream::cast(dst)->getId();
3214
3215 // Start scan at i, with the assumption that the stream order matches
3216 size_t realIdx = i;
3217 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003218 size_t halStreamCount = finalConfiguration.streams.size();
3219 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003220 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003221 found = true;
3222 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003223 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07003224 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003225 }
3226 if (!found) {
3227 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3228 __FUNCTION__, streamId);
3229 return INVALID_OPERATION;
3230 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003231 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003232 device::V3_6::HalStream &src_36 = finalConfiguration3_6.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003233
Emilian Peev710c1422017-08-30 11:19:38 +01003234 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003235 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3236 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3237
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003238 if (mHidlSession_3_6 != nullptr) {
3239 dstStream->setOfflineProcessingSupport(src_36.supportOffline);
3240 }
3241
Yin-Chia Yeh90667662019-07-01 15:45:00 -07003242 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07003243 dstStream->setFormatOverride(false);
3244 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003245 if (dst->format != overrideFormat) {
3246 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3247 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003248 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003249 if (dst->data_space != overrideDataSpace) {
3250 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3251 streamId, dst->format);
3252 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003253 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07003254 bool needFormatOverride =
3255 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
3256 bool needDataspaceOverride =
3257 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003258 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07003259 dstStream->setFormatOverride(needFormatOverride);
3260 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003261 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003262 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003263 }
3264
Emilian Peev31abd0a2017-05-11 18:37:46 +01003265 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003266 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003267 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003268 __FUNCTION__, streamId);
3269 return INVALID_OPERATION;
3270 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003271 dstStream->setUsage(
3272 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003273 } else {
3274 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003275 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003276 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3277 __FUNCTION__, streamId);
3278 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003279 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003280 dstStream->setUsage(
3281 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003282 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003283 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003284 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003285
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003286 return res;
3287}
3288
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003289status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003290 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003291 /*out*/std::vector<native_handle_t*>* handlesCreated,
3292 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003293 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003294 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
3295 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
3296 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003297 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003298 }
3299
3300 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003301
3302 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003303
3304 {
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003305 if (request->input_buffer != nullptr) {
3306 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3307 buffer_handle_t buf = *(request->input_buffer->buffer);
3308 auto pair = getBufferId(buf, streamId);
3309 bool isNewBuffer = pair.first;
3310 uint64_t bufferId = pair.second;
3311 captureRequest->inputBuffer.streamId = streamId;
3312 captureRequest->inputBuffer.bufferId = bufferId;
3313 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3314 captureRequest->inputBuffer.status = BufferStatus::OK;
3315 native_handle_t *acquireFence = nullptr;
3316 if (request->input_buffer->acquire_fence != -1) {
3317 acquireFence = native_handle_create(1,0);
3318 acquireFence->data[0] = request->input_buffer->acquire_fence;
3319 handlesCreated->push_back(acquireFence);
3320 }
3321 captureRequest->inputBuffer.acquireFence = acquireFence;
3322 captureRequest->inputBuffer.releaseFence = nullptr;
3323
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003324 mBufferRecords.pushInflightBuffer(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003325 request->input_buffer->buffer);
3326 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003327 } else {
3328 captureRequest->inputBuffer.streamId = -1;
3329 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3330 }
3331
3332 captureRequest->outputBuffers.resize(request->num_output_buffers);
3333 for (size_t i = 0; i < request->num_output_buffers; i++) {
3334 const camera3_stream_buffer_t *src = request->output_buffers + i;
3335 StreamBuffer &dst = captureRequest->outputBuffers[i];
3336 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003337 if (src->buffer != nullptr) {
3338 buffer_handle_t buf = *(src->buffer);
3339 auto pair = getBufferId(buf, streamId);
3340 bool isNewBuffer = pair.first;
3341 dst.bufferId = pair.second;
3342 dst.buffer = isNewBuffer ? buf : nullptr;
3343 native_handle_t *acquireFence = nullptr;
3344 if (src->acquire_fence != -1) {
3345 acquireFence = native_handle_create(1,0);
3346 acquireFence->data[0] = src->acquire_fence;
3347 handlesCreated->push_back(acquireFence);
3348 }
3349 dst.acquireFence = acquireFence;
3350 } else if (mUseHalBufManager) {
3351 // HAL buffer management path
3352 dst.bufferId = BUFFER_ID_NO_BUFFER;
3353 dst.buffer = nullptr;
3354 dst.acquireFence = nullptr;
3355 } else {
3356 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
3357 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003358 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003359 dst.streamId = streamId;
3360 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003361 dst.releaseFence = nullptr;
3362
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003363 // Output buffers are empty when using HAL buffer manager
3364 if (!mUseHalBufManager) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003365 mBufferRecords.pushInflightBuffer(
3366 captureRequest->frameNumber, streamId, src->buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003367 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08003368 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003369 }
3370 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003371 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003372}
3373
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003374void Camera3Device::HalInterface::cleanupNativeHandles(
3375 std::vector<native_handle_t*> *handles, bool closeFd) {
3376 if (handles == nullptr) {
3377 return;
3378 }
3379 if (closeFd) {
3380 for (auto& handle : *handles) {
3381 native_handle_close(handle);
3382 }
3383 }
3384 for (auto& handle : *handles) {
3385 native_handle_delete(handle);
3386 }
3387 handles->clear();
3388 return;
3389}
3390
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003391status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3392 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3393 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3394 if (!valid()) return INVALID_OPERATION;
3395
Emilian Peevaebbe412018-01-15 13:53:24 +00003396 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3397 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3398 if (castResult_3_4.isOk()) {
3399 hidlSession_3_4 = castResult_3_4;
3400 }
3401
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003402 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003403 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003404 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003405 if (hidlSession_3_4 != nullptr) {
3406 captureRequests_3_4.resize(batchSize);
3407 } else {
3408 captureRequests.resize(batchSize);
3409 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003410 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003411 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003412
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003413 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003414 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003415 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003416 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003417 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00003418 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003419 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
3420 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003421 }
3422 if (res != OK) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003423 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003424 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003425 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00003426 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003427 }
3428
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003429 std::vector<device::V3_2::BufferCache> cachesToRemove;
3430 {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003431 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003432 for (auto& pair : mFreedBuffers) {
3433 // The stream might have been removed since onBufferFreed
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003434 if (mBufferRecords.isStreamCached(pair.first)) {
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003435 cachesToRemove.push_back({pair.first, pair.second});
3436 }
3437 }
3438 mFreedBuffers.clear();
3439 }
3440
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003441 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3442 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003443
3444 // Write metadata to FMQ.
3445 for (size_t i = 0; i < batchSize; i++) {
3446 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003447 device::V3_2::CaptureRequest* captureRequest;
3448 if (hidlSession_3_4 != nullptr) {
3449 captureRequest = &captureRequests_3_4[i].v3_2;
3450 } else {
3451 captureRequest = &captureRequests[i];
3452 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003453
3454 if (request->settings != nullptr) {
3455 size_t settingsSize = get_camera_metadata_size(request->settings);
3456 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3457 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3458 captureRequest->settings.resize(0);
3459 captureRequest->fmqSettingsSize = settingsSize;
3460 } else {
3461 if (mRequestMetadataQueue != nullptr) {
3462 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3463 }
3464 captureRequest->settings.setToExternal(
3465 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3466 get_camera_metadata_size(request->settings));
3467 captureRequest->fmqSettingsSize = 0u;
3468 }
3469 } else {
3470 // A null request settings maps to a size-0 CameraMetadata
3471 captureRequest->settings.resize(0);
3472 captureRequest->fmqSettingsSize = 0u;
3473 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003474
3475 if (hidlSession_3_4 != nullptr) {
3476 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3477 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003478 if (request->physcam_settings != nullptr) {
3479 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3480 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3481 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3482 settingsSize)) {
3483 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3484 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3485 settingsSize;
3486 } else {
3487 if (mRequestMetadataQueue != nullptr) {
3488 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3489 }
3490 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3491 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3492 request->physcam_settings[j])),
3493 get_camera_metadata_size(request->physcam_settings[j]));
3494 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003495 }
Emilian Peev00420d22018-02-05 21:33:13 +00003496 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003497 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003498 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003499 }
3500 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3501 request->physcam_id[j];
3502 }
3503 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003504 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003505
3506 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003507 auto resultCallback =
3508 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3509 status = s;
3510 *numRequestProcessed = n;
3511 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003512 if (hidlSession_3_4 != nullptr) {
3513 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003514 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003515 } else {
3516 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003517 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003518 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003519 if (!err.isOk()) {
3520 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003521 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003522 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003523
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003524 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3525 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3526 __FUNCTION__, *numRequestProcessed, batchSize);
3527 status = common::V1_0::Status::INTERNAL_ERROR;
3528 }
3529
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003530 res = CameraProviderManager::mapToStatusT(status);
3531 if (res == OK) {
3532 if (mHidlSession->isRemote()) {
3533 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
3534 // sent to camera HAL processes)
3535 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
3536 } else {
3537 // In passthrough mode the FDs are now owned by HAL
3538 cleanupNativeHandles(&handlesCreated);
3539 }
3540 } else {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003541 mBufferRecords.popInflightBuffers(inflightBuffers);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003542 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003543 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003544 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003545}
3546
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003547status_t Camera3Device::HalInterface::flush() {
3548 ATRACE_NAME("CameraHal::flush");
3549 if (!valid()) return INVALID_OPERATION;
3550 status_t res = OK;
3551
Emilian Peev31abd0a2017-05-11 18:37:46 +01003552 auto err = mHidlSession->flush();
3553 if (!err.isOk()) {
3554 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3555 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003556 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003557 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003558 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003559
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003560 return res;
3561}
3562
Emilian Peev31abd0a2017-05-11 18:37:46 +01003563status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003564 ATRACE_NAME("CameraHal::dump");
3565 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003566
Emilian Peev31abd0a2017-05-11 18:37:46 +01003567 // Handled by CameraProviderManager::dump
3568
3569 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003570}
3571
3572status_t Camera3Device::HalInterface::close() {
3573 ATRACE_NAME("CameraHal::close()");
3574 if (!valid()) return INVALID_OPERATION;
3575 status_t res = OK;
3576
Emilian Peev31abd0a2017-05-11 18:37:46 +01003577 auto err = mHidlSession->close();
3578 // Interface will be dead shortly anyway, so don't log errors
3579 if (!err.isOk()) {
3580 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003581 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003582
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003583 return res;
3584}
3585
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003586void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
3587 ATRACE_NAME("CameraHal::signalPipelineDrain");
3588 if (!valid() || mHidlSession_3_5 == nullptr) {
3589 ALOGE("%s called on invalid camera!", __FUNCTION__);
3590 return;
3591 }
3592
Yin-Chia Yehc300a072019-02-13 14:56:57 -08003593 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003594 if (!err.isOk()) {
3595 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3596 return;
3597 }
3598}
3599
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003600status_t Camera3Device::HalInterface::switchToOffline(
3601 const std::vector<int32_t>& streamsToKeep,
3602 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003603 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
3604 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003605 ATRACE_NAME("CameraHal::switchToOffline");
3606 if (!valid() || mHidlSession_3_6 == nullptr) {
3607 ALOGE("%s called on invalid camera!", __FUNCTION__);
3608 return INVALID_OPERATION;
3609 }
3610
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003611 if (offlineSessionInfo == nullptr || offlineSession == nullptr || bufferRecords == nullptr) {
3612 ALOGE("%s: output arguments must not be null!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003613 return INVALID_OPERATION;
3614 }
3615
3616 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003617 auto resultCallback =
3618 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
3619 status = s;
3620 *offlineSessionInfo = info;
3621 *offlineSession = session;
3622 };
3623 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
3624
3625 if (!err.isOk()) {
3626 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3627 return DEAD_OBJECT;
3628 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003629
3630 status_t ret = CameraProviderManager::mapToStatusT(status);
3631 if (ret != OK) {
3632 return ret;
3633 }
3634
3635 // TODO: assert no ongoing requestBuffer/returnBuffer call here
3636 // TODO: update RequestBufferStateMachine to block requestBuffer/returnBuffer once HAL
3637 // returns from switchToOffline.
3638
3639
3640 // Validate buffer caches
3641 std::vector<int32_t> streams;
3642 streams.reserve(offlineSessionInfo->offlineStreams.size());
3643 for (auto offlineStream : offlineSessionInfo->offlineStreams) {
3644 int32_t id = offlineStream.id;
3645 streams.push_back(id);
3646 // Verify buffer caches
3647 std::vector<uint64_t> bufIds(offlineStream.circulatingBufferIds.begin(),
3648 offlineStream.circulatingBufferIds.end());
3649 if (!verifyBufferIds(id, bufIds)) {
3650 ALOGE("%s: stream ID %d buffer cache records mismatch!", __FUNCTION__, id);
3651 return UNKNOWN_ERROR;
3652 }
3653 }
3654
3655 // Move buffer records
3656 bufferRecords->takeBufferCaches(mBufferRecords, streams);
3657 bufferRecords->takeInflightBufferMap(mBufferRecords);
3658 bufferRecords->takeRequestedBufferMap(mBufferRecords);
3659 return ret;
Yin-Chia Yehb978c382019-10-30 00:22:37 -07003660}
3661
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003662void Camera3Device::HalInterface::getInflightBufferKeys(
3663 std::vector<std::pair<int32_t, int32_t>>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003664 mBufferRecords.getInflightBufferKeys(out);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003665 return;
3666}
3667
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003668void Camera3Device::HalInterface::getInflightRequestBufferKeys(
3669 std::vector<uint64_t>* out) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003670 mBufferRecords.getInflightRequestBufferKeys(out);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003671 return;
3672}
3673
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003674bool Camera3Device::HalInterface::verifyBufferIds(
3675 int32_t streamId, std::vector<uint64_t>& bufIds) {
3676 return mBufferRecords.verifyBufferIds(streamId, bufIds);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003677}
3678
3679status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08003680 int32_t frameNumber, int32_t streamId,
3681 /*out*/ buffer_handle_t **buffer) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003682 return mBufferRecords.popInflightBuffer(frameNumber, streamId, buffer);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07003683}
3684
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003685status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003686 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003687 return mBufferRecords.pushInflightRequestBuffer(bufferId, buf, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003688}
3689
3690// Find and pop a buffer_handle_t based on bufferId
3691status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003692 uint64_t bufferId,
3693 /*out*/ buffer_handle_t** buffer,
3694 /*optional out*/ int32_t* streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003695 return mBufferRecords.popInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003696}
3697
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003698std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
3699 const buffer_handle_t& buf, int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003700 return mBufferRecords.getBufferId(buf, streamId);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003701}
3702
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003703void Camera3Device::HalInterface::onBufferFreed(
3704 int streamId, const native_handle_t* handle) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003705 uint32_t bufferId = mBufferRecords.removeOneBufferCache(streamId, handle);
3706 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3707 if (bufferId != BUFFER_ID_NO_BUFFER) {
3708 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003709 }
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003710}
3711
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003712void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08003713 std::vector<uint64_t> bufIds = mBufferRecords.clearBufferCaches(streamId);
3714 std::lock_guard<std::mutex> lock(mFreedBuffersLock);
3715 for (auto bufferId : bufIds) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003716 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
3717 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07003718}
3719
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003720/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003721 * RequestThread inner class methods
3722 */
3723
3724Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003725 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003726 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
3727 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003728 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003729 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003730 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003731 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07003732 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003733 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003734 mReconfigured(false),
3735 mDoPause(false),
3736 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003737 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003738 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07003739 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07003740 mCurrentAfTriggerId(0),
3741 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08003742 mRotateAndCropOverride(ANDROID_SCALER_ROTATE_AND_CROP_NONE),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003743 mRepeatingLastFrameNumber(
3744 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07003745 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003746 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003747 mRequestLatency(kRequestLatencyBinSize),
3748 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003749 mLatestSessionParams(sessionParamKeys.size()),
3750 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003751 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003752}
3753
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003754Camera3Device::RequestThread::~RequestThread() {}
3755
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07003756void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003757 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003758 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003759 Mutex::Autolock l(mRequestLock);
3760 mListener = listener;
3761}
3762
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003763void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
3764 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003765 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003766 Mutex::Autolock l(mRequestLock);
3767 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003768 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07003769 // Prepare video stream for high speed recording.
3770 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01003771 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003772}
3773
Jianing Wei90e59c92014-03-12 18:29:36 -07003774status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003775 List<sp<CaptureRequest> > &requests,
3776 /*out*/
3777 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003778 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07003779 Mutex::Autolock l(mRequestLock);
3780 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
3781 ++it) {
3782 mRequestQueue.push_back(*it);
3783 }
3784
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003785 if (lastFrameNumber != NULL) {
3786 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
3787 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
3788 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
3789 *lastFrameNumber);
3790 }
Jianing Weicb0652e2014-03-12 18:29:36 -07003791
Jianing Wei90e59c92014-03-12 18:29:36 -07003792 unpauseForNewRequests();
3793
3794 return OK;
3795}
3796
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003797
3798status_t Camera3Device::RequestThread::queueTrigger(
3799 RequestTrigger trigger[],
3800 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003801 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003802 Mutex::Autolock l(mTriggerMutex);
3803 status_t ret;
3804
3805 for (size_t i = 0; i < count; ++i) {
3806 ret = queueTriggerLocked(trigger[i]);
3807
3808 if (ret != OK) {
3809 return ret;
3810 }
3811 }
3812
3813 return OK;
3814}
3815
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003816const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
3817 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003818 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003819 if (d != nullptr) return d->mId;
3820 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003821}
3822
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003823status_t Camera3Device::RequestThread::queueTriggerLocked(
3824 RequestTrigger trigger) {
3825
3826 uint32_t tag = trigger.metadataTag;
3827 ssize_t index = mTriggerMap.indexOfKey(tag);
3828
3829 switch (trigger.getTagType()) {
3830 case TYPE_BYTE:
3831 // fall-through
3832 case TYPE_INT32:
3833 break;
3834 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003835 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
3836 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003837 return INVALID_OPERATION;
3838 }
3839
3840 /**
3841 * Collect only the latest trigger, since we only have 1 field
3842 * in the request settings per trigger tag, and can't send more than 1
3843 * trigger per request.
3844 */
3845 if (index != NAME_NOT_FOUND) {
3846 mTriggerMap.editValueAt(index) = trigger;
3847 } else {
3848 mTriggerMap.add(tag, trigger);
3849 }
3850
3851 return OK;
3852}
3853
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003854status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003855 const RequestList &requests,
3856 /*out*/
3857 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003858 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003859 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003860 if (lastFrameNumber != NULL) {
3861 *lastFrameNumber = mRepeatingLastFrameNumber;
3862 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003863 mRepeatingRequests.clear();
3864 mRepeatingRequests.insert(mRepeatingRequests.begin(),
3865 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07003866
3867 unpauseForNewRequests();
3868
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003869 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003870 return OK;
3871}
3872
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07003873bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003874 if (mRepeatingRequests.empty()) {
3875 return false;
3876 }
3877 int32_t requestId = requestIn->mResultExtras.requestId;
3878 const RequestList &repeatRequests = mRepeatingRequests;
3879 // All repeating requests are guaranteed to have same id so only check first quest
3880 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
3881 return (firstRequest->mResultExtras.requestId == requestId);
3882}
3883
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003884status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003885 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003886 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003887 return clearRepeatingRequestsLocked(lastFrameNumber);
3888
3889}
3890
3891status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003892 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003893 if (lastFrameNumber != NULL) {
3894 *lastFrameNumber = mRepeatingLastFrameNumber;
3895 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003896 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003897 return OK;
3898}
3899
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003900status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003901 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003902 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003903 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003904 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003905
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003906 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003907
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003908 // Send errors for all requests pending in the request queue, including
3909 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003910 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003911 if (listener != NULL) {
3912 for (RequestList::iterator it = mRequestQueue.begin();
3913 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003914 // Abort the input buffers for reprocess requests.
3915 if ((*it)->mInputStream != NULL) {
3916 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07003917 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
3918 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003919 if (res != OK) {
3920 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
3921 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3922 } else {
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07003923 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07003924 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
3925 if (res != OK) {
3926 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
3927 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
3928 }
3929 }
3930 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003931 // Set the frame number this request would have had, if it
3932 // had been submitted; this frame number will not be reused.
3933 // The requestId and burstId fields were set when the request was
3934 // submitted originally (in convertMetadataListToRequestListLocked)
3935 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003936 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003937 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07003938 }
3939 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003940 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08003941
3942 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003943 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07003944 if (lastFrameNumber != NULL) {
3945 *lastFrameNumber = mRepeatingLastFrameNumber;
3946 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003947 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08003948 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07003949 return OK;
3950}
3951
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003952status_t Camera3Device::RequestThread::flush() {
3953 ATRACE_CALL();
3954 Mutex::Autolock l(mFlushLock);
3955
Emilian Peev08dd2452017-04-06 16:55:14 +01003956 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07003957}
3958
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003959void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003960 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003961 Mutex::Autolock l(mPauseLock);
3962 mDoPause = paused;
3963 mDoPauseSignal.signal();
3964}
3965
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003966status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
3967 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003968 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003969 Mutex::Autolock l(mLatestRequestMutex);
3970 status_t res;
3971 while (mLatestRequestId != requestId) {
3972 nsecs_t startTime = systemTime();
3973
3974 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
3975 if (res != OK) return res;
3976
3977 timeout -= (systemTime() - startTime);
3978 }
3979
3980 return OK;
3981}
3982
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003983void Camera3Device::RequestThread::requestExit() {
3984 // Call parent to set up shutdown
3985 Thread::requestExit();
3986 // The exit from any possible waits
3987 mDoPauseSignal.signal();
3988 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07003989
3990 mRequestLatency.log("ProcessCaptureRequest latency histogram");
3991 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003992}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07003993
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07003994void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003995 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003996 bool surfaceAbandoned = false;
3997 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003998 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07003999 {
4000 Mutex::Autolock l(mRequestLock);
4001 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4002 // repeating requests.
4003 for (const auto& request : mRepeatingRequests) {
4004 for (const auto& s : request->mOutputStreams) {
4005 if (s->isAbandoned()) {
4006 surfaceAbandoned = true;
4007 clearRepeatingRequestsLocked(&lastFrameNumber);
4008 break;
4009 }
4010 }
4011 if (surfaceAbandoned) {
4012 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004013 }
4014 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004015 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004016 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004017
4018 if (listener != NULL && surfaceAbandoned) {
4019 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004020 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004021}
4022
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004023bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004024 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004025 status_t res;
4026 size_t batchSize = mNextRequests.size();
4027 std::vector<camera3_capture_request_t*> requests(batchSize);
4028 uint32_t numRequestProcessed = 0;
4029 for (size_t i = 0; i < batchSize; i++) {
4030 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004031 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004032 }
4033
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004034 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4035
4036 bool triggerRemoveFailed = false;
4037 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4038 for (size_t i = 0; i < numRequestProcessed; i++) {
4039 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4040 nextRequest.submitted = true;
4041
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004042 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00004043
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004044 if (!triggerRemoveFailed) {
4045 // Remove any previously queued triggers (after unlock)
4046 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4047 if (removeTriggerRes != OK) {
4048 triggerRemoveFailed = true;
4049 triggerFailedRequest = nextRequest;
4050 }
4051 }
4052 }
4053
4054 if (triggerRemoveFailed) {
4055 SET_ERR("RequestThread: Unable to remove triggers "
4056 "(capture request %d, HAL device: %s (%d)",
4057 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4058 cleanUpFailedRequests(/*sendRequestError*/ false);
4059 return false;
4060 }
4061
4062 if (res != OK) {
4063 // Should only get a failure here for malformed requests or device-level
4064 // errors, so consider all errors fatal. Bad metadata failures should
4065 // come through notify.
4066 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4067 mNextRequests[numRequestProcessed].halRequest.frame_number,
4068 strerror(-res), res);
4069 cleanUpFailedRequests(/*sendRequestError*/ false);
4070 return false;
4071 }
4072 return true;
4073}
4074
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004075nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4076 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4077 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4078 find_camera_metadata_ro_entry(request,
4079 ANDROID_CONTROL_AE_MODE,
4080 &e);
4081 if (e.count == 0) return maxExpectedDuration;
4082
4083 switch (e.data.u8[0]) {
4084 case ANDROID_CONTROL_AE_MODE_OFF:
4085 find_camera_metadata_ro_entry(request,
4086 ANDROID_SENSOR_EXPOSURE_TIME,
4087 &e);
4088 if (e.count > 0) {
4089 maxExpectedDuration = e.data.i64[0];
4090 }
4091 find_camera_metadata_ro_entry(request,
4092 ANDROID_SENSOR_FRAME_DURATION,
4093 &e);
4094 if (e.count > 0) {
4095 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4096 }
4097 break;
4098 default:
4099 find_camera_metadata_ro_entry(request,
4100 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4101 &e);
4102 if (e.count > 1) {
4103 maxExpectedDuration = 1e9 / e.data.u8[0];
4104 }
4105 break;
4106 }
4107
4108 return maxExpectedDuration;
4109}
4110
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004111bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4112 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4113 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4114 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4115 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4116 return true;
4117 }
4118
4119 return false;
4120}
4121
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004122void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
4123 // Update the latest request sent to HAL
4124 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4125 Mutex::Autolock al(mLatestRequestMutex);
4126
4127 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4128 mLatestRequest.acquire(cloned);
4129
4130 mLatestPhysicalRequest.clear();
4131 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
4132 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
4133 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
4134 CameraMetadata(cloned));
4135 }
4136
4137 sp<Camera3Device> parent = mParent.promote();
4138 if (parent != NULL) {
4139 parent->monitorMetadata(TagMonitor::REQUEST,
4140 nextRequest.halRequest.frame_number,
4141 0, mLatestRequest, mLatestPhysicalRequest);
4142 }
4143 }
4144
4145 if (nextRequest.halRequest.settings != NULL) {
4146 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4147 nextRequest.halRequest.settings);
4148 }
4149
4150 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4151}
4152
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004153bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4154 ATRACE_CALL();
4155 bool updatesDetected = false;
4156
Emilian Peev4ec17882019-01-24 17:16:58 -08004157 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004158 for (auto tag : mSessionParamKeys) {
4159 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004160 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004161
4162 if (entry.count > 0) {
4163 bool isDifferent = false;
4164 if (lastEntry.count > 0) {
4165 // Have a last value, compare to see if changed
4166 if (lastEntry.type == entry.type &&
4167 lastEntry.count == entry.count) {
4168 // Same type and count, compare values
4169 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4170 size_t entryBytes = bytesPerValue * lastEntry.count;
4171 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4172 if (cmp != 0) {
4173 isDifferent = true;
4174 }
4175 } else {
4176 // Count or type has changed
4177 isDifferent = true;
4178 }
4179 } else {
4180 // No last entry, so always consider to be different
4181 isDifferent = true;
4182 }
4183
4184 if (isDifferent) {
4185 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004186 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4187 updatesDetected = true;
4188 }
Emilian Peev4ec17882019-01-24 17:16:58 -08004189 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004190 }
4191 } else if (lastEntry.count > 0) {
4192 // Value has been removed
4193 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08004194 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004195 updatesDetected = true;
4196 }
4197 }
4198
Emilian Peev4ec17882019-01-24 17:16:58 -08004199 bool reconfigureRequired;
4200 if (updatesDetected) {
4201 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
4202 updatedParams);
4203 mLatestSessionParams = updatedParams;
4204 } else {
4205 reconfigureRequired = false;
4206 }
4207
4208 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004209}
4210
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004211bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004212 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004213 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08004214 // Any function called from threadLoop() must not hold mInterfaceLock since
4215 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
4216 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004217
4218 // Handle paused state.
4219 if (waitIfPaused()) {
4220 return true;
4221 }
4222
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004223 // Wait for the next batch of requests.
4224 waitForNextRequestBatch();
4225 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004226 return true;
4227 }
4228
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004229 // Get the latest request ID, if any
4230 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004231 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004232 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004233 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004234 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004235 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004236 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4237 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004238 }
4239
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004240 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4241 // or a single request from streaming or burst. In either case the first element
4242 // should contain the latest camera settings that we need to check for any session
4243 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004244 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004245 res = OK;
4246
4247 //Input stream buffers are already acquired at this point so an input stream
4248 //will not be able to move to idle state unless we force it.
4249 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4250 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4251 if (res != OK) {
4252 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4253 cleanUpFailedRequests(/*sendRequestError*/ false);
4254 return false;
4255 }
4256 }
4257
4258 if (res == OK) {
4259 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4260 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004261 sp<Camera3Device> parent = mParent.promote();
4262 if (parent != nullptr) {
4263 parent->pauseStateNotify(true);
4264 }
4265
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004266 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4267
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004268 if (parent != nullptr) {
4269 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4270 }
4271
4272 statusTracker->markComponentActive(mStatusId);
4273 setPaused(false);
4274 }
4275
4276 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4277 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4278 if (res != OK) {
4279 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4280 cleanUpFailedRequests(/*sendRequestError*/ false);
4281 return false;
4282 }
4283 }
4284 }
4285 }
4286
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004287 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004288 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004289 if (res == TIMED_OUT) {
4290 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004291 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004292 // Check if any stream is abandoned.
4293 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004294 return true;
4295 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004296 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004297 return false;
4298 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004299
Zhijun Hecc27e112013-10-03 16:12:43 -07004300 // Inform waitUntilRequestProcessed thread of a new request ID
4301 {
4302 Mutex::Autolock al(mLatestRequestMutex);
4303
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004304 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004305 mLatestRequestSignal.signal();
4306 }
4307
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004308 // Submit a batch of requests to HAL.
4309 // Use flush lock only when submitting multilple requests in a batch.
4310 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4311 // which may take a long time to finish so synchronizing flush() and
4312 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4313 // For now, only synchronize for high speed recording and we should figure something out for
4314 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004315 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004316
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004317 if (useFlushLock) {
4318 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004319 }
4320
Zhijun Hef0645c12016-08-02 00:58:11 -07004321 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004322 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004323
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08004324 sp<Camera3Device> parent = mParent.promote();
4325 if (parent != nullptr) {
4326 parent->mRequestBufferSM.onSubmittingRequest();
4327 }
4328
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004329 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004330 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07004331 submitRequestSuccess = sendRequestsBatch();
4332
Shuzhen Wang686f6442017-06-20 16:16:04 -07004333 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4334 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004335
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004336 if (useFlushLock) {
4337 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004338 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004339
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004340 // Unset as current request
4341 {
4342 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004343 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004344 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004345 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004346
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004347 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004348}
4349
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004350status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004351 ATRACE_CALL();
4352
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004353 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004354 for (size_t i = 0; i < mNextRequests.size(); i++) {
4355 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004356 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4357 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4358 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4359
4360 // Prepare a request to HAL
4361 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4362
4363 // Insert any queued triggers (before metadata is locked)
4364 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004365 if (res < 0) {
4366 SET_ERR("RequestThread: Unable to insert triggers "
4367 "(capture request %d, HAL device: %s (%d)",
4368 halRequest->frame_number, strerror(-res), res);
4369 return INVALID_OPERATION;
4370 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004371
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004372 int triggerCount = res;
4373 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4374 mPrevTriggers = triggerCount;
4375
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004376 bool rotateAndCropChanged = overrideAutoRotateAndCrop(captureRequest);
4377
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004378 // If the request is the same as last, or we had triggers last time
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004379 bool newRequest =
4380 (mPrevRequest != captureRequest || triggersMixedIn || rotateAndCropChanged) &&
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004381 // Request settings are all the same within one batch, so only treat the first
4382 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004383 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004384 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004385 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004386 /**
4387 * HAL workaround:
4388 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4389 */
4390 res = addDummyTriggerIds(captureRequest);
4391 if (res != OK) {
4392 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4393 "(capture request %d, HAL device: %s (%d)",
4394 halRequest->frame_number, strerror(-res), res);
4395 return INVALID_OPERATION;
4396 }
4397
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004398 {
4399 // Correct metadata regions for distortion correction if enabled
4400 sp<Camera3Device> parent = mParent.promote();
4401 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07004402 List<PhysicalCameraSettings>::iterator it;
4403 for (it = captureRequest->mSettingsList.begin();
4404 it != captureRequest->mSettingsList.end(); it++) {
4405 if (parent->mDistortionMappers.find(it->cameraId) ==
4406 parent->mDistortionMappers.end()) {
4407 continue;
4408 }
4409 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
4410 &(it->metadata));
4411 if (res != OK) {
4412 SET_ERR("RequestThread: Unable to correct capture requests "
4413 "for lens distortion for request %d: %s (%d)",
4414 halRequest->frame_number, strerror(-res), res);
4415 return INVALID_OPERATION;
4416 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004417 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004418
4419 for (it = captureRequest->mSettingsList.begin();
4420 it != captureRequest->mSettingsList.end(); it++) {
4421 if (parent->mZoomRatioMappers.find(it->cameraId) ==
4422 parent->mZoomRatioMappers.end()) {
4423 continue;
4424 }
4425
4426 camera_metadata_entry_t e = it->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
4427 if (e.count > 0 && e.data.f[0] != 1.0f) {
4428 cameraIdsWithZoom.insert(it->cameraId);
4429 }
4430
4431 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
4432 &(it->metadata));
4433 if (res != OK) {
4434 SET_ERR("RequestThread: Unable to correct capture requests "
4435 "for zoom ratio for request %d: %s (%d)",
4436 halRequest->frame_number, strerror(-res), res);
4437 return INVALID_OPERATION;
4438 }
4439 }
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004440 if (captureRequest->mRotateAndCropAuto) {
4441 for (it = captureRequest->mSettingsList.begin();
4442 it != captureRequest->mSettingsList.end(); it++) {
4443 auto mapper = parent->mRotateAndCropMappers.find(it->cameraId);
4444 if (mapper != parent->mRotateAndCropMappers.end()) {
4445 res = mapper->second.updateCaptureRequest(&(it->metadata));
4446 if (res != OK) {
4447 SET_ERR("RequestThread: Unable to correct capture requests "
4448 "for rotate-and-crop for request %d: %s (%d)",
4449 halRequest->frame_number, strerror(-res), res);
4450 return INVALID_OPERATION;
4451 }
4452 }
4453 }
4454 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004455 }
4456 }
4457
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004458 /**
4459 * The request should be presorted so accesses in HAL
4460 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4461 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004462 captureRequest->mSettingsList.begin()->metadata.sort();
4463 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004464 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004465 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004466 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4467
4468 IF_ALOGV() {
4469 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4470 find_camera_metadata_ro_entry(
4471 halRequest->settings,
4472 ANDROID_CONTROL_AF_TRIGGER,
4473 &e
4474 );
4475 if (e.count > 0) {
4476 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4477 __FUNCTION__,
4478 halRequest->frame_number,
4479 e.data.u8[0]);
4480 }
4481 }
4482 } else {
4483 // leave request.settings NULL to indicate 'reuse latest given'
4484 ALOGVV("%s: Request settings are REUSED",
4485 __FUNCTION__);
4486 }
4487
Emilian Peevaebbe412018-01-15 13:53:24 +00004488 if (captureRequest->mSettingsList.size() > 1) {
4489 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4490 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004491 if (newRequest) {
4492 halRequest->physcam_settings =
4493 new const camera_metadata* [halRequest->num_physcam_settings];
4494 } else {
4495 halRequest->physcam_settings = nullptr;
4496 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004497 auto it = ++captureRequest->mSettingsList.begin();
4498 size_t i = 0;
4499 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4500 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004501 if (newRequest) {
4502 it->metadata.sort();
4503 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4504 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004505 }
4506 }
4507
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004508 uint32_t totalNumBuffers = 0;
4509
4510 // Fill in buffers
4511 if (captureRequest->mInputStream != NULL) {
4512 halRequest->input_buffer = &captureRequest->mInputBuffer;
4513 totalNumBuffers += 1;
4514 } else {
4515 halRequest->input_buffer = NULL;
4516 }
4517
4518 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4519 captureRequest->mOutputStreams.size());
4520 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004521 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004522
4523 sp<Camera3Device> parent = mParent.promote();
4524 if (parent == NULL) {
4525 // Should not happen, and nowhere to send errors to, so just log it
4526 CLOGE("RequestThread: Parent is gone");
4527 return INVALID_OPERATION;
4528 }
4529 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4530
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004531 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004532 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004533 sp<Camera3OutputStreamInterface> outputStream =
4534 captureRequest->mOutputStreams.editItemAt(j);
4535 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004536
4537 // Prepare video buffers for high speed recording on the first video request.
4538 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4539 // Only try to prepare video stream on the first video request.
4540 mPrepareVideoStream = false;
4541
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004542 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4543 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004544 while (res == NOT_ENOUGH_DATA) {
4545 res = outputStream->prepareNextBuffer();
4546 }
4547 if (res != OK) {
4548 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4549 __FUNCTION__, strerror(-res), res);
4550 outputStream->cancelPrepare();
4551 }
4552 }
4553
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004554 std::vector<size_t> uniqueSurfaceIds;
4555 res = outputStream->getUniqueSurfaceIds(
4556 captureRequest->mOutputSurfaces[streamId],
4557 &uniqueSurfaceIds);
4558 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
4559 if (res != OK && res != INVALID_OPERATION) {
4560 ALOGE("%s: failed to query stream %d unique surface IDs",
4561 __FUNCTION__, streamId);
4562 return res;
4563 }
4564 if (res == OK) {
4565 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
4566 }
4567
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004568 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004569 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004570 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08004571 return TIMED_OUT;
4572 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004573 // HAL will request buffer through requestStreamBuffer API
4574 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
4575 buffer.stream = outputStream->asHalStream();
4576 buffer.buffer = nullptr;
4577 buffer.status = CAMERA3_BUFFER_STATUS_OK;
4578 buffer.acquire_fence = -1;
4579 buffer.release_fence = -1;
4580 } else {
4581 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4582 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004583 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004584 if (res != OK) {
4585 // Can't get output buffer from gralloc queue - this could be due to
4586 // abandoned queue or other consumer misbehavior, so not a fatal
4587 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07004588 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004589 " %s (%d)", strerror(-res), res);
4590
4591 return TIMED_OUT;
4592 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004593 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08004594
4595 {
4596 sp<Camera3Device> parent = mParent.promote();
4597 if (parent != nullptr) {
4598 const String8& streamCameraId = outputStream->getPhysicalCameraId();
4599 for (const auto& settings : captureRequest->mSettingsList) {
4600 if ((streamCameraId.isEmpty() &&
4601 parent->getId() == settings.cameraId.c_str()) ||
4602 streamCameraId == settings.cameraId.c_str()) {
4603 outputStream->fireBufferRequestForFrameNumber(
4604 captureRequest->mResultExtras.frameNumber,
4605 settings.metadata);
4606 }
4607 }
4608 }
4609 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004610
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004611 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4612
4613 if (!physicalCameraId.isEmpty()) {
4614 // Physical stream isn't supported for input request.
4615 if (halRequest->input_buffer) {
4616 CLOGE("Physical stream is not supported for input request");
4617 return INVALID_OPERATION;
4618 }
4619 requestedPhysicalCameras.insert(physicalCameraId);
4620 }
4621 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004622 }
4623 totalNumBuffers += halRequest->num_output_buffers;
4624
4625 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004626 // If this request list is for constrained high speed recording (not
4627 // preview), and the current request is not the last one in the batch,
4628 // do not send callback to the app.
4629 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004630 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004631 hasCallback = false;
4632 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004633 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004634 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01004635 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4636 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4637 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4638 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4639 isStillCapture = true;
4640 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4641 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004642
4643 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
4644 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4645 isZslCapture = true;
4646 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004647 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004648 res = parent->registerInFlight(halRequest->frame_number,
4649 totalNumBuffers, captureRequest->mResultExtras,
4650 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004651 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004652 calculateMaxExpectedDuration(halRequest->settings),
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004653 requestedPhysicalCameras, isStillCapture, isZslCapture,
4654 captureRequest->mRotateAndCropAuto, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004655 (mUseHalBufManager) ? uniqueSurfaceIdMap :
4656 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004657 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4658 ", burstId = %" PRId32 ".",
4659 __FUNCTION__,
4660 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4661 captureRequest->mResultExtras.burstId);
4662 if (res != OK) {
4663 SET_ERR("RequestThread: Unable to register new in-flight request:"
4664 " %s (%d)", strerror(-res), res);
4665 return INVALID_OPERATION;
4666 }
4667 }
4668
4669 return OK;
4670}
4671
Igor Murashkin1e479c02013-09-06 16:55:14 -07004672CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004673 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004674 Mutex::Autolock al(mLatestRequestMutex);
4675
4676 ALOGV("RequestThread::%s", __FUNCTION__);
4677
4678 return mLatestRequest;
4679}
4680
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004681bool Camera3Device::RequestThread::isStreamPending(
4682 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004683 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004684 Mutex::Autolock l(mRequestLock);
4685
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004686 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004687 if (!nextRequest.submitted) {
4688 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4689 if (stream == s) return true;
4690 }
4691 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004692 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004693 }
4694
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004695 for (const auto& request : mRequestQueue) {
4696 for (const auto& s : request->mOutputStreams) {
4697 if (stream == s) return true;
4698 }
4699 if (stream == request->mInputStream) return true;
4700 }
4701
4702 for (const auto& request : mRepeatingRequests) {
4703 for (const auto& s : request->mOutputStreams) {
4704 if (stream == s) return true;
4705 }
4706 if (stream == request->mInputStream) return true;
4707 }
4708
4709 return false;
4710}
Jianing Weicb0652e2014-03-12 18:29:36 -07004711
Emilian Peev40ead602017-09-26 15:46:36 +01004712bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4713 ATRACE_CALL();
4714 Mutex::Autolock l(mRequestLock);
4715
4716 for (const auto& nextRequest : mNextRequests) {
4717 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4718 if (s.first == streamId) {
4719 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4720 if (it != s.second.end()) {
4721 return true;
4722 }
4723 }
4724 }
4725 }
4726
4727 for (const auto& request : mRequestQueue) {
4728 for (const auto& s : request->mOutputSurfaces) {
4729 if (s.first == streamId) {
4730 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4731 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004732 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004733 }
4734 }
4735 }
4736 }
4737
4738 for (const auto& request : mRepeatingRequests) {
4739 for (const auto& s : request->mOutputSurfaces) {
4740 if (s.first == streamId) {
4741 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4742 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004743 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01004744 }
4745 }
4746 }
4747 }
4748
4749 return false;
4750}
4751
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004752void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
4753 if (!mUseHalBufManager) {
4754 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
4755 return;
4756 }
4757
4758 Mutex::Autolock pl(mPauseLock);
4759 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07004760 mInterface->signalPipelineDrain(streamIds);
4761 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004762 }
4763 // If request thread is still busy, wait until paused then notify HAL
4764 mNotifyPipelineDrain = true;
4765 mStreamIdsToBeDrained = streamIds;
4766}
4767
Emilian Peevc0fe54c2020-03-11 14:05:07 -07004768void Camera3Device::RequestThread::clearPreviousRequest() {
4769 Mutex::Autolock l(mRequestLock);
4770 mPrevRequest.clear();
4771}
4772
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004773status_t Camera3Device::RequestThread::switchToOffline(
4774 const std::vector<int32_t>& streamsToKeep,
4775 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004776 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession,
4777 /*out*/camera3::BufferRecords* bufferRecords) {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004778 Mutex::Autolock l(mRequestLock);
4779 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
4780
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004781 // Wait until request thread is fully stopped
4782 // TBD: check if request thread is being paused by other APIs (shouldn't be)
4783
4784 // We could also check for mRepeatingRequests.empty(), but the API interface
4785 // is serialized by Camera3Device::mInterfaceLock so no one should be able to submit any
4786 // new requests during the call; hence skip that check.
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004787 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4788 while (!queueEmpty) {
4789 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
4790 if (res == TIMED_OUT) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004791 ALOGE("%s: request thread failed to submit one request within timeout!", __FUNCTION__);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004792 return res;
4793 } else if (res != OK) {
4794 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
4795 __FUNCTION__, strerror(-res), res);
4796 return res;
4797 }
4798 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
4799 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004800
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004801 return mInterface->switchToOffline(
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004802 streamsToKeep, offlineSessionInfo, offlineSession, bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004803}
4804
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08004805status_t Camera3Device::RequestThread::setRotateAndCropAutoBehavior(
4806 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
4807 ATRACE_CALL();
4808 Mutex::Autolock l(mTriggerMutex);
4809 if (rotateAndCropValue == ANDROID_SCALER_ROTATE_AND_CROP_AUTO) {
4810 return BAD_VALUE;
4811 }
4812 mRotateAndCropOverride = rotateAndCropValue;
4813 return OK;
4814}
4815
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07004816nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004817 ATRACE_CALL();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004818 std::lock_guard<std::mutex> l(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004819 return mExpectedInflightDuration > kMinInflightDuration ?
4820 mExpectedInflightDuration : kMinInflightDuration;
4821}
4822
Emilian Peevaebbe412018-01-15 13:53:24 +00004823void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
4824 camera3_capture_request_t *halRequest) {
4825 if ((request == nullptr) || (halRequest == nullptr)) {
4826 ALOGE("%s: Invalid request!", __FUNCTION__);
4827 return;
4828 }
4829
4830 if (halRequest->num_physcam_settings > 0) {
4831 if (halRequest->physcam_id != nullptr) {
4832 delete [] halRequest->physcam_id;
4833 halRequest->physcam_id = nullptr;
4834 }
4835 if (halRequest->physcam_settings != nullptr) {
4836 auto it = ++(request->mSettingsList.begin());
4837 size_t i = 0;
4838 for (; it != request->mSettingsList.end(); it++, i++) {
4839 it->metadata.unlock(halRequest->physcam_settings[i]);
4840 }
4841 delete [] halRequest->physcam_settings;
4842 halRequest->physcam_settings = nullptr;
4843 }
4844 }
4845}
4846
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004847void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
4848 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004849 return;
4850 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004851
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004852 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004853 // Skip the ones that have been submitted successfully.
4854 if (nextRequest.submitted) {
4855 continue;
4856 }
4857
4858 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4859 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4860 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4861
4862 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004863 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004864 }
4865
Emilian Peevaebbe412018-01-15 13:53:24 +00004866 cleanupPhysicalSettings(captureRequest, halRequest);
4867
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004868 if (captureRequest->mInputStream != NULL) {
4869 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
4870 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
4871 }
4872
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08004873 // No output buffer can be returned when using HAL buffer manager
4874 if (!mUseHalBufManager) {
4875 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
4876 //Buffers that failed processing could still have
4877 //valid acquire fence.
4878 int acquireFence = (*outputBuffers)[i].acquire_fence;
4879 if (0 <= acquireFence) {
4880 close(acquireFence);
4881 outputBuffers->editItemAt(i).acquire_fence = -1;
4882 }
4883 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
4884 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
4885 /*timestampIncreasing*/true, std::vector<size_t> (),
4886 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01004887 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004888 }
4889
4890 if (sendRequestError) {
4891 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004892 sp<NotificationListener> listener = mListener.promote();
4893 if (listener != NULL) {
4894 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004895 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004896 captureRequest->mResultExtras);
4897 }
4898 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004899
4900 // Remove yet-to-be submitted inflight request from inflightMap
4901 {
4902 sp<Camera3Device> parent = mParent.promote();
4903 if (parent != NULL) {
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08004904 std::lock_guard<std::mutex> l(parent->mInFlightLock);
Shuzhen Wangcadb3302016-11-04 14:17:56 -07004905 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
4906 if (idx >= 0) {
4907 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
4908 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
4909 parent->removeInFlightMapEntryLocked(idx);
4910 }
4911 }
4912 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004913 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004914
4915 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004916 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004917}
4918
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004919void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004920 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004921 // Optimized a bit for the simple steady-state case (single repeating
4922 // request), to avoid putting that request in the queue temporarily.
4923 Mutex::Autolock l(mRequestLock);
4924
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004925 assert(mNextRequests.empty());
4926
4927 NextRequest nextRequest;
4928 nextRequest.captureRequest = waitForNextRequestLocked();
4929 if (nextRequest.captureRequest == nullptr) {
4930 return;
4931 }
4932
4933 nextRequest.halRequest = camera3_capture_request_t();
4934 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004935 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004936
4937 // Wait for additional requests
4938 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
4939
4940 for (size_t i = 1; i < batchSize; i++) {
4941 NextRequest additionalRequest;
4942 additionalRequest.captureRequest = waitForNextRequestLocked();
4943 if (additionalRequest.captureRequest == nullptr) {
4944 break;
4945 }
4946
4947 additionalRequest.halRequest = camera3_capture_request_t();
4948 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004949 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004950 }
4951
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004952 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08004953 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004954 mNextRequests.size(), batchSize);
4955 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004956 }
4957
4958 return;
4959}
4960
4961sp<Camera3Device::CaptureRequest>
4962 Camera3Device::RequestThread::waitForNextRequestLocked() {
4963 status_t res;
4964 sp<CaptureRequest> nextRequest;
4965
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004966 while (mRequestQueue.empty()) {
4967 if (!mRepeatingRequests.empty()) {
4968 // Always atomically enqueue all requests in a repeating request
4969 // list. Guarantees a complete in-sequence set of captures to
4970 // application.
4971 const RequestList &requests = mRepeatingRequests;
4972 RequestList::const_iterator firstRequest =
4973 requests.begin();
4974 nextRequest = *firstRequest;
4975 mRequestQueue.insert(mRequestQueue.end(),
4976 ++firstRequest,
4977 requests.end());
4978 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07004979
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004980 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07004981
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004982 break;
4983 }
4984
4985 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
4986
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004987 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
4988 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004989 Mutex::Autolock pl(mPauseLock);
4990 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004991 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004992 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004993 if (mNotifyPipelineDrain) {
4994 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
4995 mNotifyPipelineDrain = false;
4996 mStreamIdsToBeDrained.clear();
4997 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004998 // Let the tracker know
4999 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5000 if (statusTracker != 0) {
5001 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5002 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005003 sp<Camera3Device> parent = mParent.promote();
5004 if (parent != nullptr) {
5005 parent->mRequestBufferSM.onRequestThreadPaused();
5006 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005007 }
5008 // Stop waiting for now and let thread management happen
5009 return NULL;
5010 }
5011 }
5012
5013 if (nextRequest == NULL) {
5014 // Don't have a repeating request already in hand, so queue
5015 // must have an entry now.
5016 RequestList::iterator firstRequest =
5017 mRequestQueue.begin();
5018 nextRequest = *firstRequest;
5019 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005020 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5021 sp<NotificationListener> listener = mListener.promote();
5022 if (listener != NULL) {
5023 listener->notifyRequestQueueEmpty();
5024 }
5025 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005026 }
5027
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005028 // In case we've been unpaused by setPaused clearing mDoPause, need to
5029 // update internal pause state (capture/setRepeatingRequest unpause
5030 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005031 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005032 if (mPaused) {
5033 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5034 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5035 if (statusTracker != 0) {
5036 statusTracker->markComponentActive(mStatusId);
5037 }
5038 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005039 mPaused = false;
5040
5041 // Check if we've reconfigured since last time, and reset the preview
5042 // request if so. Can't use 'NULL request == repeat' across configure calls.
5043 if (mReconfigured) {
5044 mPrevRequest.clear();
5045 mReconfigured = false;
5046 }
5047
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005048 if (nextRequest != NULL) {
5049 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005050 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5051 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005052
5053 // Since RequestThread::clear() removes buffers from the input stream,
5054 // get the right buffer here before unlocking mRequestLock
5055 if (nextRequest->mInputStream != NULL) {
5056 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5057 if (res != OK) {
5058 // Can't get input buffer from gralloc queue - this could be due to
5059 // disconnected queue or other producer misbehavior, so not a fatal
5060 // error
5061 ALOGE("%s: Can't get input buffer, skipping request:"
5062 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005063
5064 sp<NotificationListener> listener = mListener.promote();
5065 if (listener != NULL) {
5066 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005067 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005068 nextRequest->mResultExtras);
5069 }
5070 return NULL;
5071 }
5072 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005073 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005074
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005075 return nextRequest;
5076}
5077
5078bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005079 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005080 status_t res;
5081 Mutex::Autolock l(mPauseLock);
5082 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005083 if (mPaused == false) {
5084 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005085 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005086 if (mNotifyPipelineDrain) {
5087 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5088 mNotifyPipelineDrain = false;
5089 mStreamIdsToBeDrained.clear();
5090 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005091 // Let the tracker know
5092 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5093 if (statusTracker != 0) {
5094 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5095 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005096 sp<Camera3Device> parent = mParent.promote();
5097 if (parent != nullptr) {
5098 parent->mRequestBufferSM.onRequestThreadPaused();
5099 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005100 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005101
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005102 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005103 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005104 return true;
5105 }
5106 }
5107 // We don't set mPaused to false here, because waitForNextRequest needs
5108 // to further manage the paused state in case of starvation.
5109 return false;
5110}
5111
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005112void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005113 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005114 // With work to do, mark thread as unpaused.
5115 // If paused by request (setPaused), don't resume, to avoid
5116 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005117 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005118 Mutex::Autolock p(mPauseLock);
5119 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005120 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5121 if (mPaused) {
5122 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5123 if (statusTracker != 0) {
5124 statusTracker->markComponentActive(mStatusId);
5125 }
5126 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005127 mPaused = false;
5128 }
5129}
5130
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005131void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5132 sp<Camera3Device> parent = mParent.promote();
5133 if (parent != NULL) {
5134 va_list args;
5135 va_start(args, fmt);
5136
5137 parent->setErrorStateV(fmt, args);
5138
5139 va_end(args);
5140 }
5141}
5142
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005143status_t Camera3Device::RequestThread::insertTriggers(
5144 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005145 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005146 Mutex::Autolock al(mTriggerMutex);
5147
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005148 sp<Camera3Device> parent = mParent.promote();
5149 if (parent == NULL) {
5150 CLOGE("RequestThread: Parent is gone");
5151 return DEAD_OBJECT;
5152 }
5153
Emilian Peevaebbe412018-01-15 13:53:24 +00005154 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005155 size_t count = mTriggerMap.size();
5156
5157 for (size_t i = 0; i < count; ++i) {
5158 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005159 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005160
5161 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5162 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5163 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005164 if (isAeTrigger) {
5165 request->mResultExtras.precaptureTriggerId = triggerId;
5166 mCurrentPreCaptureTriggerId = triggerId;
5167 } else {
5168 request->mResultExtras.afTriggerId = triggerId;
5169 mCurrentAfTriggerId = triggerId;
5170 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005171 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005172 }
5173
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005174 camera_metadata_entry entry = metadata.find(tag);
5175
5176 if (entry.count > 0) {
5177 /**
5178 * Already has an entry for this trigger in the request.
5179 * Rewrite it with our requested trigger value.
5180 */
5181 RequestTrigger oldTrigger = trigger;
5182
5183 oldTrigger.entryValue = entry.data.u8[0];
5184
5185 mTriggerReplacedMap.add(tag, oldTrigger);
5186 } else {
5187 /**
5188 * More typical, no trigger entry, so we just add it
5189 */
5190 mTriggerRemovedMap.add(tag, trigger);
5191 }
5192
5193 status_t res;
5194
5195 switch (trigger.getTagType()) {
5196 case TYPE_BYTE: {
5197 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5198 res = metadata.update(tag,
5199 &entryValue,
5200 /*count*/1);
5201 break;
5202 }
5203 case TYPE_INT32:
5204 res = metadata.update(tag,
5205 &trigger.entryValue,
5206 /*count*/1);
5207 break;
5208 default:
5209 ALOGE("%s: Type not supported: 0x%x",
5210 __FUNCTION__,
5211 trigger.getTagType());
5212 return INVALID_OPERATION;
5213 }
5214
5215 if (res != OK) {
5216 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5217 ", value %d", __FUNCTION__, trigger.getTagName(),
5218 trigger.entryValue);
5219 return res;
5220 }
5221
5222 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5223 trigger.getTagName(),
5224 trigger.entryValue);
5225 }
5226
5227 mTriggerMap.clear();
5228
5229 return count;
5230}
5231
5232status_t Camera3Device::RequestThread::removeTriggers(
5233 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005234 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005235 Mutex::Autolock al(mTriggerMutex);
5236
Emilian Peevaebbe412018-01-15 13:53:24 +00005237 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005238
5239 /**
5240 * Replace all old entries with their old values.
5241 */
5242 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5243 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5244
5245 status_t res;
5246
5247 uint32_t tag = trigger.metadataTag;
5248 switch (trigger.getTagType()) {
5249 case TYPE_BYTE: {
5250 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5251 res = metadata.update(tag,
5252 &entryValue,
5253 /*count*/1);
5254 break;
5255 }
5256 case TYPE_INT32:
5257 res = metadata.update(tag,
5258 &trigger.entryValue,
5259 /*count*/1);
5260 break;
5261 default:
5262 ALOGE("%s: Type not supported: 0x%x",
5263 __FUNCTION__,
5264 trigger.getTagType());
5265 return INVALID_OPERATION;
5266 }
5267
5268 if (res != OK) {
5269 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5270 ", trigger value %d", __FUNCTION__,
5271 trigger.getTagName(), trigger.entryValue);
5272 return res;
5273 }
5274 }
5275 mTriggerReplacedMap.clear();
5276
5277 /**
5278 * Remove all new entries.
5279 */
5280 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5281 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5282 status_t res = metadata.erase(trigger.metadataTag);
5283
5284 if (res != OK) {
5285 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5286 ", trigger value %d", __FUNCTION__,
5287 trigger.getTagName(), trigger.entryValue);
5288 return res;
5289 }
5290 }
5291 mTriggerRemovedMap.clear();
5292
5293 return OK;
5294}
5295
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005296status_t Camera3Device::RequestThread::addDummyTriggerIds(
5297 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005298 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005299 static const int32_t dummyTriggerId = 1;
5300 status_t res;
5301
Emilian Peevaebbe412018-01-15 13:53:24 +00005302 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005303
5304 // If AF trigger is active, insert a dummy AF trigger ID if none already
5305 // exists
5306 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5307 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5308 if (afTrigger.count > 0 &&
5309 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5310 afId.count == 0) {
5311 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5312 if (res != OK) return res;
5313 }
5314
5315 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5316 // if none already exists
5317 camera_metadata_entry pcTrigger =
5318 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5319 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5320 if (pcTrigger.count > 0 &&
5321 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5322 pcId.count == 0) {
5323 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5324 &dummyTriggerId, 1);
5325 if (res != OK) return res;
5326 }
5327
5328 return OK;
5329}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005330
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005331bool Camera3Device::RequestThread::overrideAutoRotateAndCrop(
5332 const sp<CaptureRequest> &request) {
5333 ATRACE_CALL();
5334
5335 if (request->mRotateAndCropAuto) {
5336 Mutex::Autolock l(mTriggerMutex);
5337 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
5338
5339 auto rotateAndCropEntry = metadata.find(ANDROID_SCALER_ROTATE_AND_CROP);
5340 if (rotateAndCropEntry.count > 0) {
5341 if (rotateAndCropEntry.data.u8[0] == mRotateAndCropOverride) {
5342 return false;
5343 } else {
5344 rotateAndCropEntry.data.u8[0] = mRotateAndCropOverride;
5345 return true;
5346 }
5347 } else {
5348 uint8_t rotateAndCrop_u8 = mRotateAndCropOverride;
5349 metadata.update(ANDROID_SCALER_ROTATE_AND_CROP,
5350 &rotateAndCrop_u8, 1);
5351 return true;
5352 }
5353 }
5354 return false;
5355}
5356
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005357/**
5358 * PreparerThread inner class methods
5359 */
5360
5361Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005362 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005363 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005364}
5365
5366Camera3Device::PreparerThread::~PreparerThread() {
5367 Thread::requestExitAndWait();
5368 if (mCurrentStream != nullptr) {
5369 mCurrentStream->cancelPrepare();
5370 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5371 mCurrentStream.clear();
5372 }
5373 clear();
5374}
5375
Ruben Brunkc78ac262015-08-13 17:58:46 -07005376status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005377 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005378 status_t res;
5379
5380 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005381 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005382
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005383 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005384 if (res == OK) {
5385 // No preparation needed, fire listener right off
5386 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005387 if (listener != NULL) {
5388 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005389 }
5390 return OK;
5391 } else if (res != NOT_ENOUGH_DATA) {
5392 return res;
5393 }
5394
5395 // Need to prepare, start up thread if necessary
5396 if (!mActive) {
5397 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5398 // isn't running
5399 Thread::requestExitAndWait();
5400 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5401 if (res != OK) {
5402 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005403 if (listener != NULL) {
5404 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005405 }
5406 return res;
5407 }
5408 mCancelNow = false;
5409 mActive = true;
5410 ALOGV("%s: Preparer stream started", __FUNCTION__);
5411 }
5412
5413 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005414 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005415 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5416
5417 return OK;
5418}
5419
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005420void Camera3Device::PreparerThread::pause() {
5421 ATRACE_CALL();
5422
5423 Mutex::Autolock l(mLock);
5424
5425 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5426 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5427 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5428 int currentMaxCount = mCurrentMaxCount;
5429 mPendingStreams.clear();
5430 mCancelNow = true;
5431 while (mActive) {
5432 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5433 if (res == TIMED_OUT) {
5434 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5435 return;
5436 } else if (res != OK) {
5437 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5438 return;
5439 }
5440 }
5441
5442 //Check whether the prepare thread was able to complete the current
5443 //stream. In case work is still pending emplace it along with the rest
5444 //of the streams in the pending list.
5445 if (currentStream != nullptr) {
5446 if (!mCurrentPrepareComplete) {
5447 pendingStreams.emplace(currentMaxCount, currentStream);
5448 }
5449 }
5450
5451 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5452 for (const auto& it : mPendingStreams) {
5453 it.second->cancelPrepare();
5454 }
5455}
5456
5457status_t Camera3Device::PreparerThread::resume() {
5458 ATRACE_CALL();
5459 status_t res;
5460
5461 Mutex::Autolock l(mLock);
5462 sp<NotificationListener> listener = mListener.promote();
5463
5464 if (mActive) {
5465 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5466 return NO_INIT;
5467 }
5468
5469 auto it = mPendingStreams.begin();
5470 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005471 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005472 if (res == OK) {
5473 if (listener != NULL) {
5474 listener->notifyPrepared(it->second->getId());
5475 }
5476 it = mPendingStreams.erase(it);
5477 } else if (res != NOT_ENOUGH_DATA) {
5478 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5479 res, strerror(-res));
5480 it = mPendingStreams.erase(it);
5481 } else {
5482 it++;
5483 }
5484 }
5485
5486 if (mPendingStreams.empty()) {
5487 return OK;
5488 }
5489
5490 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5491 if (res != OK) {
5492 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5493 __FUNCTION__, res, strerror(-res));
5494 return res;
5495 }
5496 mCancelNow = false;
5497 mActive = true;
5498 ALOGV("%s: Preparer stream started", __FUNCTION__);
5499
5500 return OK;
5501}
5502
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005503status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005504 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005505 Mutex::Autolock l(mLock);
5506
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005507 for (const auto& it : mPendingStreams) {
5508 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005509 }
5510 mPendingStreams.clear();
5511 mCancelNow = true;
5512
5513 return OK;
5514}
5515
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005516void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005517 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005518 Mutex::Autolock l(mLock);
5519 mListener = listener;
5520}
5521
5522bool Camera3Device::PreparerThread::threadLoop() {
5523 status_t res;
5524 {
5525 Mutex::Autolock l(mLock);
5526 if (mCurrentStream == nullptr) {
5527 // End thread if done with work
5528 if (mPendingStreams.empty()) {
5529 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5530 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5531 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5532 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005533 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005534 return false;
5535 }
5536
5537 // Get next stream to prepare
5538 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005539 mCurrentStream = it->second;
5540 mCurrentMaxCount = it->first;
5541 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005542 mPendingStreams.erase(it);
5543 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5544 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5545 } else if (mCancelNow) {
5546 mCurrentStream->cancelPrepare();
5547 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5548 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5549 mCurrentStream.clear();
5550 mCancelNow = false;
5551 return true;
5552 }
5553 }
5554
5555 res = mCurrentStream->prepareNextBuffer();
5556 if (res == NOT_ENOUGH_DATA) return true;
5557 if (res != OK) {
5558 // Something bad happened; try to recover by cancelling prepare and
5559 // signalling listener anyway
5560 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5561 mCurrentStream->getId(), res, strerror(-res));
5562 mCurrentStream->cancelPrepare();
5563 }
5564
5565 // This stream has finished, notify listener
5566 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005567 sp<NotificationListener> listener = mListener.promote();
5568 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005569 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5570 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005571 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005572 }
5573
5574 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5575 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005576 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005577
5578 return true;
5579}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005580
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005581status_t Camera3Device::RequestBufferStateMachine::initialize(
5582 sp<camera3::StatusTracker> statusTracker) {
5583 if (statusTracker == nullptr) {
5584 ALOGE("%s: statusTracker is null", __FUNCTION__);
5585 return BAD_VALUE;
5586 }
5587
5588 std::lock_guard<std::mutex> lock(mLock);
5589 mStatusTracker = statusTracker;
5590 mRequestBufferStatusId = statusTracker->addComponent();
5591 return OK;
5592}
5593
5594bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
5595 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005596 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005597 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005598 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005599 return true;
5600 }
5601 return false;
5602}
5603
5604void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
5605 std::lock_guard<std::mutex> lock(mLock);
5606 if (!mRequestBufferOngoing) {
5607 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
5608 return;
5609 }
5610 mRequestBufferOngoing = false;
5611 if (mStatus == RB_STATUS_PENDING_STOP) {
5612 checkSwitchToStopLocked();
5613 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08005614 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005615}
5616
5617void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
5618 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005619 mSwitchedToOffline = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005620 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005621 return;
5622}
5623
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005624void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005625 std::lock_guard<std::mutex> lock(mLock);
5626 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005627 // inflight map register actually happens in prepareHalRequest now, but it is close enough
5628 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005629 mInflightMapEmpty = false;
5630 if (mStatus == RB_STATUS_STOPPED) {
5631 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005632 }
5633 return;
5634}
5635
5636void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
5637 std::lock_guard<std::mutex> lock(mLock);
5638 mRequestThreadPaused = true;
5639 if (mStatus == RB_STATUS_PENDING_STOP) {
5640 checkSwitchToStopLocked();
5641 }
5642 return;
5643}
5644
5645void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
5646 std::lock_guard<std::mutex> lock(mLock);
5647 mInflightMapEmpty = true;
5648 if (mStatus == RB_STATUS_PENDING_STOP) {
5649 checkSwitchToStopLocked();
5650 }
5651 return;
5652}
5653
5654void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
5655 std::lock_guard<std::mutex> lock(mLock);
5656 if (!checkSwitchToStopLocked()) {
5657 mStatus = RB_STATUS_PENDING_STOP;
5658 }
5659 return;
5660}
5661
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005662bool Camera3Device::RequestBufferStateMachine::onSwitchToOfflineSuccess() {
5663 std::lock_guard<std::mutex> lock(mLock);
5664 if (mRequestBufferOngoing) {
5665 ALOGE("%s: HAL must not be requesting buffer after HAL returns switchToOffline!",
5666 __FUNCTION__);
5667 return false;
5668 }
5669 mSwitchedToOffline = true;
5670 mInflightMapEmpty = true;
5671 mRequestThreadPaused = true;
5672 mStatus = RB_STATUS_STOPPED;
5673 return true;
5674}
5675
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005676void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
5677 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5678 if (statusTracker != nullptr) {
5679 if (active) {
5680 statusTracker->markComponentActive(mRequestBufferStatusId);
5681 } else {
5682 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
5683 }
5684 }
5685}
5686
5687bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
5688 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
5689 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005690 return true;
5691 }
5692 return false;
5693}
5694
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005695bool Camera3Device::startRequestBuffer() {
5696 return mRequestBufferSM.startRequestBuffer();
5697}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005698
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005699void Camera3Device::endRequestBuffer() {
5700 mRequestBufferSM.endRequestBuffer();
5701}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005702
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005703nsecs_t Camera3Device::getWaitDuration() {
5704 return kBaseGetBufferWait + getExpectedInFlightDuration();
5705}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005706
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005707void Camera3Device::getInflightBufferKeys(std::vector<std::pair<int32_t, int32_t>>* out) {
5708 mInterface->getInflightBufferKeys(out);
5709}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005710
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005711void Camera3Device::getInflightRequestBufferKeys(std::vector<uint64_t>* out) {
5712 mInterface->getInflightRequestBufferKeys(out);
5713}
Shuzhen Wang268a1362018-10-16 16:32:59 -07005714
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005715std::vector<sp<Camera3StreamInterface>> Camera3Device::getAllStreams() {
5716 std::vector<sp<Camera3StreamInterface>> ret;
5717 bool hasInputStream = mInputStream != nullptr;
5718 ret.reserve(mOutputStreams.size() + mDeletedStreams.size() + ((hasInputStream) ? 1 : 0));
5719 if (hasInputStream) {
5720 ret.push_back(mInputStream);
Shuzhen Wang268a1362018-10-16 16:32:59 -07005721 }
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005722 for (size_t i = 0; i < mOutputStreams.size(); i++) {
5723 ret.push_back(mOutputStreams[i]);
5724 }
5725 for (size_t i = 0; i < mDeletedStreams.size(); i++) {
5726 ret.push_back(mDeletedStreams[i]);
5727 }
5728 return ret;
Shuzhen Wang268a1362018-10-16 16:32:59 -07005729}
5730
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005731status_t Camera3Device::switchToOffline(
5732 const std::vector<int32_t>& streamsToKeep,
5733 /*out*/ sp<CameraOfflineSessionBase>* session) {
5734 ATRACE_CALL();
5735 if (session == nullptr) {
5736 ALOGE("%s: session must not be null", __FUNCTION__);
5737 return BAD_VALUE;
5738 }
5739
5740 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005741
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005742 bool hasInputStream = mInputStream != nullptr;
5743 int32_t inputStreamId = hasInputStream ? mInputStream->getId() : -1;
5744 bool inputStreamSupportsOffline = hasInputStream ?
5745 mInputStream->getOfflineProcessingSupport() : false;
5746 auto outputStreamIds = mOutputStreams.getStreamIds();
5747 auto streamIds = outputStreamIds;
5748 if (hasInputStream) {
5749 streamIds.push_back(mInputStream->getId());
5750 }
5751
5752 // Check all streams in streamsToKeep supports offline mode
5753 for (auto id : streamsToKeep) {
5754 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5755 ALOGE("%s: Unknown stream ID %d", __FUNCTION__, id);
5756 return BAD_VALUE;
5757 } else if (id == inputStreamId) {
5758 if (!inputStreamSupportsOffline) {
5759 ALOGE("%s: input stream %d cannot be switched to offline",
5760 __FUNCTION__, id);
5761 return BAD_VALUE;
5762 }
5763 } else {
5764 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
5765 if (!stream->getOfflineProcessingSupport()) {
5766 ALOGE("%s: output stream %d cannot be switched to offline",
5767 __FUNCTION__, id);
5768 return BAD_VALUE;
5769 }
5770 }
5771 }
5772
5773 // TODO: block surface sharing and surface group streams until we can support them
5774
5775 // Stop repeating request, wait until all remaining requests are submitted, then call into
5776 // HAL switchToOffline
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005777 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
5778 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005779 camera3::BufferRecords bufferRecords;
5780 status_t ret = mRequestThread->switchToOffline(
5781 streamsToKeep, &offlineSessionInfo, &offlineSession, &bufferRecords);
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005782
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005783 if (ret != OK) {
5784 SET_ERR("Switch to offline failed: %s (%d)", strerror(-ret), ret);
5785 return ret;
5786 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005787
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005788 bool succ = mRequestBufferSM.onSwitchToOfflineSuccess();
5789 if (!succ) {
5790 SET_ERR("HAL must not be calling requestStreamBuffers call");
5791 // TODO: block ALL callbacks from HAL till app configured new streams?
5792 return UNKNOWN_ERROR;
5793 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005794
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005795 // Verify offlineSessionInfo
5796 std::vector<int32_t> offlineStreamIds;
5797 offlineStreamIds.reserve(offlineSessionInfo.offlineStreams.size());
5798 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5799 // verify stream IDs
5800 int32_t id = offlineStream.id;
5801 if (std::find(streamIds.begin(), streamIds.end(), id) == streamIds.end()) {
5802 SET_ERR("stream ID %d not found!", id);
5803 return UNKNOWN_ERROR;
5804 }
5805
5806 // When not using HAL buf manager, only allow streams requested by app to be preserved
5807 if (!mUseHalBufManager) {
5808 if (std::find(streamsToKeep.begin(), streamsToKeep.end(), id) == streamsToKeep.end()) {
5809 SET_ERR("stream ID %d must not be switched to offline!", id);
5810 return UNKNOWN_ERROR;
5811 }
5812 }
5813
5814 offlineStreamIds.push_back(id);
5815 sp<Camera3StreamInterface> stream = (id == inputStreamId) ?
5816 static_cast<sp<Camera3StreamInterface>>(mInputStream) :
5817 static_cast<sp<Camera3StreamInterface>>(mOutputStreams.get(id));
5818 // Verify number of outstanding buffers
5819 if (stream->getOutstandingBuffersCount() != offlineStream.numOutstandingBuffers) {
5820 SET_ERR("Offline stream %d # of remaining buffer mismatch: (%zu,%d) (service/HAL)",
5821 id, stream->getOutstandingBuffersCount(), offlineStream.numOutstandingBuffers);
5822 return UNKNOWN_ERROR;
5823 }
5824 }
5825
5826 // Verify all streams to be deleted don't have any outstanding buffers
5827 if (hasInputStream && std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5828 inputStreamId) == offlineStreamIds.end()) {
5829 if (mInputStream->hasOutstandingBuffers()) {
5830 SET_ERR("Input stream %d still has %zu outstanding buffer!",
5831 inputStreamId, mInputStream->getOutstandingBuffersCount());
5832 return UNKNOWN_ERROR;
5833 }
5834 }
5835
5836 for (const auto& outStreamId : outputStreamIds) {
5837 if (std::find(offlineStreamIds.begin(), offlineStreamIds.end(),
5838 outStreamId) == offlineStreamIds.end()) {
5839 auto outStream = mOutputStreams.get(outStreamId);
5840 if (outStream->hasOutstandingBuffers()) {
5841 SET_ERR("Output stream %d still has %zu outstanding buffer!",
5842 outStreamId, outStream->getOutstandingBuffersCount());
5843 return UNKNOWN_ERROR;
5844 }
5845 }
5846 }
5847
5848 InFlightRequestMap offlineReqs;
5849 // Verify inflight requests and their pending buffers
5850 {
5851 std::lock_guard<std::mutex> l(mInFlightLock);
5852 for (auto offlineReq : offlineSessionInfo.offlineRequests) {
5853 int idx = mInFlightMap.indexOfKey(offlineReq.frameNumber);
5854 if (idx == NAME_NOT_FOUND) {
5855 SET_ERR("Offline request frame number %d not found!", offlineReq.frameNumber);
5856 return UNKNOWN_ERROR;
5857 }
5858
5859 const auto& inflightReq = mInFlightMap.valueAt(idx);
5860 // TODO: check specific stream IDs
5861 size_t numBuffersLeft = static_cast<size_t>(inflightReq.numBuffersLeft);
5862 if (numBuffersLeft != offlineReq.pendingStreams.size()) {
5863 SET_ERR("Offline request # of remaining buffer mismatch: (%d,%d) (service/HAL)",
5864 inflightReq.numBuffersLeft, offlineReq.pendingStreams.size());
5865 return UNKNOWN_ERROR;
5866 }
5867 offlineReqs.add(offlineReq.frameNumber, inflightReq);
5868 }
5869 }
5870
5871 // Create Camera3OfflineSession and transfer object ownership
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005872 // (streams, inflight requests, buffer caches)
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005873 camera3::StreamSet offlineStreamSet;
5874 sp<camera3::Camera3Stream> inputStream;
5875 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5876 int32_t id = offlineStream.id;
5877 if (mInputStream != nullptr && id == mInputStream->getId()) {
5878 inputStream = mInputStream;
5879 } else {
5880 offlineStreamSet.add(id, mOutputStreams.get(id));
5881 }
5882 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005883
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005884 // TODO: check if we need to lock before copying states
5885 // though technically no other thread should be talking to Camera3Device at this point
5886 Camera3OfflineStates offlineStates(
5887 mTagMonitor, mVendorTagId, mUseHalBufManager, mNeedFixupMonochromeTags,
5888 mUsePartialResult, mNumPartialResults, mNextResultFrameNumber,
5889 mNextReprocessResultFrameNumber, mNextZslStillResultFrameNumber,
5890 mNextShutterFrameNumber, mNextReprocessShutterFrameNumber,
5891 mNextZslStillShutterFrameNumber, mDeviceInfo, mPhysicalDeviceInfoMap,
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005892 mDistortionMappers, mZoomRatioMappers, mRotateAndCropMappers);
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005893
5894 *session = new Camera3OfflineSession(mId, inputStream, offlineStreamSet,
5895 std::move(bufferRecords), offlineReqs, offlineStates, offlineSession);
5896
5897 // Delete all streams that has been transferred to offline session
5898 Mutex::Autolock l(mLock);
5899 for (auto offlineStream : offlineSessionInfo.offlineStreams) {
5900 int32_t id = offlineStream.id;
5901 if (mInputStream != nullptr && id == mInputStream->getId()) {
5902 mInputStream.clear();
5903 } else {
5904 mOutputStreams.remove(id);
5905 }
5906 }
5907
5908 // disconnect all other streams and switch to UNCONFIGURED state
5909 if (mInputStream != nullptr) {
5910 ret = mInputStream->disconnect();
5911 if (ret != OK) {
5912 SET_ERR_L("disconnect input stream failed!");
5913 return UNKNOWN_ERROR;
5914 }
5915 }
5916
5917 for (auto streamId : mOutputStreams.getStreamIds()) {
5918 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
5919 ret = stream->disconnect();
5920 if (ret != OK) {
5921 SET_ERR_L("disconnect output stream %d failed!", streamId);
5922 return UNKNOWN_ERROR;
5923 }
5924 }
5925
5926 mInputStream.clear();
5927 mOutputStreams.clear();
5928 mNeedConfig = true;
5929 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
5930 mOperatingMode = NO_MODE;
5931 mIsConstrainedHighSpeedConfiguration = false;
Emilian Peevc0fe54c2020-03-11 14:05:07 -07005932 mRequestThread->clearPreviousRequest();
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005933
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005934 return OK;
Yin-Chia Yeh5fd603e2019-11-20 11:22:27 -08005935 // TO be done by CameraDeviceClient/Camera3OfflineSession
5936 // register the offline client to camera service
5937 // Setup result passthing threads etc
5938 // Initialize offline session so HAL can start sending callback to it (result Fmq)
5939 // TODO: check how many onIdle callback will be sent
5940 // Java side to make sure the CameraCaptureSession is properly closed
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005941}
5942
Emilian Peevcc0b7952020-01-07 13:54:47 -08005943void Camera3Device::getOfflineStreamIds(std::vector<int> *offlineStreamIds) {
5944 ATRACE_CALL();
5945
5946 if (offlineStreamIds == nullptr) {
5947 return;
5948 }
5949
5950 Mutex::Autolock il(mInterfaceLock);
5951
5952 auto streamIds = mOutputStreams.getStreamIds();
5953 bool hasInputStream = mInputStream != nullptr;
5954 if (hasInputStream && mInputStream->getOfflineProcessingSupport()) {
5955 offlineStreamIds->push_back(mInputStream->getId());
5956 }
5957
5958 for (const auto & streamId : streamIds) {
5959 sp<camera3::Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
5960 // Streams that use the camera buffer manager are currently not supported in
5961 // offline mode
5962 if (stream->getOfflineProcessingSupport() &&
5963 (stream->getStreamSetId() == CAMERA3_STREAM_SET_ID_INVALID)) {
5964 offlineStreamIds->push_back(streamId);
5965 }
5966 }
5967}
5968
Eino-Ville Talvalaf2e37092020-01-07 15:32:32 -08005969status_t Camera3Device::setRotateAndCropAutoBehavior(
5970 camera_metadata_enum_android_scaler_rotate_and_crop_t rotateAndCropValue) {
5971 ATRACE_CALL();
5972 Mutex::Autolock il(mInterfaceLock);
5973 Mutex::Autolock l(mLock);
5974 if (mRequestThread == nullptr) {
5975 return INVALID_OPERATION;
5976 }
5977 return mRequestThread->setRotateAndCropAutoBehavior(rotateAndCropValue);
5978}
5979
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005980}; // namespace android