blob: 1d40d13c83121ce9e75d0941e21346ef1c522e7f [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
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Shuzhen Wang5c22c152017-12-31 17:12:25 -080042#include <utility>
43
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080044#include <utils/Log.h>
45#include <utils/Trace.h>
46#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070047#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070048
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080049#include <android/hardware/camera2/ICameraDeviceUser.h>
50
Igor Murashkinff3e31d2013-10-23 16:40:06 -070051#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070052#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "device3/Camera3Device.h"
54#include "device3/Camera3OutputStream.h"
55#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070056#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070057#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070058#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070059#include "utils/CameraThreadState.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080060
61using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080062using namespace android::hardware::camera;
63using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080064
65namespace android {
66
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080067Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080068 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080069 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070070 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070071 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070072 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070073 mUsePartialResult(false),
74 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080075 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070076 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070077 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070078 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070079 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000080 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010081 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
82 mLastTemplateId(-1)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080083{
84 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080085 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080086}
87
88Camera3Device::~Camera3Device()
89{
90 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080091 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -070092 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080093}
94
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080095const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080096 return mId;
97}
98
Emilian Peevbd8c5032018-02-14 23:05:40 +000099status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800100 ATRACE_CALL();
101 Mutex::Autolock il(mInterfaceLock);
102 Mutex::Autolock l(mLock);
103
104 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
105 if (mStatus != STATUS_UNINITIALIZED) {
106 CLOGE("Already initialized!");
107 return INVALID_OPERATION;
108 }
109 if (manager == nullptr) return INVALID_OPERATION;
110
111 sp<ICameraDeviceSession> session;
112 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800113 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800114 /*out*/ &session);
115 ATRACE_END();
116 if (res != OK) {
117 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
118 return res;
119 }
120
Steven Moreland5ff9c912017-03-09 23:13:00 -0800121 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800122 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700123 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800124 session->close();
125 return res;
126 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800127
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700128 std::vector<std::string> physicalCameraIds;
129 bool isLogical = CameraProviderManager::isLogicalCamera(mDeviceInfo, &physicalCameraIds);
130 if (isLogical) {
131 for (auto& physicalId : physicalCameraIds) {
132 res = manager->getCameraCharacteristics(physicalId, &mPhysicalDeviceInfoMap[physicalId]);
133 if (res != OK) {
134 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
135 physicalId.c_str(), strerror(-res), res);
136 session->close();
137 return res;
138 }
139 }
140 }
141
Yifan Hongf79b5542017-04-11 14:44:25 -0700142 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700143 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
144 [&queue](const auto& descriptor) {
145 queue = std::make_shared<RequestMetadataQueue>(descriptor);
146 if (!queue->isValid() || queue->availableToWrite() <= 0) {
147 ALOGE("HAL returns empty request metadata fmq, not use it");
148 queue = nullptr;
149 // don't use the queue onwards.
150 }
151 });
152 if (!requestQueueRet.isOk()) {
153 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
154 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700155 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700156 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700157
158 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700159 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700160 [&resQueue](const auto& descriptor) {
161 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
162 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700163 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700164 resQueue = nullptr;
165 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700166 }
167 });
168 if (!resultQueueRet.isOk()) {
169 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
170 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700171 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700172 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700173 IF_ALOGV() {
174 session->interfaceChain([](
175 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
176 ALOGV("Session interface chain:");
177 for (auto iface : interfaceChain) {
178 ALOGV(" %s", iface.c_str());
179 }
180 });
181 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700182
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700183 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000184 std::string providerType;
185 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000186 mTagMonitor.initialize(mVendorTagId);
187 if (!monitorTags.isEmpty()) {
188 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
189 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800190
191 return initializeCommonLocked();
192}
193
194status_t Camera3Device::initializeCommonLocked() {
195
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700196 /** Start up status tracker thread */
197 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800198 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700199 if (res != OK) {
200 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
201 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800202 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700203 mStatusTracker.clear();
204 return res;
205 }
206
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700207 /** Register in-flight map to the status tracker */
208 mInFlightStatusId = mStatusTracker->addComponent();
209
Zhijun He125684a2015-12-26 15:07:30 -0800210 /** Create buffer manager */
211 mBufferManager = new Camera3BufferManager();
212
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000213 Vector<int32_t> sessionParamKeys;
214 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
215 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
216 if (sessionKeysEntry.count > 0) {
217 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
218 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700219
220 camera_metadata_entry bufMgrMode =
221 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
222 if (bufMgrMode.count > 0) {
223 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
224 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
225 }
226
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700227 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700228 mRequestThread = new RequestThread(
229 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800230 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800231 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700232 SET_ERR_L("Unable to start request queue thread: %s (%d)",
233 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800234 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800235 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800236 return res;
237 }
238
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700239 mPreparerThread = new PreparerThread();
240
Ruben Brunk183f0562015-08-12 12:55:02 -0700241 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800242 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700243 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700244 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700245 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800246
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800247 // Measure the clock domain offset between camera and video/hw_composer
248 camera_metadata_entry timestampSource =
249 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
250 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
251 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
252 mTimestampOffset = getMonoToBoottimeOffset();
253 }
254
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700255 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100256 camera_metadata_entry partialResultsCount =
257 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
258 if (partialResultsCount.count > 0) {
259 mNumPartialResults = partialResultsCount.data.i32[0];
260 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700261 }
262
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700263 camera_metadata_entry configs =
264 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
265 for (uint32_t i = 0; i < configs.count; i += 4) {
266 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
267 configs.data.i32[i + 3] ==
268 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
269 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
270 configs.data.i32[i + 2]));
271 }
272 }
273
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700274 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
275 res = mDistortionMapper.setupStaticInfo(mDeviceInfo);
276 if (res != OK) {
277 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
278 return res;
279 }
280 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800281 return OK;
282}
283
284status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700285 return disconnectImpl();
286}
287
288status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800289 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700290 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800291
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700292 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800293
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700294 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700295 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700296 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700297 {
298 Mutex::Autolock l(mLock);
299 if (mStatus == STATUS_UNINITIALIZED) return res;
300
301 if (mStatus == STATUS_ACTIVE ||
302 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
303 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700304 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700305 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700306 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700307 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700308 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700309 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700310 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
311 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700312 // Continue to close device even in case of error
313 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700314 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800315 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800316
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700317 if (mStatus == STATUS_ERROR) {
318 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700319 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700320
321 if (mStatusTracker != NULL) {
322 mStatusTracker->requestExit();
323 }
324
325 if (mRequestThread != NULL) {
326 mRequestThread->requestExit();
327 }
328
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700329 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
330 for (size_t i = 0; i < mOutputStreams.size(); i++) {
331 streams.push_back(mOutputStreams[i]);
332 }
333 if (mInputStream != nullptr) {
334 streams.push_back(mInputStream);
335 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700336 }
337
338 // Joining done without holding mLock, otherwise deadlocks may ensue
339 // as the threads try to access parent state
340 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
341 // HAL may be in a bad state, so waiting for request thread
342 // (which may be stuck in the HAL processCaptureRequest call)
343 // could be dangerous.
344 mRequestThread->join();
345 }
346
347 if (mStatusTracker != NULL) {
348 mStatusTracker->join();
349 }
350
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800351 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700352 {
353 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800354 mRequestThread.clear();
Emilian Peev2843c362018-09-26 08:49:40 +0100355 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700356 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800357 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700358 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800359
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700360 // Call close without internal mutex held, as the HAL close may need to
361 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800362 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700363
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700364 flushInflightRequests();
365
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700366 {
367 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800368 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700369 mOutputStreams.clear();
370 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700371 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700372 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700373 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700374 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800375
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700376 for (auto& weakStream : streams) {
377 sp<Camera3StreamInterface> stream = weakStream.promote();
378 if (stream != nullptr) {
379 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
380 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
381 }
382 }
383
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700384 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700385 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800386}
387
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700388// For dumping/debugging only -
389// try to acquire a lock a few times, eventually give up to proceed with
390// debug/dump operations
391bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
392 bool gotLock = false;
393 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
394 if (lock.tryLock() == NO_ERROR) {
395 gotLock = true;
396 break;
397 } else {
398 usleep(kDumpSleepDuration);
399 }
400 }
401 return gotLock;
402}
403
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700404Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
405 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100406 const int STREAM_CONFIGURATION_SIZE = 4;
407 const int STREAM_FORMAT_OFFSET = 0;
408 const int STREAM_WIDTH_OFFSET = 1;
409 const int STREAM_HEIGHT_OFFSET = 2;
410 const int STREAM_IS_INPUT_OFFSET = 3;
411 camera_metadata_ro_entry_t availableStreamConfigs =
412 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
413 if (availableStreamConfigs.count == 0 ||
414 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
415 return Size(0, 0);
416 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700417
Emilian Peev08dd2452017-04-06 16:55:14 +0100418 // Get max jpeg size (area-wise).
419 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
420 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
421 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
422 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
423 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
424 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
425 && format == HAL_PIXEL_FORMAT_BLOB &&
426 (width * height > maxJpegWidth * maxJpegHeight)) {
427 maxJpegWidth = width;
428 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700429 }
430 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100431
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700432 return Size(maxJpegWidth, maxJpegHeight);
433}
434
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800435nsecs_t Camera3Device::getMonoToBoottimeOffset() {
436 // try three times to get the clock offset, choose the one
437 // with the minimum gap in measurements.
438 const int tries = 3;
439 nsecs_t bestGap, measured;
440 for (int i = 0; i < tries; ++i) {
441 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
442 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
443 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
444 const nsecs_t gap = tmono2 - tmono;
445 if (i == 0 || gap < bestGap) {
446 bestGap = gap;
447 measured = tbase - ((tmono + tmono2) >> 1);
448 }
449 }
450 return measured;
451}
452
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800453hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
454 int frameworkFormat) {
455 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
456}
457
458DataspaceFlags Camera3Device::mapToHidlDataspace(
459 android_dataspace dataSpace) {
460 return dataSpace;
461}
462
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700463BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100464 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700465 return usage;
466}
467
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800468StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
469 switch (rotation) {
470 case CAMERA3_STREAM_ROTATION_0:
471 return StreamRotation::ROTATION_0;
472 case CAMERA3_STREAM_ROTATION_90:
473 return StreamRotation::ROTATION_90;
474 case CAMERA3_STREAM_ROTATION_180:
475 return StreamRotation::ROTATION_180;
476 case CAMERA3_STREAM_ROTATION_270:
477 return StreamRotation::ROTATION_270;
478 }
479 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
480 return StreamRotation::ROTATION_0;
481}
482
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800483status_t Camera3Device::mapToStreamConfigurationMode(
484 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
485 if (mode == nullptr) return BAD_VALUE;
486 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
487 switch(operationMode) {
488 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
489 *mode = StreamConfigurationMode::NORMAL_MODE;
490 break;
491 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
492 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
493 break;
494 default:
495 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
496 return BAD_VALUE;
497 }
498 } else {
499 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800500 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800501 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800502}
503
504camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
505 switch (status) {
506 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
507 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
508 }
509 return CAMERA3_BUFFER_STATUS_ERROR;
510}
511
512int Camera3Device::mapToFrameworkFormat(
513 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
514 return static_cast<uint32_t>(pixelFormat);
515}
516
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700517android_dataspace Camera3Device::mapToFrameworkDataspace(
518 DataspaceFlags dataSpace) {
519 return static_cast<android_dataspace>(dataSpace);
520}
521
Emilian Peev050f5dc2017-05-18 14:43:56 +0100522uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700523 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700524 return usage;
525}
526
Emilian Peev050f5dc2017-05-18 14:43:56 +0100527uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700528 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700529 return usage;
530}
531
Zhijun Hef7da0962014-04-24 13:27:56 -0700532ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700533 // Get max jpeg size (area-wise).
534 Size maxJpegResolution = getMaxJpegResolution();
535 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800536 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
537 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700538 return BAD_VALUE;
539 }
540
Zhijun Hef7da0962014-04-24 13:27:56 -0700541 // Get max jpeg buffer size
542 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700543 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
544 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800545 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
546 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700547 return BAD_VALUE;
548 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700549 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800550 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700551
552 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700553 float scaleFactor = ((float) (width * height)) /
554 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800555 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
556 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700557 if (jpegBufferSize > maxJpegBufferSize) {
558 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700559 }
560
561 return jpegBufferSize;
562}
563
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700564ssize_t Camera3Device::getPointCloudBufferSize() const {
565 const int FLOATS_PER_POINT=4;
566 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
567 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800568 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
569 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700570 return BAD_VALUE;
571 }
572 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
573 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
574 return maxBytesForPointCloud;
575}
576
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800577ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800578 const int PER_CONFIGURATION_SIZE = 3;
579 const int WIDTH_OFFSET = 0;
580 const int HEIGHT_OFFSET = 1;
581 const int SIZE_OFFSET = 2;
582 camera_metadata_ro_entry rawOpaqueSizes =
583 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800584 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800585 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800586 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
587 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800588 return BAD_VALUE;
589 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700590
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800591 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
592 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
593 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
594 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
595 }
596 }
597
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800598 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
599 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800600 return BAD_VALUE;
601}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700602
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800603status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
604 ATRACE_CALL();
605 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700606
607 // Try to lock, but continue in case of failure (to avoid blocking in
608 // deadlocks)
609 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
610 bool gotLock = tryLockSpinRightRound(mLock);
611
612 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800613 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
614 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700615 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800616 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
617 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700618
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800619 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700620
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800621 String16 templatesOption("-t");
622 int n = args.size();
623 for (int i = 0; i < n; i++) {
624 if (args[i] == templatesOption) {
625 dumpTemplates = true;
626 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000627 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700628 if (i + 1 < n) {
629 String8 monitorTags = String8(args[i + 1]);
630 if (monitorTags == "off") {
631 mTagMonitor.disableMonitoring();
632 } else {
633 mTagMonitor.parseTagsToMonitor(monitorTags);
634 }
635 } else {
636 mTagMonitor.disableMonitoring();
637 }
638 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800639 }
640
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800641 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800642
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800643 const char *status =
644 mStatus == STATUS_ERROR ? "ERROR" :
645 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700646 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
647 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800648 mStatus == STATUS_ACTIVE ? "ACTIVE" :
649 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700650
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800651 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700652 if (mStatus == STATUS_ERROR) {
653 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
654 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800655 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800656 const char *mode =
657 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
658 mOperatingMode == static_cast<int>(
659 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
660 "CUSTOM";
661 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800662
663 if (mInputStream != NULL) {
664 write(fd, lines.string(), lines.size());
665 mInputStream->dump(fd, args);
666 } else {
667 lines.appendFormat(" No input stream.\n");
668 write(fd, lines.string(), lines.size());
669 }
670 for (size_t i = 0; i < mOutputStreams.size(); i++) {
671 mOutputStreams[i]->dump(fd,args);
672 }
673
Zhijun He431503c2016-03-07 17:30:16 -0800674 if (mBufferManager != NULL) {
675 lines = String8(" Camera3 Buffer Manager:\n");
676 write(fd, lines.string(), lines.size());
677 mBufferManager->dump(fd, args);
678 }
Zhijun He125684a2015-12-26 15:07:30 -0800679
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700680 lines = String8(" In-flight requests:\n");
681 if (mInFlightMap.size() == 0) {
682 lines.append(" None\n");
683 } else {
684 for (size_t i = 0; i < mInFlightMap.size(); i++) {
685 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700686 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700687 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800688 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700689 r.numBuffersLeft);
690 }
691 }
692 write(fd, lines.string(), lines.size());
693
Shuzhen Wang686f6442017-06-20 16:16:04 -0700694 if (mRequestThread != NULL) {
695 mRequestThread->dumpCaptureRequestLatency(fd,
696 " ProcessCaptureRequest latency histogram:");
697 }
698
Igor Murashkin1e479c02013-09-06 16:55:14 -0700699 {
700 lines = String8(" Last request sent:\n");
701 write(fd, lines.string(), lines.size());
702
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700703 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700704 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
705 }
706
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800707 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800708 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800709 "TEMPLATE_PREVIEW",
710 "TEMPLATE_STILL_CAPTURE",
711 "TEMPLATE_VIDEO_RECORD",
712 "TEMPLATE_VIDEO_SNAPSHOT",
713 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800714 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800715 };
716
717 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800718 camera_metadata_t *templateRequest = nullptr;
719 mInterface->constructDefaultRequestSettings(
720 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800721 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800722 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800723 lines.append(" Not supported\n");
724 write(fd, lines.string(), lines.size());
725 } else {
726 write(fd, lines.string(), lines.size());
727 dump_indented_camera_metadata(templateRequest,
728 fd, /*verbosity*/2, /*indentation*/8);
729 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800730 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800731 }
732 }
733
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700734 mTagMonitor.dumpMonitoredMetadata(fd);
735
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800736 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800737 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800738 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800739 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800740 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800741
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700742 if (gotLock) mLock.unlock();
743 if (gotInterfaceLock) mInterfaceLock.unlock();
744
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800745 return OK;
746}
747
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700748const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800749 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800750 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
751 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700752 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800753 mStatus == STATUS_ERROR ?
754 "when in error state" : "before init");
755 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700756 if (physicalId.isEmpty()) {
757 return mDeviceInfo;
758 } else {
759 std::string id(physicalId.c_str());
760 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
761 return mPhysicalDeviceInfoMap.at(id);
762 } else {
763 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
764 return mDeviceInfo;
765 }
766 }
767}
768
769const CameraMetadata& Camera3Device::info() const {
770 String8 emptyId;
771 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800772}
773
Jianing Wei90e59c92014-03-12 18:29:36 -0700774status_t Camera3Device::checkStatusOkToCaptureLocked() {
775 switch (mStatus) {
776 case STATUS_ERROR:
777 CLOGE("Device has encountered a serious error");
778 return INVALID_OPERATION;
779 case STATUS_UNINITIALIZED:
780 CLOGE("Device not initialized");
781 return INVALID_OPERATION;
782 case STATUS_UNCONFIGURED:
783 case STATUS_CONFIGURED:
784 case STATUS_ACTIVE:
785 // OK
786 break;
787 default:
788 SET_ERR_L("Unexpected status: %d", mStatus);
789 return INVALID_OPERATION;
790 }
791 return OK;
792}
793
794status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000795 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700796 const std::list<const SurfaceMap> &surfaceMaps,
797 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700798 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700799 if (requestList == NULL) {
800 CLOGE("requestList cannot be NULL.");
801 return BAD_VALUE;
802 }
803
Jianing Weicb0652e2014-03-12 18:29:36 -0700804 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000805 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700806 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
807 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
808 ++metadataIt, ++surfaceMapIt) {
809 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700810 if (newRequest == 0) {
811 CLOGE("Can't create capture request");
812 return BAD_VALUE;
813 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700814
Shuzhen Wang9d066012016-09-30 11:30:20 -0700815 newRequest->mRepeating = repeating;
816
Jianing Weicb0652e2014-03-12 18:29:36 -0700817 // Setup burst Id and request Id
818 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000819 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
820 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700821 CLOGE("RequestID entry exists; but must not be empty in metadata");
822 return BAD_VALUE;
823 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000824 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
825 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700826 } else {
827 CLOGE("RequestID does not exist in metadata");
828 return BAD_VALUE;
829 }
830
Jianing Wei90e59c92014-03-12 18:29:36 -0700831 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700832
833 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700834 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700835 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
836 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
837 return BAD_VALUE;
838 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700839
840 // Setup batch size if this is a high speed video recording request.
841 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
842 auto firstRequest = requestList->begin();
843 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
844 if (outputStream->isVideoStream()) {
845 (*firstRequest)->mBatchSize = requestList->size();
846 break;
847 }
848 }
849 }
850
Jianing Wei90e59c92014-03-12 18:29:36 -0700851 return OK;
852}
853
Jianing Weicb0652e2014-03-12 18:29:36 -0700854status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800856
Emilian Peevaebbe412018-01-15 13:53:24 +0000857 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000859 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700860
Emilian Peevaebbe412018-01-15 13:53:24 +0000861 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700862}
863
Emilian Peevaebbe412018-01-15 13:53:24 +0000864void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700865 std::list<const SurfaceMap>& surfaceMaps,
866 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000867 PhysicalCameraSettingsList requestList;
868 requestList.push_back({std::string(getId().string()), request});
869 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700870
871 SurfaceMap surfaceMap;
872 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
873 // With no surface list passed in, stream and surface will have 1-to-1
874 // mapping. So the surface index is 0 for each stream in the surfaceMap.
875 for (size_t i = 0; i < streams.count; i++) {
876 surfaceMap[streams.data.i32[i]].push_back(0);
877 }
878 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800879}
880
Jianing Wei90e59c92014-03-12 18:29:36 -0700881status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000882 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700883 const std::list<const SurfaceMap> &surfaceMaps,
884 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700885 /*out*/
886 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700887 ATRACE_CALL();
888 Mutex::Autolock il(mInterfaceLock);
889 Mutex::Autolock l(mLock);
890
891 status_t res = checkStatusOkToCaptureLocked();
892 if (res != OK) {
893 // error logged by previous call
894 return res;
895 }
896
897 RequestList requestList;
898
Shuzhen Wang0129d522016-10-30 22:43:41 -0700899 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
900 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700901 if (res != OK) {
902 // error logged by previous call
903 return res;
904 }
905
906 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700907 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700908 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700909 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700910 }
911
912 if (res == OK) {
913 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
914 if (res != OK) {
915 SET_ERR_L("Can't transition to active in %f seconds!",
916 kActiveTimeout/1e9);
917 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800918 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700919 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700920 } else {
921 CLOGE("Cannot queue request. Impossible.");
922 return BAD_VALUE;
923 }
924
925 return res;
926}
927
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700928hardware::Return<void> Camera3Device::requestStreamBuffers(
929 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
930 requestStreamBuffers_cb _hidl_cb) {
931 using hardware::camera::device::V3_5::BufferRequestStatus;
932 using hardware::camera::device::V3_5::StreamBufferRet;
933 using hardware::camera::device::V3_5::StreamBufferRequestError;
934
935 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
936
937 hardware::hidl_vec<StreamBufferRet> bufRets;
938 if (!mUseHalBufManager) {
939 ALOGE("%s: Camera %s does not support HAL buffer management",
940 __FUNCTION__, mId.string());
941 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
942 return hardware::Void();
943 }
944
945 SortedVector<int32_t> streamIds;
946 ssize_t sz = streamIds.setCapacity(bufReqs.size());
947 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
948 ALOGE("%s: failed to allocate memory for %zu buffer requests",
949 __FUNCTION__, bufReqs.size());
950 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
951 return hardware::Void();
952 }
953
954 // Check for repeated streamId
955 for (const auto& bufReq : bufReqs) {
956 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
957 ALOGE("%s: Stream %d appear multiple times in buffer requests",
958 __FUNCTION__, bufReq.streamId);
959 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
960 return hardware::Void();
961 }
962 streamIds.add(bufReq.streamId);
963 }
964
965 // TODO: check we are not configuring streams. If so return FAILED_CONFIGURING
966 // Probably need to hook CameraDeviceClient::beginConfigure and figure something
967 // out for API1 client... maybe grab mLock and check mNeedConfig but then we will
968 // need to wait until mLock is released...
969 // _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
970 // return hardware::Void();
971
972 // TODO: here we start accessing mOutputStreams, might need mLock, but that
973 // might block incoming API calls. Not sure how bad is it.
974 if (bufReqs.size() > mOutputStreams.size()) {
975 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
976 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
977 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
978 return hardware::Void();
979 }
980
981 bufRets.resize(bufReqs.size());
982
983 bool allReqsSucceeds = true;
984 bool oneReqSucceeds = false;
985 for (size_t i = 0; i < bufReqs.size(); i++) {
986 const auto& bufReq = bufReqs[i];
987 auto& bufRet = bufRets[i];
988 int32_t streamId = bufReq.streamId;
989 ssize_t idx = mOutputStreams.indexOfKey(streamId);
990 if (idx == NAME_NOT_FOUND) {
991 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
992 hardware::hidl_vec<StreamBufferRet> emptyBufRets;
993 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
994 return hardware::Void();
995 }
996 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.valueAt(idx);
997
998 bufRet.streamId = streamId;
999 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
1000 size_t totalHandout = outputStream->getOutstandingBuffersCount() + numBuffersRequested;
1001 if (totalHandout > outputStream->asHalStream()->max_buffers) {
1002 // Not able to allocate enough buffer. Exit early for this stream
1003 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1004 allReqsSucceeds = false;
1005 continue;
1006 }
1007
1008 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1009 bool currentReqSucceeds = true;
1010 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1011 size_t numAllocatedBuffers = 0;
1012 size_t numPushedInflightBuffers = 0;
1013 for (size_t b = 0; b < numBuffersRequested; b++) {
1014 camera3_stream_buffer_t& sb = streamBuffers[b];
1015 // Since this method can run concurrently with request thread
1016 // We need to update the wait duration everytime we call getbuffer
1017 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1018 status_t res = outputStream->getBuffer(&sb, waitDuration);
1019 if (res != OK) {
1020 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1021 __FUNCTION__, streamId, strerror(-res), res);
1022 if (res == NO_INIT || res == DEAD_OBJECT) {
1023 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1024 } else if (res == TIMED_OUT || res == NO_MEMORY) {
1025 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1026 } else {
1027 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1028 }
1029 currentReqSucceeds = false;
1030 break;
1031 }
1032 numAllocatedBuffers++;
1033
1034 buffer_handle_t *buffer = sb.buffer;
1035 auto pair = mInterface->getBufferId(*buffer, streamId);
1036 bool isNewBuffer = pair.first;
1037 uint64_t bufferId = pair.second;
1038 StreamBuffer& hBuf = tmpRetBuffers[b];
1039
1040 hBuf.streamId = streamId;
1041 hBuf.bufferId = bufferId;
1042 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1043 hBuf.status = BufferStatus::OK;
1044 hBuf.releaseFence = nullptr;
1045
1046 native_handle_t *acquireFence = nullptr;
1047 if (sb.acquire_fence != -1) {
1048 acquireFence = native_handle_create(1,0);
1049 acquireFence->data[0] = sb.acquire_fence;
1050 }
1051 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1052 hBuf.releaseFence = nullptr;
1053
1054 res = mInterface->pushInflightRequestBuffer(bufferId, buffer);
1055 if (res != OK) {
1056 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1057 __FUNCTION__, streamId, strerror(-res), res);
1058 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1059 currentReqSucceeds = false;
1060 break;
1061 }
1062 numPushedInflightBuffers++;
1063 }
1064 if (currentReqSucceeds) {
1065 bufRet.val.buffers(std::move(tmpRetBuffers));
1066 oneReqSucceeds = true;
1067 } else {
1068 allReqsSucceeds = false;
1069 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1070 StreamBuffer& hBuf = tmpRetBuffers[b];
1071 buffer_handle_t* buffer;
1072 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1073 if (res != OK) {
1074 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1075 __FUNCTION__, streamId, strerror(-res), res);
1076 }
1077 }
1078 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1079 }
1080 }
1081 // End of mOutputStreams access
1082
1083 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1084 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1085 BufferRequestStatus::FAILED_UNKNOWN,
1086 bufRets);
1087 return hardware::Void();
1088}
1089
1090hardware::Return<void> Camera3Device::returnStreamBuffers(
1091 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1092 if (!mUseHalBufManager) {
1093 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1094 __FUNCTION__, mId.string());
1095 return hardware::Void();
1096 }
1097
1098 for (const auto& buf : buffers) {
1099 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1100 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1101 continue;
1102 }
1103
1104 buffer_handle_t* buffer;
1105 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1106
1107 if (res != OK) {
1108 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1109 __FUNCTION__, buf.bufferId, buf.streamId);
1110 continue;
1111 }
1112
1113 camera3_stream_buffer_t streamBuffer;
1114 streamBuffer.buffer = buffer;
1115 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1116 streamBuffer.acquire_fence = -1;
1117 streamBuffer.release_fence = -1;
1118
1119 if (buf.releaseFence == nullptr) {
1120 streamBuffer.release_fence = -1;
1121 } else if (buf.releaseFence->numFds == 1) {
1122 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1123 } else {
1124 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1125 __FUNCTION__, buf.releaseFence->numFds);
1126 continue;
1127 }
1128
1129 // Need to lock mLock here if we were to allow HAL to return buffer during
1130 // stream configuration. This is not currently possible because we only
1131 // do stream configuration when there is no inflight buffers in HAL.
1132 ssize_t idx = mOutputStreams.indexOfKey(buf.streamId);
1133 if (idx == NAME_NOT_FOUND) {
1134 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1135 continue;
1136 }
1137 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
1138 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1139 }
1140 return hardware::Void();
1141}
1142
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001143hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001144 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001145 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001146 // Ideally we should grab mLock, but that can lead to deadlock, and
1147 // it's not super important to get up to date value of mStatus for this
1148 // warning print, hence skipping the lock here
1149 if (mStatus == STATUS_ERROR) {
1150 // Per API contract, HAL should act as closed after device error
1151 // But mStatus can be set to error by framework as well, so just log
1152 // a warning here.
1153 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001154 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001155
1156 if (mProcessCaptureResultLock.tryLock() != OK) {
1157 // This should never happen; it indicates a wrong client implementation
1158 // that doesn't follow the contract. But, we can be tolerant here.
1159 ALOGE("%s: callback overlapped! waiting 1s...",
1160 __FUNCTION__);
1161 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1162 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1163 __FUNCTION__);
1164 // really don't know what to do, so bail out.
1165 return hardware::Void();
1166 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001167 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001168 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001169 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001170 }
1171 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001172 return hardware::Void();
1173}
1174
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001175// Only one processCaptureResult should be called at a time, so
1176// the locks won't block. The locks are present here simply to enforce this.
1177hardware::Return<void> Camera3Device::processCaptureResult(
1178 const hardware::hidl_vec<
1179 hardware::camera::device::V3_2::CaptureResult>& results) {
1180 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1181
1182 // Ideally we should grab mLock, but that can lead to deadlock, and
1183 // it's not super important to get up to date value of mStatus for this
1184 // warning print, hence skipping the lock here
1185 if (mStatus == STATUS_ERROR) {
1186 // Per API contract, HAL should act as closed after device error
1187 // But mStatus can be set to error by framework as well, so just log
1188 // a warning here.
1189 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1190 }
1191
1192 if (mProcessCaptureResultLock.tryLock() != OK) {
1193 // This should never happen; it indicates a wrong client implementation
1194 // that doesn't follow the contract. But, we can be tolerant here.
1195 ALOGE("%s: callback overlapped! waiting 1s...",
1196 __FUNCTION__);
1197 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1198 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1199 __FUNCTION__);
1200 // really don't know what to do, so bail out.
1201 return hardware::Void();
1202 }
1203 }
1204 for (const auto& result : results) {
1205 processOneCaptureResultLocked(result, noPhysMetadata);
1206 }
1207 mProcessCaptureResultLock.unlock();
1208 return hardware::Void();
1209}
1210
1211status_t Camera3Device::readOneCameraMetadataLocked(
1212 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1213 const hardware::camera::device::V3_2::CameraMetadata& result) {
1214 if (fmqResultSize > 0) {
1215 resultMetadata.resize(fmqResultSize);
1216 if (mResultMetadataQueue == nullptr) {
1217 return NO_MEMORY; // logged in initialize()
1218 }
1219 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1220 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1221 __FUNCTION__, fmqResultSize);
1222 return INVALID_OPERATION;
1223 }
1224 } else {
1225 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1226 result.size());
1227 }
1228
1229 if (resultMetadata.size() != 0) {
1230 status_t res;
1231 const camera_metadata_t* metadata =
1232 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1233 size_t expected_metadata_size = resultMetadata.size();
1234 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1235 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1236 __FUNCTION__, strerror(-res), res);
1237 return INVALID_OPERATION;
1238 }
1239 }
1240
1241 return OK;
1242}
1243
Yifan Honga640c5a2017-04-12 16:30:31 -07001244void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001245 const hardware::camera::device::V3_2::CaptureResult& result,
1246 const hardware::hidl_vec<
1247 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001248 camera3_capture_result r;
1249 status_t res;
1250 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001251
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001252 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001253 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001254 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1255 if (res != OK) {
1256 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1257 __FUNCTION__, result.frameNumber);
1258 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001259 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001260 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001261
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001262 // Read and validate physical camera metadata
1263 size_t physResultCount = physicalCameraMetadatas.size();
1264 std::vector<const char*> physCamIds(physResultCount);
1265 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1266 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1267 physResultMetadata.resize(physResultCount);
1268 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1269 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1270 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1271 if (res != OK) {
1272 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1273 __FUNCTION__, result.frameNumber,
1274 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001275 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001276 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001277 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1278 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1279 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001280 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001281 r.num_physcam_metadata = physResultCount;
1282 r.physcam_ids = physCamIds.data();
1283 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001284
1285 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1286 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1287 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1288 auto& bDst = outputBuffers[i];
1289 const StreamBuffer &bSrc = result.outputBuffers[i];
1290
1291 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001292 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001293 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1294 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001295 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001296 }
1297 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
1298
1299 buffer_handle_t *buffer;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001300 if (mUseHalBufManager) {
1301 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1302 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1303 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1304 return;
1305 }
1306 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1307 } else {
1308 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1309 }
1310
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001311 if (res != OK) {
1312 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1313 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001314 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001315 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001316
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001317 bDst.buffer = buffer;
1318 bDst.status = mapHidlBufferStatus(bSrc.status);
1319 bDst.acquire_fence = -1;
1320 if (bSrc.releaseFence == nullptr) {
1321 bDst.release_fence = -1;
1322 } else if (bSrc.releaseFence->numFds == 1) {
1323 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1324 } else {
1325 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1326 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001327 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001328 }
1329 }
1330 r.num_output_buffers = outputBuffers.size();
1331 r.output_buffers = outputBuffers.data();
1332
1333 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001334 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001335 r.input_buffer = nullptr;
1336 } else {
1337 if (mInputStream->getId() != result.inputBuffer.streamId) {
1338 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1339 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001340 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001341 }
1342 inputBuffer.stream = mInputStream->asHalStream();
1343 buffer_handle_t *buffer;
1344 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1345 &buffer);
1346 if (res != OK) {
1347 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1348 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001349 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001350 }
1351 inputBuffer.buffer = buffer;
1352 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1353 inputBuffer.acquire_fence = -1;
1354 if (result.inputBuffer.releaseFence == nullptr) {
1355 inputBuffer.release_fence = -1;
1356 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1357 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1358 } else {
1359 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1360 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001361 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001362 }
1363 r.input_buffer = &inputBuffer;
1364 }
1365
1366 r.partial_result = result.partialResult;
1367
1368 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001369}
1370
1371hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001372 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001373 // Ideally we should grab mLock, but that can lead to deadlock, and
1374 // it's not super important to get up to date value of mStatus for this
1375 // warning print, hence skipping the lock here
1376 if (mStatus == STATUS_ERROR) {
1377 // Per API contract, HAL should act as closed after device error
1378 // But mStatus can be set to error by framework as well, so just log
1379 // a warning here.
1380 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001381 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001382
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001383 for (const auto& msg : msgs) {
1384 notify(msg);
1385 }
1386 return hardware::Void();
1387}
1388
1389void Camera3Device::notify(
1390 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1391
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001392 camera3_notify_msg m;
1393 switch (msg.type) {
1394 case MsgType::ERROR:
1395 m.type = CAMERA3_MSG_ERROR;
1396 m.message.error.frame_number = msg.msg.error.frameNumber;
1397 if (msg.msg.error.errorStreamId >= 0) {
1398 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001399 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001400 ALOGE("%s: Frame %d: Invalid error stream id %d",
1401 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001402 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001403 }
1404 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1405 } else {
1406 m.message.error.error_stream = nullptr;
1407 }
1408 switch (msg.msg.error.errorCode) {
1409 case ErrorCode::ERROR_DEVICE:
1410 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1411 break;
1412 case ErrorCode::ERROR_REQUEST:
1413 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1414 break;
1415 case ErrorCode::ERROR_RESULT:
1416 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1417 break;
1418 case ErrorCode::ERROR_BUFFER:
1419 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1420 break;
1421 }
1422 break;
1423 case MsgType::SHUTTER:
1424 m.type = CAMERA3_MSG_SHUTTER;
1425 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1426 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1427 break;
1428 }
1429 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001430}
1431
Emilian Peevaebbe412018-01-15 13:53:24 +00001432status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001433 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001434 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001435 ATRACE_CALL();
1436
Emilian Peevaebbe412018-01-15 13:53:24 +00001437 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001438}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001439
Jianing Weicb0652e2014-03-12 18:29:36 -07001440status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1441 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001442 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001443
Emilian Peevaebbe412018-01-15 13:53:24 +00001444 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001445 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001446 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001447
Emilian Peevaebbe412018-01-15 13:53:24 +00001448 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001449 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001450}
1451
Emilian Peevaebbe412018-01-15 13:53:24 +00001452status_t Camera3Device::setStreamingRequestList(
1453 const List<const PhysicalCameraSettingsList> &requestsList,
1454 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001455 ATRACE_CALL();
1456
Emilian Peevaebbe412018-01-15 13:53:24 +00001457 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001458}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459
1460sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001461 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001462 status_t res;
1463
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001464 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001465 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1466 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001467 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1468 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001469 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001471 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001472 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001473 } else if (mStatus == STATUS_UNCONFIGURED) {
1474 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001475 CLOGE("No streams configured");
1476 return NULL;
1477 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001478 }
1479
Shuzhen Wang0129d522016-10-30 22:43:41 -07001480 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001482}
1483
Jianing Weicb0652e2014-03-12 18:29:36 -07001484status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001485 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001486 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001487 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001488
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001489 switch (mStatus) {
1490 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001491 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001492 return INVALID_OPERATION;
1493 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001494 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001496 case STATUS_UNCONFIGURED:
1497 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 case STATUS_ACTIVE:
1499 // OK
1500 break;
1501 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001502 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 return INVALID_OPERATION;
1504 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001505 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001506
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001507 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001508}
1509
1510status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1511 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001512 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001513
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001514 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001515}
1516
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001517status_t Camera3Device::createInputStream(
1518 uint32_t width, uint32_t height, int format, int *id) {
1519 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001520 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001521 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001522 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001523 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1524 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001525
1526 status_t res;
1527 bool wasActive = false;
1528
1529 switch (mStatus) {
1530 case STATUS_ERROR:
1531 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1532 return INVALID_OPERATION;
1533 case STATUS_UNINITIALIZED:
1534 ALOGE("%s: Device not initialized", __FUNCTION__);
1535 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001536 case STATUS_UNCONFIGURED:
1537 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001538 // OK
1539 break;
1540 case STATUS_ACTIVE:
1541 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001542 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001543 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001545 return res;
1546 }
1547 wasActive = true;
1548 break;
1549 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001550 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001551 return INVALID_OPERATION;
1552 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001553 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001554
1555 if (mInputStream != 0) {
1556 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1557 return INVALID_OPERATION;
1558 }
1559
1560 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1561 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001562 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001563
1564 mInputStream = newStream;
1565
1566 *id = mNextStreamId++;
1567
1568 // Continue captures if active at start
1569 if (wasActive) {
1570 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001571 // Reuse current operating mode and session parameters for new stream config
1572 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001573 if (res != OK) {
1574 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1575 __FUNCTION__, mNextStreamId, strerror(-res), res);
1576 return res;
1577 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001578 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001579 }
1580
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001581 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001582 return OK;
1583}
1584
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001585status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001586 uint32_t width, uint32_t height, int format,
1587 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001588 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001589 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001590 ATRACE_CALL();
1591
1592 if (consumer == nullptr) {
1593 ALOGE("%s: consumer must not be null", __FUNCTION__);
1594 return BAD_VALUE;
1595 }
1596
1597 std::vector<sp<Surface>> consumers;
1598 consumers.push_back(consumer);
1599
1600 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001601 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1602 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001603}
1604
1605status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1606 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1607 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001608 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001609 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001610 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001611
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001612 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001613 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001614 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001615 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001616 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1617 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1618 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001619
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001620 status_t res;
1621 bool wasActive = false;
1622
1623 switch (mStatus) {
1624 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001625 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001626 return INVALID_OPERATION;
1627 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001628 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001629 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001630 case STATUS_UNCONFIGURED:
1631 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001632 // OK
1633 break;
1634 case STATUS_ACTIVE:
1635 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001636 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001637 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001638 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001639 return res;
1640 }
1641 wasActive = true;
1642 break;
1643 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001644 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001645 return INVALID_OPERATION;
1646 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001647 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001648
1649 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001650
Shuzhen Wang0129d522016-10-30 22:43:41 -07001651 if (consumers.size() == 0 && !hasDeferredConsumer) {
1652 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1653 return BAD_VALUE;
1654 }
Zhijun He5d677d12016-05-29 16:52:39 -07001655
Shuzhen Wang0129d522016-10-30 22:43:41 -07001656 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001657 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1658 return BAD_VALUE;
1659 }
1660
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001661 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001662 ssize_t blobBufferSize;
1663 if (dataSpace != HAL_DATASPACE_DEPTH) {
1664 blobBufferSize = getJpegBufferSize(width, height);
1665 if (blobBufferSize <= 0) {
1666 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1667 return BAD_VALUE;
1668 }
1669 } else {
1670 blobBufferSize = getPointCloudBufferSize();
1671 if (blobBufferSize <= 0) {
1672 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1673 return BAD_VALUE;
1674 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001675 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001676 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001677 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001678 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001679 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1680 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1681 if (rawOpaqueBufferSize <= 0) {
1682 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1683 return BAD_VALUE;
1684 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001685 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001686 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001687 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001688 } else if (isShared) {
1689 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1690 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001691 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001692 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001693 newStream = new Camera3OutputStream(mNextStreamId,
1694 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001695 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001696 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001697 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001698 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001699 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001700 }
Emilian Peev40ead602017-09-26 15:46:36 +01001701
1702 size_t consumerCount = consumers.size();
1703 for (size_t i = 0; i < consumerCount; i++) {
1704 int id = newStream->getSurfaceId(consumers[i]);
1705 if (id < 0) {
1706 SET_ERR_L("Invalid surface id");
1707 return BAD_VALUE;
1708 }
1709 if (surfaceIds != nullptr) {
1710 surfaceIds->push_back(id);
1711 }
1712 }
1713
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001714 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001715
Emilian Peev08dd2452017-04-06 16:55:14 +01001716 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001717
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001718 res = mOutputStreams.add(mNextStreamId, newStream);
1719 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001720 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001721 return res;
1722 }
1723
1724 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001725 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001726
1727 // Continue captures if active at start
1728 if (wasActive) {
1729 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001730 // Reuse current operating mode and session parameters for new stream config
1731 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001732 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001733 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1734 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001735 return res;
1736 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001737 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001738 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001739 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001740 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001741}
1742
Emilian Peev710c1422017-08-30 11:19:38 +01001743status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001744 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001745 if (nullptr == streamInfo) {
1746 return BAD_VALUE;
1747 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001748 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001749 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001750
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001751 switch (mStatus) {
1752 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001753 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001754 return INVALID_OPERATION;
1755 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001756 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001757 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001758 case STATUS_UNCONFIGURED:
1759 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001760 case STATUS_ACTIVE:
1761 // OK
1762 break;
1763 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001764 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001765 return INVALID_OPERATION;
1766 }
1767
1768 ssize_t idx = mOutputStreams.indexOfKey(id);
1769 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001770 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001771 return idx;
1772 }
1773
Emilian Peev710c1422017-08-30 11:19:38 +01001774 streamInfo->width = mOutputStreams[idx]->getWidth();
1775 streamInfo->height = mOutputStreams[idx]->getHeight();
1776 streamInfo->format = mOutputStreams[idx]->getFormat();
1777 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1778 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1779 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001780 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1781 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001782 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001783}
1784
1785status_t Camera3Device::setStreamTransform(int id,
1786 int transform) {
1787 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001788 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001789 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001790
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001791 switch (mStatus) {
1792 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001793 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001794 return INVALID_OPERATION;
1795 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001796 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001797 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001798 case STATUS_UNCONFIGURED:
1799 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001800 case STATUS_ACTIVE:
1801 // OK
1802 break;
1803 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001804 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001805 return INVALID_OPERATION;
1806 }
1807
1808 ssize_t idx = mOutputStreams.indexOfKey(id);
1809 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001810 CLOGE("Stream %d does not exist",
1811 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001812 return BAD_VALUE;
1813 }
1814
1815 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001816}
1817
1818status_t Camera3Device::deleteStream(int id) {
1819 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001820 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001821 Mutex::Autolock l(mLock);
1822 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001823
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001824 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001825
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001826 // CameraDevice semantics require device to already be idle before
1827 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001829 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001830 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001831 }
1832
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001833 if (mStatus == STATUS_ERROR) {
1834 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1835 __FUNCTION__, mId.string());
1836 return -EBUSY;
1837 }
1838
Igor Murashkin2fba5842013-04-22 14:03:54 -07001839 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001840 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001841 if (mInputStream != NULL && id == mInputStream->getId()) {
1842 deletedStream = mInputStream;
1843 mInputStream.clear();
1844 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001845 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001846 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001847 return BAD_VALUE;
1848 }
Zhijun He5f446352014-01-22 09:49:33 -08001849 }
1850
1851 // Delete output stream or the output part of a bi-directional stream.
1852 if (outputStreamIdx != NAME_NOT_FOUND) {
1853 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001854 mOutputStreams.removeItem(id);
1855 }
1856
1857 // Free up the stream endpoint so that it can be used by some other stream
1858 res = deletedStream->disconnect();
1859 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001860 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001861 // fall through since we want to still list the stream as deleted.
1862 }
1863 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001864 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001865
1866 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001867}
1868
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001869status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001870 ATRACE_CALL();
1871 ALOGV("%s: E", __FUNCTION__);
1872
1873 Mutex::Autolock il(mInterfaceLock);
1874 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001875
Emilian Peev811d2952018-05-25 11:08:40 +01001876 // In case the client doesn't include any session parameter, try a
1877 // speculative configuration using the values from the last cached
1878 // default request.
1879 if (sessionParams.isEmpty() &&
1880 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1881 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1882 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1883 mLastTemplateId);
1884 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1885 operatingMode);
1886 }
1887
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001888 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1889}
1890
1891status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1892 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001893 //Filter out any incoming session parameters
1894 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001895 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1896 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001897 CameraMetadata filteredParams(availableSessionKeys.count);
1898 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1899 filteredParams.getAndLock());
1900 set_camera_metadata_vendor_id(meta, mVendorTagId);
1901 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001902 if (availableSessionKeys.count > 0) {
1903 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1904 camera_metadata_ro_entry entry = params.find(
1905 availableSessionKeys.data.i32[i]);
1906 if (entry.count > 0) {
1907 filteredParams.update(entry);
1908 }
1909 }
1910 }
1911
1912 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001913}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001914
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001915status_t Camera3Device::getInputBufferProducer(
1916 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001917 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001918 Mutex::Autolock il(mInterfaceLock);
1919 Mutex::Autolock l(mLock);
1920
1921 if (producer == NULL) {
1922 return BAD_VALUE;
1923 } else if (mInputStream == NULL) {
1924 return INVALID_OPERATION;
1925 }
1926
1927 return mInputStream->getInputBufferProducer(producer);
1928}
1929
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001930status_t Camera3Device::createDefaultRequest(int templateId,
1931 CameraMetadata *request) {
1932 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001933 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001934
1935 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1936 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001937 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001938 return BAD_VALUE;
1939 }
1940
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001941 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001942
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001943 {
1944 Mutex::Autolock l(mLock);
1945 switch (mStatus) {
1946 case STATUS_ERROR:
1947 CLOGE("Device has encountered a serious error");
1948 return INVALID_OPERATION;
1949 case STATUS_UNINITIALIZED:
1950 CLOGE("Device is not initialized!");
1951 return INVALID_OPERATION;
1952 case STATUS_UNCONFIGURED:
1953 case STATUS_CONFIGURED:
1954 case STATUS_ACTIVE:
1955 // OK
1956 break;
1957 default:
1958 SET_ERR_L("Unexpected status: %d", mStatus);
1959 return INVALID_OPERATION;
1960 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001961
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001962 if (!mRequestTemplateCache[templateId].isEmpty()) {
1963 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001964 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001965 return OK;
1966 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001967 }
1968
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001969 camera_metadata_t *rawRequest;
1970 status_t res = mInterface->constructDefaultRequestSettings(
1971 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001972
1973 {
1974 Mutex::Autolock l(mLock);
1975 if (res == BAD_VALUE) {
1976 ALOGI("%s: template %d is not supported on this camera device",
1977 __FUNCTION__, templateId);
1978 return res;
1979 } else if (res != OK) {
1980 CLOGE("Unable to construct request template %d: %s (%d)",
1981 templateId, strerror(-res), res);
1982 return res;
1983 }
1984
1985 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1986 mRequestTemplateCache[templateId].acquire(rawRequest);
1987
1988 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001989 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001990 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001991 return OK;
1992}
1993
1994status_t Camera3Device::waitUntilDrained() {
1995 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001996 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001997 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001998 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001999
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002000 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002001}
2002
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002003status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002004 switch (mStatus) {
2005 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002006 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002007 ALOGV("%s: Already idle", __FUNCTION__);
2008 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002009 case STATUS_CONFIGURED:
2010 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002011 case STATUS_ERROR:
2012 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002013 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002014 break;
2015 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002016 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002017 return INVALID_OPERATION;
2018 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002019 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2020 maxExpectedDuration);
2021 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002022 if (res != OK) {
2023 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2024 res);
2025 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002026 return res;
2027}
2028
Ruben Brunk183f0562015-08-12 12:55:02 -07002029
2030void Camera3Device::internalUpdateStatusLocked(Status status) {
2031 mStatus = status;
2032 mRecentStatusUpdates.add(mStatus);
2033 mStatusChanged.broadcast();
2034}
2035
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002036void Camera3Device::pauseStateNotify(bool enable) {
2037 Mutex::Autolock il(mInterfaceLock);
2038 Mutex::Autolock l(mLock);
2039
2040 mPauseStateNotify = enable;
2041}
2042
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002043// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002044status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002045 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002046
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002047 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2048 maxExpectedDuration);
2049 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002050 if (res != OK) {
2051 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002052 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002053 }
2054
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002055 return res;
2056}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002057
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002058// Resume after internalPauseAndWaitLocked
2059status_t Camera3Device::internalResumeLocked() {
2060 status_t res;
2061
2062 mRequestThread->setPaused(false);
2063
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002064 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2065 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002066 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2067 if (res != OK) {
2068 SET_ERR_L("Can't transition to active in %f seconds!",
2069 kActiveTimeout/1e9);
2070 }
2071 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002072 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002073}
2074
Ruben Brunk183f0562015-08-12 12:55:02 -07002075status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002076 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002077
2078 size_t startIndex = 0;
2079 if (mStatusWaiters == 0) {
2080 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2081 // this status list
2082 mRecentStatusUpdates.clear();
2083 } else {
2084 // If other threads are waiting on updates to this status list, set the position of the
2085 // first element that this list will check rather than clearing the list.
2086 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002087 }
2088
Ruben Brunk183f0562015-08-12 12:55:02 -07002089 mStatusWaiters++;
2090
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002091 bool stateSeen = false;
2092 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002093 if (active == (mStatus == STATUS_ACTIVE)) {
2094 // Desired state is current
2095 break;
2096 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002097
2098 res = mStatusChanged.waitRelative(mLock, timeout);
2099 if (res != OK) break;
2100
Ruben Brunk183f0562015-08-12 12:55:02 -07002101 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2102 // transitions.
2103 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2104 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2105 __FUNCTION__);
2106
2107 // Encountered desired state since we began waiting
2108 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002109 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2110 stateSeen = true;
2111 break;
2112 }
2113 }
2114 } while (!stateSeen);
2115
Ruben Brunk183f0562015-08-12 12:55:02 -07002116 mStatusWaiters--;
2117
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002118 return res;
2119}
2120
2121
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002122status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002123 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002124 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002125
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002126 if (listener != NULL && mListener != NULL) {
2127 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2128 }
2129 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002130 mRequestThread->setNotificationListener(listener);
2131 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002132
2133 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002134}
2135
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002136bool Camera3Device::willNotify3A() {
2137 return false;
2138}
2139
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002140status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002141 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002142 status_t res;
2143 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002144
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002145 while (mResultQueue.empty()) {
2146 res = mResultSignal.waitRelative(mOutputLock, timeout);
2147 if (res == TIMED_OUT) {
2148 return res;
2149 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002150 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2151 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002152 return res;
2153 }
2154 }
2155 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002156}
2157
Jianing Weicb0652e2014-03-12 18:29:36 -07002158status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002159 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002160 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002161
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002162 if (mResultQueue.empty()) {
2163 return NOT_ENOUGH_DATA;
2164 }
2165
Jianing Weicb0652e2014-03-12 18:29:36 -07002166 if (frame == NULL) {
2167 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2168 return BAD_VALUE;
2169 }
2170
2171 CaptureResult &result = *(mResultQueue.begin());
2172 frame->mResultExtras = result.mResultExtras;
2173 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002174 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002175 mResultQueue.erase(mResultQueue.begin());
2176
2177 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002178}
2179
2180status_t Camera3Device::triggerAutofocus(uint32_t id) {
2181 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002182 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002183
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002184 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2185 // Mix-in this trigger into the next request and only the next request.
2186 RequestTrigger trigger[] = {
2187 {
2188 ANDROID_CONTROL_AF_TRIGGER,
2189 ANDROID_CONTROL_AF_TRIGGER_START
2190 },
2191 {
2192 ANDROID_CONTROL_AF_TRIGGER_ID,
2193 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002194 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002195 };
2196
2197 return mRequestThread->queueTrigger(trigger,
2198 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002199}
2200
2201status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2202 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002203 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002204
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002205 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2206 // Mix-in this trigger into the next request and only the next request.
2207 RequestTrigger trigger[] = {
2208 {
2209 ANDROID_CONTROL_AF_TRIGGER,
2210 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2211 },
2212 {
2213 ANDROID_CONTROL_AF_TRIGGER_ID,
2214 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002215 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002216 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002217
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002218 return mRequestThread->queueTrigger(trigger,
2219 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002220}
2221
2222status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2223 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002224 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002225
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002226 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2227 // Mix-in this trigger into the next request and only the next request.
2228 RequestTrigger trigger[] = {
2229 {
2230 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2231 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2232 },
2233 {
2234 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2235 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002236 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002237 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002238
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002239 return mRequestThread->queueTrigger(trigger,
2240 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002241}
2242
Jianing Weicb0652e2014-03-12 18:29:36 -07002243status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002244 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002245 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002246 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002247
Zhijun He7ef20392014-04-21 16:04:17 -07002248 {
2249 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002250
2251 // b/116514106 "disconnect()" can get called twice for the same device. The
2252 // camera device will not be initialized during the second run.
2253 if (mStatus == STATUS_UNINITIALIZED) {
2254 return OK;
2255 }
2256
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002257 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002258 }
2259
Emilian Peev08dd2452017-04-06 16:55:14 +01002260 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002261}
2262
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002263status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002264 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2265}
2266
2267status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002268 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002269 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002270 Mutex::Autolock il(mInterfaceLock);
2271 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002272
2273 sp<Camera3StreamInterface> stream;
2274 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2275 if (outputStreamIdx == NAME_NOT_FOUND) {
2276 CLOGE("Stream %d does not exist", streamId);
2277 return BAD_VALUE;
2278 }
2279
2280 stream = mOutputStreams.editValueAt(outputStreamIdx);
2281
2282 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002283 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002284 return BAD_VALUE;
2285 }
2286
2287 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002288 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002289 return BAD_VALUE;
2290 }
2291
Ruben Brunkc78ac262015-08-13 17:58:46 -07002292 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002293}
2294
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002295status_t Camera3Device::tearDown(int streamId) {
2296 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002297 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002298 Mutex::Autolock il(mInterfaceLock);
2299 Mutex::Autolock l(mLock);
2300
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002301 sp<Camera3StreamInterface> stream;
2302 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2303 if (outputStreamIdx == NAME_NOT_FOUND) {
2304 CLOGE("Stream %d does not exist", streamId);
2305 return BAD_VALUE;
2306 }
2307
2308 stream = mOutputStreams.editValueAt(outputStreamIdx);
2309
2310 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2311 CLOGE("Stream %d is a target of a in-progress request", streamId);
2312 return BAD_VALUE;
2313 }
2314
2315 return stream->tearDown();
2316}
2317
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002318status_t Camera3Device::addBufferListenerForStream(int streamId,
2319 wp<Camera3StreamBufferListener> listener) {
2320 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002321 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002322 Mutex::Autolock il(mInterfaceLock);
2323 Mutex::Autolock l(mLock);
2324
2325 sp<Camera3StreamInterface> stream;
2326 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2327 if (outputStreamIdx == NAME_NOT_FOUND) {
2328 CLOGE("Stream %d does not exist", streamId);
2329 return BAD_VALUE;
2330 }
2331
2332 stream = mOutputStreams.editValueAt(outputStreamIdx);
2333 stream->addBufferListener(listener);
2334
2335 return OK;
2336}
2337
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002338/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002339 * Methods called by subclasses
2340 */
2341
2342void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002343 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002344 {
2345 // Need mLock to safely update state and synchronize to current
2346 // state of methods in flight.
2347 Mutex::Autolock l(mLock);
2348 // We can get various system-idle notices from the status tracker
2349 // while starting up. Only care about them if we've actually sent
2350 // in some requests recently.
2351 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2352 return;
2353 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002354 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2355 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002356 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002357
2358 // Skip notifying listener if we're doing some user-transparent
2359 // state changes
2360 if (mPauseStateNotify) return;
2361 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002362
2363 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002364 {
2365 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002366 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002367 }
2368 if (idle && listener != NULL) {
2369 listener->notifyIdle();
2370 }
2371}
2372
Shuzhen Wang758c2152017-01-10 18:26:18 -08002373status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002374 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002375 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002376 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2377 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002378
2379 if (surfaceIds == nullptr) {
2380 return BAD_VALUE;
2381 }
2382
Zhijun He5d677d12016-05-29 16:52:39 -07002383 Mutex::Autolock il(mInterfaceLock);
2384 Mutex::Autolock l(mLock);
2385
Shuzhen Wang758c2152017-01-10 18:26:18 -08002386 if (consumers.size() == 0) {
2387 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002388 return BAD_VALUE;
2389 }
2390
2391 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2392 if (idx == NAME_NOT_FOUND) {
2393 CLOGE("Stream %d is unknown", streamId);
2394 return idx;
2395 }
2396 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002397 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002398 if (res != OK) {
2399 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2400 return res;
2401 }
2402
Emilian Peev40ead602017-09-26 15:46:36 +01002403 for (auto &consumer : consumers) {
2404 int id = stream->getSurfaceId(consumer);
2405 if (id < 0) {
2406 CLOGE("Invalid surface id!");
2407 return BAD_VALUE;
2408 }
2409 surfaceIds->push_back(id);
2410 }
2411
Shuzhen Wang0129d522016-10-30 22:43:41 -07002412 if (stream->isConsumerConfigurationDeferred()) {
2413 if (!stream->isConfiguring()) {
2414 CLOGE("Stream %d was already fully configured.", streamId);
2415 return INVALID_OPERATION;
2416 }
Zhijun He5d677d12016-05-29 16:52:39 -07002417
Shuzhen Wang0129d522016-10-30 22:43:41 -07002418 res = stream->finishConfiguration();
2419 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002420 // If finishConfiguration fails due to abandoned surface, do not set
2421 // device to error state.
2422 bool isSurfaceAbandoned =
2423 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2424 if (!isSurfaceAbandoned) {
2425 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2426 stream->getId(), strerror(-res), res);
2427 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002428 return res;
2429 }
Zhijun He5d677d12016-05-29 16:52:39 -07002430 }
2431
2432 return OK;
2433}
2434
Emilian Peev40ead602017-09-26 15:46:36 +01002435status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2436 const std::vector<OutputStreamInfo> &outputInfo,
2437 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2438 Mutex::Autolock il(mInterfaceLock);
2439 Mutex::Autolock l(mLock);
2440
2441 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2442 if (idx == NAME_NOT_FOUND) {
2443 CLOGE("Stream %d is unknown", streamId);
2444 return idx;
2445 }
2446
2447 for (const auto &it : removedSurfaceIds) {
2448 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2449 CLOGE("Shared surface still part of a pending request!");
2450 return -EBUSY;
2451 }
2452 }
2453
2454 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2455 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2456 if (res != OK) {
2457 CLOGE("Stream %d failed to update stream (error %d %s) ",
2458 streamId, res, strerror(-res));
2459 if (res == UNKNOWN_ERROR) {
2460 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2461 __FUNCTION__);
2462 }
2463 return res;
2464 }
2465
2466 return res;
2467}
2468
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002469status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2470 Mutex::Autolock il(mInterfaceLock);
2471 Mutex::Autolock l(mLock);
2472
2473 int idx = mOutputStreams.indexOfKey(streamId);
2474 if (idx == NAME_NOT_FOUND) {
2475 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2476 return BAD_VALUE;
2477 }
2478
2479 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2480 return stream->dropBuffers(dropping);
2481}
2482
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002483/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002484 * Camera3Device private methods
2485 */
2486
2487sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002488 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002489 ATRACE_CALL();
2490 status_t res;
2491
2492 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002493 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002494
2495 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002496 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002497 if (inputStreams.count > 0) {
2498 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002499 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002500 CLOGE("Request references unknown input stream %d",
2501 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002502 return NULL;
2503 }
2504 // Lazy completion of stream configuration (allocation/registration)
2505 // on first use
2506 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002507 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002508 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002509 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002510 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002511 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002512 return NULL;
2513 }
2514 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002515 // Check if stream prepare is blocking requests.
2516 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002517 CLOGE("Request references an input stream that's being prepared!");
2518 return NULL;
2519 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002520
2521 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002522 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002523 }
2524
2525 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002526 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002527 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002528 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002529 return NULL;
2530 }
2531
2532 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002533 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002534 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002535 CLOGE("Request references unknown stream %d",
2536 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002537 return NULL;
2538 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002539 sp<Camera3OutputStreamInterface> stream =
2540 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002541
Zhijun He5d677d12016-05-29 16:52:39 -07002542 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002543 auto iter = surfaceMap.find(streams.data.i32[i]);
2544 if (iter != surfaceMap.end()) {
2545 const std::vector<size_t>& surfaces = iter->second;
2546 for (const auto& surface : surfaces) {
2547 if (stream->isConsumerConfigurationDeferred(surface)) {
2548 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2549 "due to deferred consumer", stream->getId(), surface);
2550 return NULL;
2551 }
2552 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002553 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002554 }
2555
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002556 // Lazy completion of stream configuration (allocation/registration)
2557 // on first use
2558 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002559 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002560 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002561 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2562 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002563 return NULL;
2564 }
2565 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002566 // Check if stream prepare is blocking requests.
2567 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002568 CLOGE("Request references an output stream that's being prepared!");
2569 return NULL;
2570 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002571
2572 newRequest->mOutputStreams.push(stream);
2573 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002574 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002575 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002576
2577 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002578}
2579
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002580bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2581 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2582 Size size = mSupportedOpaqueInputSizes[i];
2583 if (size.width == width && size.height == height) {
2584 return true;
2585 }
2586 }
2587
2588 return false;
2589}
2590
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002591void Camera3Device::cancelStreamsConfigurationLocked() {
2592 int res = OK;
2593 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2594 res = mInputStream->cancelConfiguration();
2595 if (res != OK) {
2596 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2597 mInputStream->getId(), strerror(-res), res);
2598 }
2599 }
2600
2601 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2602 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2603 if (outputStream->isConfiguring()) {
2604 res = outputStream->cancelConfiguration();
2605 if (res != OK) {
2606 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2607 outputStream->getId(), strerror(-res), res);
2608 }
2609 }
2610 }
2611
2612 // Return state to that at start of call, so that future configures
2613 // properly clean things up
2614 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2615 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002616
2617 res = mPreparerThread->resume();
2618 if (res != OK) {
2619 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2620 }
2621}
2622
2623bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2624 ATRACE_CALL();
2625 bool ret = false;
2626
2627 Mutex::Autolock il(mInterfaceLock);
2628 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2629
2630 Mutex::Autolock l(mLock);
2631 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2632 if (rc == NO_ERROR) {
2633 mNeedConfig = true;
2634 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2635 if (rc == NO_ERROR) {
2636 ret = true;
2637 mPauseStateNotify = false;
2638 //Moving to active state while holding 'mLock' is important.
2639 //There could be pending calls to 'create-/deleteStream' which
2640 //will trigger another stream configuration while the already
2641 //present streams end up with outstanding buffers that will
2642 //not get drained.
2643 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002644 } else if (rc == DEAD_OBJECT) {
2645 // DEAD_OBJECT can be returned if either the consumer surface is
2646 // abandoned, or the HAL has died.
2647 // - If the HAL has died, configureStreamsLocked call will set
2648 // device to error state,
2649 // - If surface is abandoned, we should not set device to error
2650 // state.
2651 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002652 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002653 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002654 }
2655 } else {
2656 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2657 }
2658
2659 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002660}
2661
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002662status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002663 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002664 ATRACE_CALL();
2665 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002666
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002667 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002668 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002669 return INVALID_OPERATION;
2670 }
2671
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002672 if (operatingMode < 0) {
2673 CLOGE("Invalid operating mode: %d", operatingMode);
2674 return BAD_VALUE;
2675 }
2676
2677 bool isConstrainedHighSpeed =
2678 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2679 operatingMode;
2680
2681 if (mOperatingMode != operatingMode) {
2682 mNeedConfig = true;
2683 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2684 mOperatingMode = operatingMode;
2685 }
2686
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002687 if (!mNeedConfig) {
2688 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2689 return OK;
2690 }
2691
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002692 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2693 // adding a dummy stream instead.
2694 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2695 if (mOutputStreams.size() == 0) {
2696 addDummyStreamLocked();
2697 } else {
2698 tryRemoveDummyStreamLocked();
2699 }
2700
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002701 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002702 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002703
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002704 mPreparerThread->pause();
2705
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002706 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002707 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002708 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2709
2710 Vector<camera3_stream_t*> streams;
2711 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002712 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002713
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002714
2715 if (mInputStream != NULL) {
2716 camera3_stream_t *inputStream;
2717 inputStream = mInputStream->startConfiguration();
2718 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002719 CLOGE("Can't start input stream configuration");
2720 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002721 return INVALID_OPERATION;
2722 }
2723 streams.add(inputStream);
2724 }
2725
2726 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002727
2728 // Don't configure bidi streams twice, nor add them twice to the list
2729 if (mOutputStreams[i].get() ==
2730 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2731
2732 config.num_streams--;
2733 continue;
2734 }
2735
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002736 camera3_stream_t *outputStream;
2737 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2738 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002739 CLOGE("Can't start output stream configuration");
2740 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002741 return INVALID_OPERATION;
2742 }
2743 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002744
2745 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2746 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002747 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2748 // always occupy the initial entry.
2749 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002750 getJpegBufferSize(outputStream->width, outputStream->height));
2751 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002752 }
2753
2754 config.streams = streams.editArray();
2755
2756 // Do the HAL configuration; will potentially touch stream
2757 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002758
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002759 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002760 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002761 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002762
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002763 if (res == BAD_VALUE) {
2764 // HAL rejected this set of streams as unsupported, clean up config
2765 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002766 CLOGE("Set of requested inputs/outputs not supported by HAL");
2767 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002768 return BAD_VALUE;
2769 } else if (res != OK) {
2770 // Some other kind of error from configure_streams - this is not
2771 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002772 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2773 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002774 return res;
2775 }
2776
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002777 // Finish all stream configuration immediately.
2778 // TODO: Try to relax this later back to lazy completion, which should be
2779 // faster
2780
Igor Murashkin073f8572013-05-02 14:59:28 -07002781 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002782 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002783 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002784 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002785 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002786 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002787 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2788 return DEAD_OBJECT;
2789 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002790 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002791 }
2792 }
2793
2794 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002795 sp<Camera3OutputStreamInterface> outputStream =
2796 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002797 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002798 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002799 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002800 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002801 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002802 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002803 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2804 return DEAD_OBJECT;
2805 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002806 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002807 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002808 }
2809 }
2810
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002811 // Request thread needs to know to avoid using repeat-last-settings protocol
2812 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002813 if (notifyRequestThread) {
2814 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2815 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002816
Zhijun He90f7c372016-08-16 16:19:43 -07002817 char value[PROPERTY_VALUE_MAX];
2818 property_get("camera.fifo.disable", value, "0");
2819 int32_t disableFifo = atoi(value);
2820 if (disableFifo != 1) {
2821 // Boost priority of request thread to SCHED_FIFO.
2822 pid_t requestThreadTid = mRequestThread->getTid();
2823 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002824 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002825 if (res != OK) {
2826 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2827 strerror(-res), res);
2828 } else {
2829 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2830 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002831 }
2832
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002833 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002834 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2835 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2836 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2837 sessionParams.unlock(newSessionParams);
2838 mSessionParams.unlock(currentSessionParams);
2839 if (updateSessionParams) {
2840 mSessionParams = sessionParams;
2841 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002842
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002843 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002844
Ruben Brunk183f0562015-08-12 12:55:02 -07002845 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2846 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002847
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002848 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002849
Zhijun He0a210512014-07-24 13:45:15 -07002850 // tear down the deleted streams after configure streams.
2851 mDeletedStreams.clear();
2852
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002853 auto rc = mPreparerThread->resume();
2854 if (rc != OK) {
2855 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2856 return rc;
2857 }
2858
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002859 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002860}
2861
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002862status_t Camera3Device::addDummyStreamLocked() {
2863 ATRACE_CALL();
2864 status_t res;
2865
2866 if (mDummyStreamId != NO_STREAM) {
2867 // Should never be adding a second dummy stream when one is already
2868 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002869 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2870 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002871 return INVALID_OPERATION;
2872 }
2873
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002874 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002875
2876 sp<Camera3OutputStreamInterface> dummyStream =
2877 new Camera3DummyStream(mNextStreamId);
2878
2879 res = mOutputStreams.add(mNextStreamId, dummyStream);
2880 if (res < 0) {
2881 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2882 return res;
2883 }
2884
2885 mDummyStreamId = mNextStreamId;
2886 mNextStreamId++;
2887
2888 return OK;
2889}
2890
2891status_t Camera3Device::tryRemoveDummyStreamLocked() {
2892 ATRACE_CALL();
2893 status_t res;
2894
2895 if (mDummyStreamId == NO_STREAM) return OK;
2896 if (mOutputStreams.size() == 1) return OK;
2897
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002898 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002899
2900 // Ok, have a dummy stream and there's at least one other output stream,
2901 // so remove the dummy
2902
2903 sp<Camera3StreamInterface> deletedStream;
2904 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2905 if (outputStreamIdx == NAME_NOT_FOUND) {
2906 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2907 return INVALID_OPERATION;
2908 }
2909
2910 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2911 mOutputStreams.removeItemsAt(outputStreamIdx);
2912
2913 // Free up the stream endpoint so that it can be used by some other stream
2914 res = deletedStream->disconnect();
2915 if (res != OK) {
2916 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2917 // fall through since we want to still list the stream as deleted.
2918 }
2919 mDeletedStreams.add(deletedStream);
2920 mDummyStreamId = NO_STREAM;
2921
2922 return res;
2923}
2924
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002925void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002926 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002927 Mutex::Autolock l(mLock);
2928 va_list args;
2929 va_start(args, fmt);
2930
2931 setErrorStateLockedV(fmt, args);
2932
2933 va_end(args);
2934}
2935
2936void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002937 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002938 Mutex::Autolock l(mLock);
2939 setErrorStateLockedV(fmt, args);
2940}
2941
2942void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2943 va_list args;
2944 va_start(args, fmt);
2945
2946 setErrorStateLockedV(fmt, args);
2947
2948 va_end(args);
2949}
2950
2951void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002952 // Print out all error messages to log
2953 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002954 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002955
2956 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002957 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002958
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002959 mErrorCause = errorCause;
2960
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002961 if (mRequestThread != nullptr) {
2962 mRequestThread->setPaused(true);
2963 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002964 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002965
2966 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002967 sp<NotificationListener> listener = mListener.promote();
2968 if (listener != NULL) {
2969 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002970 CaptureResultExtras());
2971 }
2972
2973 // Save stack trace. View by dumping it later.
2974 CameraTraces::saveTrace();
2975 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002976}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002977
2978/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002979 * In-flight request management
2980 */
2981
Jianing Weicb0652e2014-03-12 18:29:36 -07002982status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002983 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002984 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002985 std::set<String8>& physicalCameraIds, bool isStillCapture,
2986 bool isZslCapture) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002987 ATRACE_CALL();
2988 Mutex::Autolock l(mInFlightLock);
2989
2990 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002991 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002992 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002993 if (res < 0) return res;
2994
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002995 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002996 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2997 // avoid a deadlock during reprocess requests.
2998 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002999 if (mStatusTracker != nullptr) {
3000 mStatusTracker->markComponentActive(mInFlightStatusId);
3001 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003002 }
3003
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003004 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003005 return OK;
3006}
3007
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003008void Camera3Device::returnOutputBuffers(
3009 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003010 nsecs_t timestamp, bool timestampIncreasing) {
3011
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003012 for (size_t i = 0; i < numBuffers; i++)
3013 {
3014 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003015 status_t res = stream->returnBuffer(outputBuffers[i], timestamp, timestampIncreasing);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003016 // Note: stream may be deallocated at this point, if this buffer was
3017 // the last reference to it.
3018 if (res != OK) {
3019 ALOGE("Can't return buffer to its stream: %s (%d)",
3020 strerror(-res), res);
3021 }
3022 }
3023}
3024
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003025void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003026 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003027 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003028 mInFlightMap.removeItemsAt(idx, 1);
3029
3030 // Indicate idle inFlightMap to the status tracker
3031 if (mInFlightMap.size() == 0) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003032 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3033 // avoid a deadlock during reprocess requests.
3034 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003035 if (mStatusTracker != nullptr) {
3036 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3037 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003038 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003039 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003040}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003041
3042void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3043
3044 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3045 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3046
3047 nsecs_t sensorTimestamp = request.sensorTimestamp;
3048 nsecs_t shutterTimestamp = request.shutterTimestamp;
3049
3050 // Check if it's okay to remove the request from InFlightMap:
3051 // In the case of a successful request:
3052 // all input and output buffers, all result metadata, shutter callback
3053 // arrived.
3054 // In the case of a unsuccessful request:
3055 // all input and output buffers arrived.
3056 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003057 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003058 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003059 if (request.stillCapture) {
3060 ATRACE_ASYNC_END("still capture", frameNumber);
3061 }
3062
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003063 ATRACE_ASYNC_END("frame capture", frameNumber);
3064
Shuzhen Wang403044a2017-02-26 23:29:04 -08003065 // Sanity check - if sensor timestamp matches shutter timestamp in the
3066 // case of request having callback.
3067 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003068 sensorTimestamp != shutterTimestamp) {
3069 SET_ERR("sensor timestamp (%" PRId64
3070 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3071 sensorTimestamp, frameNumber, shutterTimestamp);
3072 }
3073
3074 // for an unsuccessful request, it may have pending output buffers to
3075 // return.
3076 assert(request.requestStatus != OK ||
3077 request.pendingOutputBuffers.size() == 0);
3078 returnOutputBuffers(request.pendingOutputBuffers.array(),
3079 request.pendingOutputBuffers.size(), 0);
3080
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003081 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003082 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3083 }
3084
3085 // Sanity check - if we have too many in-flight frames, something has
3086 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003087 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003088 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003089 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3090 kInFlightWarnLimitHighSpeed) {
3091 CLOGE("In-flight list too large for high speed configuration: %zu",
3092 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003093 }
3094}
3095
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003096void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003097 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003098 { // First return buffers cached in mInFlightMap
3099 Mutex::Autolock l(mInFlightLock);
3100 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3101 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3102 returnOutputBuffers(request.pendingOutputBuffers.array(),
3103 request.pendingOutputBuffers.size(), 0);
3104 }
3105 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003106 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003107 }
3108
3109 // Then return all inflight buffers not returned by HAL
3110 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3111 mInterface->getInflightBufferKeys(&inflightKeys);
3112
3113 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3114 for (auto& pair : inflightKeys) {
3115 int32_t frameNumber = pair.first;
3116 int32_t streamId = pair.second;
3117 buffer_handle_t* buffer;
3118 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3119 if (res != OK) {
3120 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3121 __FUNCTION__, frameNumber, streamId);
3122 continue;
3123 }
3124
3125 camera3_stream_buffer_t streamBuffer;
3126 streamBuffer.buffer = buffer;
3127 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3128 streamBuffer.acquire_fence = -1;
3129 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003130
3131 // First check if the buffer belongs to deleted stream
3132 bool streamDeleted = false;
3133 for (auto& stream : mDeletedStreams) {
3134 if (streamId == stream->getId()) {
3135 streamDeleted = true;
3136 // Return buffer to deleted stream
3137 camera3_stream* halStream = stream->asHalStream();
3138 streamBuffer.stream = halStream;
3139 switch (halStream->stream_type) {
3140 case CAMERA3_STREAM_OUTPUT:
3141 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
3142 if (res != OK) {
3143 ALOGE("%s: Can't return output buffer for frame %d to"
3144 " stream %d: %s (%d)", __FUNCTION__,
3145 frameNumber, streamId, strerror(-res), res);
3146 }
3147 break;
3148 case CAMERA3_STREAM_INPUT:
3149 res = stream->returnInputBuffer(streamBuffer);
3150 if (res != OK) {
3151 ALOGE("%s: Can't return input buffer for frame %d to"
3152 " stream %d: %s (%d)", __FUNCTION__,
3153 frameNumber, streamId, strerror(-res), res);
3154 }
3155 break;
3156 default: // Bi-direcitonal stream is deprecated
3157 ALOGE("%s: stream %d has unknown stream type %d",
3158 __FUNCTION__, streamId, halStream->stream_type);
3159 break;
3160 }
3161 break;
3162 }
3163 }
3164 if (streamDeleted) {
3165 continue;
3166 }
3167
3168 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003169 if (streamId == inputStreamId) {
3170 streamBuffer.stream = mInputStream->asHalStream();
3171 res = mInputStream->returnInputBuffer(streamBuffer);
3172 if (res != OK) {
3173 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003174 " stream %d: %s (%d)", __FUNCTION__,
3175 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003176 }
3177 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003178 ssize_t idx = mOutputStreams.indexOfKey(streamId);
3179 if (idx == NAME_NOT_FOUND) {
3180 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3181 continue;
3182 }
3183 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003184 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3185 }
3186 }
3187}
3188
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003189void Camera3Device::insertResultLocked(CaptureResult *result,
3190 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003191 if (result == nullptr) return;
3192
Emilian Peev71c73a22017-03-21 16:35:51 +00003193 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3194 result->mMetadata.getAndLock());
3195 set_camera_metadata_vendor_id(meta, mVendorTagId);
3196 result->mMetadata.unlock(meta);
3197
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003198 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3199 (int32_t*)&frameNumber, 1) != OK) {
3200 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3201 return;
3202 }
3203
3204 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3205 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3206 return;
3207 }
3208
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003209 // Valid result, insert into queue
3210 List<CaptureResult>::iterator queuedResult =
3211 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3212 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3213 ", burstId = %" PRId32, __FUNCTION__,
3214 queuedResult->mResultExtras.requestId,
3215 queuedResult->mResultExtras.frameNumber,
3216 queuedResult->mResultExtras.burstId);
3217
3218 mResultSignal.signal();
3219}
3220
3221
3222void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003223 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003224 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003225 Mutex::Autolock l(mOutputLock);
3226
3227 CaptureResult captureResult;
3228 captureResult.mResultExtras = resultExtras;
3229 captureResult.mMetadata = partialResult;
3230
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003231 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003232}
3233
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003234
3235void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3236 CaptureResultExtras &resultExtras,
3237 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003238 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003239 bool reprocess,
3240 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003241 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003242 if (pendingMetadata.isEmpty())
3243 return;
3244
3245 Mutex::Autolock l(mOutputLock);
3246
3247 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003248 if (reprocess) {
3249 if (frameNumber < mNextReprocessResultFrameNumber) {
3250 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003251 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003252 frameNumber, mNextReprocessResultFrameNumber);
3253 return;
3254 }
3255 mNextReprocessResultFrameNumber = frameNumber + 1;
3256 } else {
3257 if (frameNumber < mNextResultFrameNumber) {
3258 SET_ERR("Out-of-order capture result metadata submitted! "
3259 "(got frame number %d, expecting %d)",
3260 frameNumber, mNextResultFrameNumber);
3261 return;
3262 }
3263 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003264 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003265
3266 CaptureResult captureResult;
3267 captureResult.mResultExtras = resultExtras;
3268 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003269 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003270
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003271 // Append any previous partials to form a complete result
3272 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3273 captureResult.mMetadata.append(collectedPartialResult);
3274 }
3275
3276 captureResult.mMetadata.sort();
3277
3278 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003279 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3280 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003281 SET_ERR("No timestamp provided by HAL for frame %d!",
3282 frameNumber);
3283 return;
3284 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003285 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3286 camera_metadata_entry timestamp =
3287 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3288 if (timestamp.count == 0) {
3289 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3290 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3291 return;
3292 }
3293 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003294
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003295 // Fix up some result metadata to account for HAL-level distortion correction
3296 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3297 if (res != OK) {
3298 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3299 frameNumber, strerror(res), res);
3300 return;
3301 }
3302
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003303 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3304 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3305
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003306 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003307}
3308
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003309/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003310 * Camera HAL device callback methods
3311 */
3312
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003313void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003314 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003315
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003316 status_t res;
3317
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003318 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003319 if (result->result == NULL && result->num_output_buffers == 0 &&
3320 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003321 SET_ERR("No result data provided by HAL for frame %d",
3322 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003323 return;
3324 }
Zhijun He204e3292014-07-14 17:09:23 -07003325
Zhijun He204e3292014-07-14 17:09:23 -07003326 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003327 result->result != NULL &&
3328 result->partial_result != 1) {
3329 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3330 " if partial result is not supported",
3331 frameNumber, result->partial_result);
3332 return;
3333 }
3334
3335 bool isPartialResult = false;
3336 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003337 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003338
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003339 // Get shutter timestamp and resultExtras from list of in-flight requests,
3340 // where it was added by the shutter notification for this frame. If the
3341 // shutter timestamp isn't received yet, append the output buffers to the
3342 // in-flight request and they will be returned when the shutter timestamp
3343 // arrives. Update the in-flight status and remove the in-flight entry if
3344 // all result data and shutter timestamp have been received.
3345 nsecs_t shutterTimestamp = 0;
3346
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003347 {
3348 Mutex::Autolock l(mInFlightLock);
3349 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3350 if (idx == NAME_NOT_FOUND) {
3351 SET_ERR("Unknown frame number for capture result: %d",
3352 frameNumber);
3353 return;
3354 }
3355 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003356 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3357 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003358 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003359 __FUNCTION__, request.resultExtras.requestId,
3360 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003361 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003362 // Always update the partial count to the latest one if it's not 0
3363 // (buffers only). When framework aggregates adjacent partial results
3364 // into one, the latest partial count will be used.
3365 if (result->partial_result != 0)
3366 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003367
3368 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003369 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003370 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3371 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3372 " the range of [1, %d] when metadata is included in the result",
3373 frameNumber, result->partial_result, mNumPartialResults);
3374 return;
3375 }
3376 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003377 if (isPartialResult && result->num_physcam_metadata) {
3378 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3379 " physical camera result", frameNumber);
3380 return;
3381 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003382 if (isPartialResult) {
3383 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003384 }
3385
Shuzhen Wang4a472662017-02-26 23:29:04 -08003386 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003387 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003388 sendPartialCaptureResult(result->result, request.resultExtras,
3389 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003390 }
3391 }
3392
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003393 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003394 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003395
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003396 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003397 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003398 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3399 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3400 request.physicalCameraIds.size(), result->num_physcam_metadata);
3401 return;
3402 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003403 if (request.haveResultMetadata) {
3404 SET_ERR("Called multiple times with metadata for frame %d",
3405 frameNumber);
3406 return;
3407 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003408 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3409 String8 physicalId(result->physcam_ids[i]);
3410 std::set<String8>::iterator cameraIdIter =
3411 request.physicalCameraIds.find(physicalId);
3412 if (cameraIdIter != request.physicalCameraIds.end()) {
3413 request.physicalCameraIds.erase(cameraIdIter);
3414 } else {
3415 SET_ERR("Total result for frame %d has already returned for camera %s",
3416 frameNumber, physicalId.c_str());
3417 return;
3418 }
3419 }
Zhijun He204e3292014-07-14 17:09:23 -07003420 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003421 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003422 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003423 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003424 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003425 request.haveResultMetadata = true;
3426 }
3427
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003428 uint32_t numBuffersReturned = result->num_output_buffers;
3429 if (result->input_buffer != NULL) {
3430 if (hasInputBufferInRequest) {
3431 numBuffersReturned += 1;
3432 } else {
3433 ALOGW("%s: Input buffer should be NULL if there is no input"
3434 " buffer sent in the request",
3435 __FUNCTION__);
3436 }
3437 }
3438 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003439 if (request.numBuffersLeft < 0) {
3440 SET_ERR("Too many buffers returned for frame %d",
3441 frameNumber);
3442 return;
3443 }
3444
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003445 camera_metadata_ro_entry_t entry;
3446 res = find_camera_metadata_ro_entry(result->result,
3447 ANDROID_SENSOR_TIMESTAMP, &entry);
3448 if (res == OK && entry.count == 1) {
3449 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003450 }
3451
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003452 // If shutter event isn't received yet, append the output buffers to
3453 // the in-flight request. Otherwise, return the output buffers to
3454 // streams.
3455 if (shutterTimestamp == 0) {
3456 request.pendingOutputBuffers.appendArray(result->output_buffers,
3457 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003458 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003459 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003460 returnOutputBuffers(result->output_buffers,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003461 result->num_output_buffers, shutterTimestamp, timestampIncreasing);
Igor Murashkind2c90692013-04-02 12:32:32 -07003462 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003463
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003464 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003465 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3466 CameraMetadata physicalMetadata;
3467 physicalMetadata.append(result->physcam_metadata[i]);
3468 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3469 physicalMetadata});
3470 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003471 if (shutterTimestamp == 0) {
3472 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003473 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003474 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003475 CameraMetadata metadata;
3476 metadata = result->result;
3477 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003478 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003479 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003480 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003481 }
3482
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003483 removeInFlightRequestIfReadyLocked(idx);
3484 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003485
Zhijun Hef0d962a2014-06-30 10:24:11 -07003486 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003487 if (hasInputBufferInRequest) {
3488 Camera3Stream *stream =
3489 Camera3Stream::cast(result->input_buffer->stream);
3490 res = stream->returnInputBuffer(*(result->input_buffer));
3491 // Note: stream may be deallocated at this point, if this buffer was the
3492 // last reference to it.
3493 if (res != OK) {
3494 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3495 " its stream:%s (%d)", __FUNCTION__,
3496 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003497 }
3498 } else {
3499 ALOGW("%s: Input buffer should be NULL if there is no input"
3500 " buffer sent in the request, skipping input buffer return.",
3501 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003502 }
3503 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003504}
3505
3506void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003507 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003508 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003509 {
3510 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003511 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003512 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003513
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003514 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003515 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003516 return;
3517 }
3518
3519 switch (msg->type) {
3520 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003521 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003522 break;
3523 }
3524 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003525 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003526 break;
3527 }
3528 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003529 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003530 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003531 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003532}
3533
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003534void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003535 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003536 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003537 // Map camera HAL error codes to ICameraDeviceCallback error codes
3538 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003539 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003540 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003541 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003542 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003543 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003544 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003545 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003546 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003547 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003548 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003549 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003550 };
3551
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003552 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003553 ((msg.error_code >= 0) &&
3554 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3555 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003556 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003557
3558 int streamId = 0;
3559 if (msg.error_stream != NULL) {
3560 Camera3Stream *stream =
3561 Camera3Stream::cast(msg.error_stream);
3562 streamId = stream->getId();
3563 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003564 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3565 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003566 streamId, msg.error_code);
3567
3568 CaptureResultExtras resultExtras;
3569 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003570 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003571 // SET_ERR calls notifyError
3572 SET_ERR("Camera HAL reported serious device error");
3573 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003574 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3575 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3576 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003577 {
3578 Mutex::Autolock l(mInFlightLock);
3579 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3580 if (idx >= 0) {
3581 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3582 r.requestStatus = msg.error_code;
3583 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003584 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3585 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3586 errorCode) {
3587 r.skipResultMetadata = true;
3588 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003589 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3590 errorCode) {
3591 // In case of missing result check whether the buffers
3592 // returned. If they returned, then remove inflight
3593 // request.
3594 removeInFlightRequestIfReadyLocked(idx);
3595 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003596 } else {
3597 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003598 ALOGE("Camera %s: %s: cannot find in-flight request on "
3599 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003600 resultExtras.frameNumber);
3601 }
3602 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003603 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003604 if (listener != NULL) {
3605 listener->notifyError(errorCode, resultExtras);
3606 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003607 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003608 }
3609 break;
3610 default:
3611 // SET_ERR calls notifyError
3612 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3613 break;
3614 }
3615}
3616
3617void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003618 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003619 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003620 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003621
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003622 // Set timestamp for the request in the in-flight tracking
3623 // and get the request ID to send upstream
3624 {
3625 Mutex::Autolock l(mInFlightLock);
3626 idx = mInFlightMap.indexOfKey(msg.frame_number);
3627 if (idx >= 0) {
3628 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003629
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003630 // Verify ordering of shutter notifications
3631 {
3632 Mutex::Autolock l(mOutputLock);
3633 // TODO: need to track errors for tighter bounds on expected frame number.
3634 if (r.hasInputBuffer) {
3635 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3636 SET_ERR("Shutter notification out-of-order. Expected "
3637 "notification for frame %d, got frame %d",
3638 mNextReprocessShutterFrameNumber, msg.frame_number);
3639 return;
3640 }
3641 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3642 } else {
3643 if (msg.frame_number < mNextShutterFrameNumber) {
3644 SET_ERR("Shutter notification out-of-order. Expected "
3645 "notification for frame %d, got frame %d",
3646 mNextShutterFrameNumber, msg.frame_number);
3647 return;
3648 }
3649 mNextShutterFrameNumber = msg.frame_number + 1;
3650 }
3651 }
3652
Shuzhen Wang4a472662017-02-26 23:29:04 -08003653 r.shutterTimestamp = msg.timestamp;
3654 if (r.hasCallback) {
3655 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003656 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003657 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003658 // Call listener, if any
3659 if (listener != NULL) {
3660 listener->notifyShutter(r.resultExtras, msg.timestamp);
3661 }
3662 // send pending result and buffers
3663 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3664 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003665 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003666 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003667 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003668 returnOutputBuffers(r.pendingOutputBuffers.array(),
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003669 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003670 r.pendingOutputBuffers.clear();
3671
3672 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003673 }
3674 }
3675 if (idx < 0) {
3676 SET_ERR("Shutter notification for non-existent frame number %d",
3677 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003678 }
3679}
3680
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003681CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003682 ALOGV("%s", __FUNCTION__);
3683
Igor Murashkin1e479c02013-09-06 16:55:14 -07003684 CameraMetadata retVal;
3685
3686 if (mRequestThread != NULL) {
3687 retVal = mRequestThread->getLatestRequest();
3688 }
3689
Igor Murashkin1e479c02013-09-06 16:55:14 -07003690 return retVal;
3691}
3692
Jianing Weicb0652e2014-03-12 18:29:36 -07003693
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003694void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3695 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3696 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3697}
3698
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003699/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003700 * HalInterface inner class methods
3701 */
3702
Yifan Hongf79b5542017-04-11 14:44:25 -07003703Camera3Device::HalInterface::HalInterface(
3704 sp<ICameraDeviceSession> &session,
3705 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003706 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003707 mRequestMetadataQueue(queue) {
3708 // Check with hardware service manager if we can downcast these interfaces
3709 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003710 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3711 if (castResult_3_5.isOk()) {
3712 mHidlSession_3_5 = castResult_3_5;
3713 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003714 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3715 if (castResult_3_4.isOk()) {
3716 mHidlSession_3_4 = castResult_3_4;
3717 }
3718 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3719 if (castResult_3_3.isOk()) {
3720 mHidlSession_3_3 = castResult_3_3;
3721 }
3722}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003723
Emilian Peev31abd0a2017-05-11 18:37:46 +01003724Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003725
3726Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003727 mHidlSession(other.mHidlSession),
3728 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003729
3730bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003731 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003732}
3733
3734void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003735 mHidlSession_3_4.clear();
3736 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003737 mHidlSession.clear();
3738}
3739
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003740bool Camera3Device::HalInterface::supportBatchRequest() {
3741 return mHidlSession != nullptr;
3742}
3743
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003744status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3745 camera3_request_template_t templateId,
3746 /*out*/ camera_metadata_t **requestTemplate) {
3747 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3748 if (!valid()) return INVALID_OPERATION;
3749 status_t res = OK;
3750
Emilian Peev31abd0a2017-05-11 18:37:46 +01003751 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003752
3753 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003754 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003755 status = s;
3756 if (status == common::V1_0::Status::OK) {
3757 const camera_metadata *r =
3758 reinterpret_cast<const camera_metadata_t*>(request.data());
3759 size_t expectedSize = request.size();
3760 int ret = validate_camera_metadata_structure(r, &expectedSize);
3761 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3762 *requestTemplate = clone_camera_metadata(r);
3763 if (*requestTemplate == nullptr) {
3764 ALOGE("%s: Unable to clone camera metadata received from HAL",
3765 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003766 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003767 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003768 } else {
3769 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3770 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003771 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003772 }
3773 };
3774 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003775 RequestTemplate id;
3776 switch (templateId) {
3777 case CAMERA3_TEMPLATE_PREVIEW:
3778 id = RequestTemplate::PREVIEW;
3779 break;
3780 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3781 id = RequestTemplate::STILL_CAPTURE;
3782 break;
3783 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3784 id = RequestTemplate::VIDEO_RECORD;
3785 break;
3786 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3787 id = RequestTemplate::VIDEO_SNAPSHOT;
3788 break;
3789 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3790 id = RequestTemplate::ZERO_SHUTTER_LAG;
3791 break;
3792 case CAMERA3_TEMPLATE_MANUAL:
3793 id = RequestTemplate::MANUAL;
3794 break;
3795 default:
3796 // Unknown template ID, or this HAL is too old to support it
3797 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003798 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003799 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003800
Emilian Peev31abd0a2017-05-11 18:37:46 +01003801 if (!err.isOk()) {
3802 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3803 res = DEAD_OBJECT;
3804 } else {
3805 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003806 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003807
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003808 return res;
3809}
3810
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003811status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003812 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003813 ATRACE_NAME("CameraHal::configureStreams");
3814 if (!valid()) return INVALID_OPERATION;
3815 status_t res = OK;
3816
Emilian Peev31abd0a2017-05-11 18:37:46 +01003817 // Convert stream config to HIDL
3818 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003819 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3820 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3821 requestedConfiguration3_2.streams.resize(config->num_streams);
3822 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003823 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003824 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3825 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003826 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003827
Emilian Peev31abd0a2017-05-11 18:37:46 +01003828 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3829 cam3stream->setBufferFreedListener(this);
3830 int streamId = cam3stream->getId();
3831 StreamType streamType;
3832 switch (src->stream_type) {
3833 case CAMERA3_STREAM_OUTPUT:
3834 streamType = StreamType::OUTPUT;
3835 break;
3836 case CAMERA3_STREAM_INPUT:
3837 streamType = StreamType::INPUT;
3838 break;
3839 default:
3840 ALOGE("%s: Stream %d: Unsupported stream type %d",
3841 __FUNCTION__, streamId, config->streams[i]->stream_type);
3842 return BAD_VALUE;
3843 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003844 dst3_2.id = streamId;
3845 dst3_2.streamType = streamType;
3846 dst3_2.width = src->width;
3847 dst3_2.height = src->height;
3848 dst3_2.format = mapToPixelFormat(src->format);
3849 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3850 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3851 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3852 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003853 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003854 if (src->physical_camera_id != nullptr) {
3855 dst3_4.physicalCameraId = src->physical_camera_id;
3856 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003857
3858 activeStreams.insert(streamId);
3859 // Create Buffer ID map if necessary
3860 if (mBufferIdMaps.count(streamId) == 0) {
3861 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3862 }
3863 }
3864 // remove BufferIdMap for deleted streams
3865 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3866 int streamId = it->first;
3867 bool active = activeStreams.count(streamId) > 0;
3868 if (!active) {
3869 it = mBufferIdMaps.erase(it);
3870 } else {
3871 ++it;
3872 }
3873 }
3874
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003875 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003876 res = mapToStreamConfigurationMode(
3877 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003878 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003879 if (res != OK) {
3880 return res;
3881 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003882 requestedConfiguration3_2.operationMode = operationMode;
3883 requestedConfiguration3_4.operationMode = operationMode;
3884 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003885 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3886 get_camera_metadata_size(sessionParams));
3887
Emilian Peev31abd0a2017-05-11 18:37:46 +01003888 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003889 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003890 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003891
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003892 // See if we have v3.4 or v3.3 HAL
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003893 if (mHidlSession_3_4 != nullptr) {
3894 // We do; use v3.4 for the call
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003895 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003896 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003897 auto err = mHidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003898 [&status, &finalConfiguration3_4]
3899 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3900 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003901 status = s;
3902 });
3903 if (!err.isOk()) {
3904 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3905 return DEAD_OBJECT;
3906 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003907 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3908 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3909 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3910 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003911 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003912 // We do; use v3.3 for the call
3913 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003914 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003915 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003916 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003917 finalConfiguration = halConfiguration;
3918 status = s;
3919 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003920 if (!err.isOk()) {
3921 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3922 return DEAD_OBJECT;
3923 }
3924 } else {
3925 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3926 ALOGV("%s: v3.2 device found", __FUNCTION__);
3927 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003928 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003929 [&status, &finalConfiguration_3_2]
3930 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3931 finalConfiguration_3_2 = halConfiguration;
3932 status = s;
3933 });
3934 if (!err.isOk()) {
3935 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3936 return DEAD_OBJECT;
3937 }
3938 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3939 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3940 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3941 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003942 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003943 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003944 }
3945
3946 if (status != common::V1_0::Status::OK ) {
3947 return CameraProviderManager::mapToStatusT(status);
3948 }
3949
3950 // And convert output stream configuration from HIDL
3951
3952 for (size_t i = 0; i < config->num_streams; i++) {
3953 camera3_stream_t *dst = config->streams[i];
3954 int streamId = Camera3Stream::cast(dst)->getId();
3955
3956 // Start scan at i, with the assumption that the stream order matches
3957 size_t realIdx = i;
3958 bool found = false;
3959 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003960 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003961 found = true;
3962 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003963 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003964 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3965 }
3966 if (!found) {
3967 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3968 __FUNCTION__, streamId);
3969 return INVALID_OPERATION;
3970 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003971 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003972
Emilian Peev710c1422017-08-30 11:19:38 +01003973 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3974 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003975 dstStream->setDataSpaceOverride(false);
3976 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3977 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3978
Emilian Peev31abd0a2017-05-11 18:37:46 +01003979 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3980 if (dst->format != overrideFormat) {
3981 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3982 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003983 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003984 if (dst->data_space != overrideDataSpace) {
3985 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3986 streamId, dst->format);
3987 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003988 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003989 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003990 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3991
Emilian Peev31abd0a2017-05-11 18:37:46 +01003992 // Override allowed with IMPLEMENTATION_DEFINED
3993 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003994 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003995 }
3996
Emilian Peev31abd0a2017-05-11 18:37:46 +01003997 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003998 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003999 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004000 __FUNCTION__, streamId);
4001 return INVALID_OPERATION;
4002 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004003 dstStream->setUsage(
4004 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004005 } else {
4006 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004007 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004008 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4009 __FUNCTION__, streamId);
4010 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004011 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004012 dstStream->setUsage(
4013 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004014 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004015 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004016 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004017
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004018 return res;
4019}
4020
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004021void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
4022 /*out*/device::V3_2::CaptureRequest* captureRequest,
4023 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004024 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004025 if (captureRequest == nullptr || handlesCreated == nullptr) {
4026 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4027 __FUNCTION__, captureRequest, handlesCreated);
4028 return;
4029 }
4030
4031 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004032
4033 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004034
4035 {
4036 std::lock_guard<std::mutex> lock(mInflightLock);
4037 if (request->input_buffer != nullptr) {
4038 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4039 buffer_handle_t buf = *(request->input_buffer->buffer);
4040 auto pair = getBufferId(buf, streamId);
4041 bool isNewBuffer = pair.first;
4042 uint64_t bufferId = pair.second;
4043 captureRequest->inputBuffer.streamId = streamId;
4044 captureRequest->inputBuffer.bufferId = bufferId;
4045 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4046 captureRequest->inputBuffer.status = BufferStatus::OK;
4047 native_handle_t *acquireFence = nullptr;
4048 if (request->input_buffer->acquire_fence != -1) {
4049 acquireFence = native_handle_create(1,0);
4050 acquireFence->data[0] = request->input_buffer->acquire_fence;
4051 handlesCreated->push_back(acquireFence);
4052 }
4053 captureRequest->inputBuffer.acquireFence = acquireFence;
4054 captureRequest->inputBuffer.releaseFence = nullptr;
4055
4056 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4057 request->input_buffer->buffer,
4058 request->input_buffer->acquire_fence);
4059 } else {
4060 captureRequest->inputBuffer.streamId = -1;
4061 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4062 }
4063
4064 captureRequest->outputBuffers.resize(request->num_output_buffers);
4065 for (size_t i = 0; i < request->num_output_buffers; i++) {
4066 const camera3_stream_buffer_t *src = request->output_buffers + i;
4067 StreamBuffer &dst = captureRequest->outputBuffers[i];
4068 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
4069 buffer_handle_t buf = *(src->buffer);
4070 auto pair = getBufferId(buf, streamId);
4071 bool isNewBuffer = pair.first;
4072 dst.streamId = streamId;
4073 dst.bufferId = pair.second;
4074 dst.buffer = isNewBuffer ? buf : nullptr;
4075 dst.status = BufferStatus::OK;
4076 native_handle_t *acquireFence = nullptr;
4077 if (src->acquire_fence != -1) {
4078 acquireFence = native_handle_create(1,0);
4079 acquireFence->data[0] = src->acquire_fence;
4080 handlesCreated->push_back(acquireFence);
4081 }
4082 dst.acquireFence = acquireFence;
4083 dst.releaseFence = nullptr;
4084
4085 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4086 src->buffer, src->acquire_fence);
4087 }
4088 }
4089}
4090
4091status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4092 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4093 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4094 if (!valid()) return INVALID_OPERATION;
4095
Emilian Peevaebbe412018-01-15 13:53:24 +00004096 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4097 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4098 if (castResult_3_4.isOk()) {
4099 hidlSession_3_4 = castResult_3_4;
4100 }
4101
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004102 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004103 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004104 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004105 if (hidlSession_3_4 != nullptr) {
4106 captureRequests_3_4.resize(batchSize);
4107 } else {
4108 captureRequests.resize(batchSize);
4109 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004110 std::vector<native_handle_t*> handlesCreated;
4111
4112 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004113 if (hidlSession_3_4 != nullptr) {
4114 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
4115 /*out*/&handlesCreated);
4116 } else {
4117 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
4118 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004119 }
4120
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004121 std::vector<device::V3_2::BufferCache> cachesToRemove;
4122 {
4123 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4124 for (auto& pair : mFreedBuffers) {
4125 // The stream might have been removed since onBufferFreed
4126 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4127 cachesToRemove.push_back({pair.first, pair.second});
4128 }
4129 }
4130 mFreedBuffers.clear();
4131 }
4132
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004133 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4134 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004135
4136 // Write metadata to FMQ.
4137 for (size_t i = 0; i < batchSize; i++) {
4138 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004139 device::V3_2::CaptureRequest* captureRequest;
4140 if (hidlSession_3_4 != nullptr) {
4141 captureRequest = &captureRequests_3_4[i].v3_2;
4142 } else {
4143 captureRequest = &captureRequests[i];
4144 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004145
4146 if (request->settings != nullptr) {
4147 size_t settingsSize = get_camera_metadata_size(request->settings);
4148 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4149 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4150 captureRequest->settings.resize(0);
4151 captureRequest->fmqSettingsSize = settingsSize;
4152 } else {
4153 if (mRequestMetadataQueue != nullptr) {
4154 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4155 }
4156 captureRequest->settings.setToExternal(
4157 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4158 get_camera_metadata_size(request->settings));
4159 captureRequest->fmqSettingsSize = 0u;
4160 }
4161 } else {
4162 // A null request settings maps to a size-0 CameraMetadata
4163 captureRequest->settings.resize(0);
4164 captureRequest->fmqSettingsSize = 0u;
4165 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004166
4167 if (hidlSession_3_4 != nullptr) {
4168 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4169 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004170 if (request->physcam_settings != nullptr) {
4171 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4172 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4173 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4174 settingsSize)) {
4175 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4176 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4177 settingsSize;
4178 } else {
4179 if (mRequestMetadataQueue != nullptr) {
4180 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4181 }
4182 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4183 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4184 request->physcam_settings[j])),
4185 get_camera_metadata_size(request->physcam_settings[j]));
4186 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004187 }
Emilian Peev00420d22018-02-05 21:33:13 +00004188 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004189 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004190 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004191 }
4192 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4193 request->physcam_id[j];
4194 }
4195 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004196 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004197
4198 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004199 auto resultCallback =
4200 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4201 status = s;
4202 *numRequestProcessed = n;
4203 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004204 if (hidlSession_3_4 != nullptr) {
4205 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004206 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004207 } else {
4208 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004209 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004210 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004211 if (!err.isOk()) {
4212 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4213 return DEAD_OBJECT;
4214 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004215 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4216 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4217 __FUNCTION__, *numRequestProcessed, batchSize);
4218 status = common::V1_0::Status::INTERNAL_ERROR;
4219 }
4220
4221 for (auto& handle : handlesCreated) {
4222 native_handle_delete(handle);
4223 }
4224 return CameraProviderManager::mapToStatusT(status);
4225}
4226
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004227status_t Camera3Device::HalInterface::processCaptureRequest(
4228 camera3_capture_request_t *request) {
4229 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004230 if (!valid()) return INVALID_OPERATION;
4231 status_t res = OK;
4232
Emilian Peev31abd0a2017-05-11 18:37:46 +01004233 uint32_t numRequestProcessed = 0;
4234 std::vector<camera3_capture_request_t*> requests(1);
4235 requests[0] = request;
4236 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4237
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004238 return res;
4239}
4240
4241status_t Camera3Device::HalInterface::flush() {
4242 ATRACE_NAME("CameraHal::flush");
4243 if (!valid()) return INVALID_OPERATION;
4244 status_t res = OK;
4245
Emilian Peev31abd0a2017-05-11 18:37:46 +01004246 auto err = mHidlSession->flush();
4247 if (!err.isOk()) {
4248 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4249 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004250 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004251 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004252 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004253
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004254 return res;
4255}
4256
Emilian Peev31abd0a2017-05-11 18:37:46 +01004257status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004258 ATRACE_NAME("CameraHal::dump");
4259 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004260
Emilian Peev31abd0a2017-05-11 18:37:46 +01004261 // Handled by CameraProviderManager::dump
4262
4263 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004264}
4265
4266status_t Camera3Device::HalInterface::close() {
4267 ATRACE_NAME("CameraHal::close()");
4268 if (!valid()) return INVALID_OPERATION;
4269 status_t res = OK;
4270
Emilian Peev31abd0a2017-05-11 18:37:46 +01004271 auto err = mHidlSession->close();
4272 // Interface will be dead shortly anyway, so don't log errors
4273 if (!err.isOk()) {
4274 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004275 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004276
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004277 return res;
4278}
4279
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004280void Camera3Device::HalInterface::getInflightBufferKeys(
4281 std::vector<std::pair<int32_t, int32_t>>* out) {
4282 std::lock_guard<std::mutex> lock(mInflightLock);
4283 out->clear();
4284 out->reserve(mInflightBufferMap.size());
4285 for (auto& pair : mInflightBufferMap) {
4286 uint64_t key = pair.first;
4287 int32_t streamId = key & 0xFFFFFFFF;
4288 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4289 out->push_back(std::make_pair(frameNumber, streamId));
4290 }
4291 return;
4292}
4293
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004294status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004295 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004296 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004297 auto pair = std::make_pair(buffer, acquireFence);
4298 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004299 return OK;
4300}
4301
4302status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004303 int32_t frameNumber, int32_t streamId,
4304 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004305 std::lock_guard<std::mutex> lock(mInflightLock);
4306
4307 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4308 auto it = mInflightBufferMap.find(key);
4309 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004310 auto pair = it->second;
4311 *buffer = pair.first;
4312 int acquireFence = pair.second;
4313 if (acquireFence > 0) {
4314 ::close(acquireFence);
4315 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004316 mInflightBufferMap.erase(it);
4317 return OK;
4318}
4319
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004320status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4321 uint64_t bufferId, buffer_handle_t* buf) {
4322 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4323 auto pair = mRequestedBuffers.insert({bufferId, buf});
4324 if (!pair.second) {
4325 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4326 __FUNCTION__, bufferId);
4327 return BAD_VALUE;
4328 }
4329 return OK;
4330}
4331
4332// Find and pop a buffer_handle_t based on bufferId
4333status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4334 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4335 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4336 auto it = mRequestedBuffers.find(bufferId);
4337 if (it == mRequestedBuffers.end()) {
4338 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4339 __FUNCTION__, bufferId);
4340 return BAD_VALUE;
4341 }
4342 *buffer = it->second;
4343 mRequestedBuffers.erase(it);
4344 return OK;
4345}
4346
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004347std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4348 const buffer_handle_t& buf, int streamId) {
4349 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4350
4351 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4352 auto it = bIdMap.find(buf);
4353 if (it == bIdMap.end()) {
4354 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004355 ALOGV("stream %d now have %zu buffer caches, buf %p",
4356 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004357 return std::make_pair(true, mNextBufferId - 1);
4358 } else {
4359 return std::make_pair(false, it->second);
4360 }
4361}
4362
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004363void Camera3Device::HalInterface::onBufferFreed(
4364 int streamId, const native_handle_t* handle) {
4365 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4366 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4367 auto mapIt = mBufferIdMaps.find(streamId);
4368 if (mapIt == mBufferIdMaps.end()) {
4369 // streamId might be from a deleted stream here
4370 ALOGI("%s: stream %d has been removed",
4371 __FUNCTION__, streamId);
4372 return;
4373 }
4374 BufferIdMap& bIdMap = mapIt->second;
4375 auto it = bIdMap.find(handle);
4376 if (it == bIdMap.end()) {
4377 ALOGW("%s: cannot find buffer %p in stream %d",
4378 __FUNCTION__, handle, streamId);
4379 return;
4380 } else {
4381 bufferId = it->second;
4382 bIdMap.erase(it);
4383 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4384 __FUNCTION__, streamId, bIdMap.size(), handle);
4385 }
4386 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4387}
4388
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004389/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004390 * RequestThread inner class methods
4391 */
4392
4393Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004394 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004395 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4396 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004397 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004398 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004399 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004400 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004401 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004402 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004403 mReconfigured(false),
4404 mDoPause(false),
4405 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004406 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004407 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004408 mCurrentAfTriggerId(0),
4409 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004410 mRepeatingLastFrameNumber(
4411 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004412 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004413 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004414 mRequestLatency(kRequestLatencyBinSize),
4415 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004416 mLatestSessionParams(sessionParamKeys.size()),
4417 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004418 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004419}
4420
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004421Camera3Device::RequestThread::~RequestThread() {}
4422
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004423void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004424 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004425 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004426 Mutex::Autolock l(mRequestLock);
4427 mListener = listener;
4428}
4429
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004430void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4431 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004432 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004433 Mutex::Autolock l(mRequestLock);
4434 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004435 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004436 // Prepare video stream for high speed recording.
4437 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004438 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004439}
4440
Jianing Wei90e59c92014-03-12 18:29:36 -07004441status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004442 List<sp<CaptureRequest> > &requests,
4443 /*out*/
4444 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004445 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004446 Mutex::Autolock l(mRequestLock);
4447 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4448 ++it) {
4449 mRequestQueue.push_back(*it);
4450 }
4451
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004452 if (lastFrameNumber != NULL) {
4453 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4454 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4455 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4456 *lastFrameNumber);
4457 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004458
Jianing Wei90e59c92014-03-12 18:29:36 -07004459 unpauseForNewRequests();
4460
4461 return OK;
4462}
4463
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004464
4465status_t Camera3Device::RequestThread::queueTrigger(
4466 RequestTrigger trigger[],
4467 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004468 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004469 Mutex::Autolock l(mTriggerMutex);
4470 status_t ret;
4471
4472 for (size_t i = 0; i < count; ++i) {
4473 ret = queueTriggerLocked(trigger[i]);
4474
4475 if (ret != OK) {
4476 return ret;
4477 }
4478 }
4479
4480 return OK;
4481}
4482
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004483const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4484 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004485 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004486 if (d != nullptr) return d->mId;
4487 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004488}
4489
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004490status_t Camera3Device::RequestThread::queueTriggerLocked(
4491 RequestTrigger trigger) {
4492
4493 uint32_t tag = trigger.metadataTag;
4494 ssize_t index = mTriggerMap.indexOfKey(tag);
4495
4496 switch (trigger.getTagType()) {
4497 case TYPE_BYTE:
4498 // fall-through
4499 case TYPE_INT32:
4500 break;
4501 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004502 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4503 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004504 return INVALID_OPERATION;
4505 }
4506
4507 /**
4508 * Collect only the latest trigger, since we only have 1 field
4509 * in the request settings per trigger tag, and can't send more than 1
4510 * trigger per request.
4511 */
4512 if (index != NAME_NOT_FOUND) {
4513 mTriggerMap.editValueAt(index) = trigger;
4514 } else {
4515 mTriggerMap.add(tag, trigger);
4516 }
4517
4518 return OK;
4519}
4520
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004521status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004522 const RequestList &requests,
4523 /*out*/
4524 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004525 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004526 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004527 if (lastFrameNumber != NULL) {
4528 *lastFrameNumber = mRepeatingLastFrameNumber;
4529 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004530 mRepeatingRequests.clear();
4531 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4532 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004533
4534 unpauseForNewRequests();
4535
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004536 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004537 return OK;
4538}
4539
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004540bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004541 if (mRepeatingRequests.empty()) {
4542 return false;
4543 }
4544 int32_t requestId = requestIn->mResultExtras.requestId;
4545 const RequestList &repeatRequests = mRepeatingRequests;
4546 // All repeating requests are guaranteed to have same id so only check first quest
4547 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4548 return (firstRequest->mResultExtras.requestId == requestId);
4549}
4550
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004551status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004552 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004553 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004554 return clearRepeatingRequestsLocked(lastFrameNumber);
4555
4556}
4557
4558status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004559 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004560 if (lastFrameNumber != NULL) {
4561 *lastFrameNumber = mRepeatingLastFrameNumber;
4562 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004563 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004564 return OK;
4565}
4566
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004567status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004568 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004569 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004570 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004571 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004572
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004573 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004574
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004575 // Send errors for all requests pending in the request queue, including
4576 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004577 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004578 if (listener != NULL) {
4579 for (RequestList::iterator it = mRequestQueue.begin();
4580 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004581 // Abort the input buffers for reprocess requests.
4582 if ((*it)->mInputStream != NULL) {
4583 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004584 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4585 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004586 if (res != OK) {
4587 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4588 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4589 } else {
4590 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4591 if (res != OK) {
4592 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4593 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4594 }
4595 }
4596 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004597 // Set the frame number this request would have had, if it
4598 // had been submitted; this frame number will not be reused.
4599 // The requestId and burstId fields were set when the request was
4600 // submitted originally (in convertMetadataListToRequestListLocked)
4601 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004602 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004603 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004604 }
4605 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004606 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004607
4608 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004609 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004610 if (lastFrameNumber != NULL) {
4611 *lastFrameNumber = mRepeatingLastFrameNumber;
4612 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004613 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004614 return OK;
4615}
4616
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004617status_t Camera3Device::RequestThread::flush() {
4618 ATRACE_CALL();
4619 Mutex::Autolock l(mFlushLock);
4620
Emilian Peev08dd2452017-04-06 16:55:14 +01004621 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004622}
4623
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004624void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004625 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004626 Mutex::Autolock l(mPauseLock);
4627 mDoPause = paused;
4628 mDoPauseSignal.signal();
4629}
4630
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004631status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4632 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004633 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004634 Mutex::Autolock l(mLatestRequestMutex);
4635 status_t res;
4636 while (mLatestRequestId != requestId) {
4637 nsecs_t startTime = systemTime();
4638
4639 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4640 if (res != OK) return res;
4641
4642 timeout -= (systemTime() - startTime);
4643 }
4644
4645 return OK;
4646}
4647
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004648void Camera3Device::RequestThread::requestExit() {
4649 // Call parent to set up shutdown
4650 Thread::requestExit();
4651 // The exit from any possible waits
4652 mDoPauseSignal.signal();
4653 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004654
4655 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4656 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004657}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004658
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004659void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004660 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004661 bool surfaceAbandoned = false;
4662 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004663 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004664 {
4665 Mutex::Autolock l(mRequestLock);
4666 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4667 // repeating requests.
4668 for (const auto& request : mRepeatingRequests) {
4669 for (const auto& s : request->mOutputStreams) {
4670 if (s->isAbandoned()) {
4671 surfaceAbandoned = true;
4672 clearRepeatingRequestsLocked(&lastFrameNumber);
4673 break;
4674 }
4675 }
4676 if (surfaceAbandoned) {
4677 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004678 }
4679 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004680 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004681 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004682
4683 if (listener != NULL && surfaceAbandoned) {
4684 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004685 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004686}
4687
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004688bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004689 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004690 status_t res;
4691 size_t batchSize = mNextRequests.size();
4692 std::vector<camera3_capture_request_t*> requests(batchSize);
4693 uint32_t numRequestProcessed = 0;
4694 for (size_t i = 0; i < batchSize; i++) {
4695 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004696 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004697 }
4698
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004699 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4700
4701 bool triggerRemoveFailed = false;
4702 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4703 for (size_t i = 0; i < numRequestProcessed; i++) {
4704 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4705 nextRequest.submitted = true;
4706
4707
4708 // Update the latest request sent to HAL
4709 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4710 Mutex::Autolock al(mLatestRequestMutex);
4711
4712 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4713 mLatestRequest.acquire(cloned);
4714
4715 sp<Camera3Device> parent = mParent.promote();
4716 if (parent != NULL) {
4717 parent->monitorMetadata(TagMonitor::REQUEST,
4718 nextRequest.halRequest.frame_number,
4719 0, mLatestRequest);
4720 }
4721 }
4722
4723 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004724 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4725 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004726 }
4727
Emilian Peevaebbe412018-01-15 13:53:24 +00004728 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4729
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004730 if (!triggerRemoveFailed) {
4731 // Remove any previously queued triggers (after unlock)
4732 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4733 if (removeTriggerRes != OK) {
4734 triggerRemoveFailed = true;
4735 triggerFailedRequest = nextRequest;
4736 }
4737 }
4738 }
4739
4740 if (triggerRemoveFailed) {
4741 SET_ERR("RequestThread: Unable to remove triggers "
4742 "(capture request %d, HAL device: %s (%d)",
4743 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4744 cleanUpFailedRequests(/*sendRequestError*/ false);
4745 return false;
4746 }
4747
4748 if (res != OK) {
4749 // Should only get a failure here for malformed requests or device-level
4750 // errors, so consider all errors fatal. Bad metadata failures should
4751 // come through notify.
4752 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4753 mNextRequests[numRequestProcessed].halRequest.frame_number,
4754 strerror(-res), res);
4755 cleanUpFailedRequests(/*sendRequestError*/ false);
4756 return false;
4757 }
4758 return true;
4759}
4760
4761bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4762 status_t res;
4763
4764 for (auto& nextRequest : mNextRequests) {
4765 // Submit request and block until ready for next one
4766 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4767 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4768
4769 if (res != OK) {
4770 // Should only get a failure here for malformed requests or device-level
4771 // errors, so consider all errors fatal. Bad metadata failures should
4772 // come through notify.
4773 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4774 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4775 res);
4776 cleanUpFailedRequests(/*sendRequestError*/ false);
4777 return false;
4778 }
4779
4780 // Mark that the request has be submitted successfully.
4781 nextRequest.submitted = true;
4782
4783 // Update the latest request sent to HAL
4784 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4785 Mutex::Autolock al(mLatestRequestMutex);
4786
4787 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4788 mLatestRequest.acquire(cloned);
4789
4790 sp<Camera3Device> parent = mParent.promote();
4791 if (parent != NULL) {
4792 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4793 0, mLatestRequest);
4794 }
4795 }
4796
4797 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004798 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4799 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004800 }
4801
Emilian Peevaebbe412018-01-15 13:53:24 +00004802 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4803
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004804 // Remove any previously queued triggers (after unlock)
4805 res = removeTriggers(mPrevRequest);
4806 if (res != OK) {
4807 SET_ERR("RequestThread: Unable to remove triggers "
4808 "(capture request %d, HAL device: %s (%d)",
4809 nextRequest.halRequest.frame_number, strerror(-res), res);
4810 cleanUpFailedRequests(/*sendRequestError*/ false);
4811 return false;
4812 }
4813 }
4814 return true;
4815}
4816
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004817nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4818 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4819 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4820 find_camera_metadata_ro_entry(request,
4821 ANDROID_CONTROL_AE_MODE,
4822 &e);
4823 if (e.count == 0) return maxExpectedDuration;
4824
4825 switch (e.data.u8[0]) {
4826 case ANDROID_CONTROL_AE_MODE_OFF:
4827 find_camera_metadata_ro_entry(request,
4828 ANDROID_SENSOR_EXPOSURE_TIME,
4829 &e);
4830 if (e.count > 0) {
4831 maxExpectedDuration = e.data.i64[0];
4832 }
4833 find_camera_metadata_ro_entry(request,
4834 ANDROID_SENSOR_FRAME_DURATION,
4835 &e);
4836 if (e.count > 0) {
4837 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4838 }
4839 break;
4840 default:
4841 find_camera_metadata_ro_entry(request,
4842 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4843 &e);
4844 if (e.count > 1) {
4845 maxExpectedDuration = 1e9 / e.data.u8[0];
4846 }
4847 break;
4848 }
4849
4850 return maxExpectedDuration;
4851}
4852
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004853bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4854 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4855 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4856 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4857 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4858 return true;
4859 }
4860
4861 return false;
4862}
4863
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004864bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4865 ATRACE_CALL();
4866 bool updatesDetected = false;
4867
4868 for (auto tag : mSessionParamKeys) {
4869 camera_metadata_ro_entry entry = settings.find(tag);
4870 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4871
4872 if (entry.count > 0) {
4873 bool isDifferent = false;
4874 if (lastEntry.count > 0) {
4875 // Have a last value, compare to see if changed
4876 if (lastEntry.type == entry.type &&
4877 lastEntry.count == entry.count) {
4878 // Same type and count, compare values
4879 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4880 size_t entryBytes = bytesPerValue * lastEntry.count;
4881 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4882 if (cmp != 0) {
4883 isDifferent = true;
4884 }
4885 } else {
4886 // Count or type has changed
4887 isDifferent = true;
4888 }
4889 } else {
4890 // No last entry, so always consider to be different
4891 isDifferent = true;
4892 }
4893
4894 if (isDifferent) {
4895 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004896 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4897 updatesDetected = true;
4898 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004899 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004900 }
4901 } else if (lastEntry.count > 0) {
4902 // Value has been removed
4903 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4904 mLatestSessionParams.erase(tag);
4905 updatesDetected = true;
4906 }
4907 }
4908
4909 return updatesDetected;
4910}
4911
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004912bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004913 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004914 status_t res;
4915
4916 // Handle paused state.
4917 if (waitIfPaused()) {
4918 return true;
4919 }
4920
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004921 // Wait for the next batch of requests.
4922 waitForNextRequestBatch();
4923 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004924 return true;
4925 }
4926
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004927 // Get the latest request ID, if any
4928 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004929 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004930 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004931 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004932 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004933 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004934 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4935 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004936 }
4937
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004938 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4939 // or a single request from streaming or burst. In either case the first element
4940 // should contain the latest camera settings that we need to check for any session
4941 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004942 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004943 res = OK;
4944
4945 //Input stream buffers are already acquired at this point so an input stream
4946 //will not be able to move to idle state unless we force it.
4947 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4948 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4949 if (res != OK) {
4950 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4951 cleanUpFailedRequests(/*sendRequestError*/ false);
4952 return false;
4953 }
4954 }
4955
4956 if (res == OK) {
4957 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4958 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004959 sp<Camera3Device> parent = mParent.promote();
4960 if (parent != nullptr) {
4961 parent->pauseStateNotify(true);
4962 }
4963
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004964 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4965
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004966 if (parent != nullptr) {
4967 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4968 }
4969
4970 statusTracker->markComponentActive(mStatusId);
4971 setPaused(false);
4972 }
4973
4974 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4975 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4976 if (res != OK) {
4977 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4978 cleanUpFailedRequests(/*sendRequestError*/ false);
4979 return false;
4980 }
4981 }
4982 }
4983 }
4984
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004985 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004986 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004987 if (res == TIMED_OUT) {
4988 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004989 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004990 // Check if any stream is abandoned.
4991 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004992 return true;
4993 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004994 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004995 return false;
4996 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004997
Zhijun Hecc27e112013-10-03 16:12:43 -07004998 // Inform waitUntilRequestProcessed thread of a new request ID
4999 {
5000 Mutex::Autolock al(mLatestRequestMutex);
5001
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005002 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005003 mLatestRequestSignal.signal();
5004 }
5005
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005006 // Submit a batch of requests to HAL.
5007 // Use flush lock only when submitting multilple requests in a batch.
5008 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5009 // which may take a long time to finish so synchronizing flush() and
5010 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5011 // For now, only synchronize for high speed recording and we should figure something out for
5012 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005013 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005014
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005015 if (useFlushLock) {
5016 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005017 }
5018
Zhijun Hef0645c12016-08-02 00:58:11 -07005019 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005020 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005021
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005022 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005023 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005024 if (mInterface->supportBatchRequest()) {
5025 submitRequestSuccess = sendRequestsBatch();
5026 } else {
5027 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005028 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005029 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5030 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005031
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005032 if (useFlushLock) {
5033 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005034 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005035
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005036 // Unset as current request
5037 {
5038 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005039 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005040 }
5041
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005042 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005043}
5044
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005045status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005046 ATRACE_CALL();
5047
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005048 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005049 for (size_t i = 0; i < mNextRequests.size(); i++) {
5050 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005051 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5052 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5053 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5054
5055 // Prepare a request to HAL
5056 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5057
5058 // Insert any queued triggers (before metadata is locked)
5059 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005060 if (res < 0) {
5061 SET_ERR("RequestThread: Unable to insert triggers "
5062 "(capture request %d, HAL device: %s (%d)",
5063 halRequest->frame_number, strerror(-res), res);
5064 return INVALID_OPERATION;
5065 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005066
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005067 int triggerCount = res;
5068 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5069 mPrevTriggers = triggerCount;
5070
5071 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005072 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5073 // Request settings are all the same within one batch, so only treat the first
5074 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005075 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005076 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005077 /**
5078 * HAL workaround:
5079 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5080 */
5081 res = addDummyTriggerIds(captureRequest);
5082 if (res != OK) {
5083 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5084 "(capture request %d, HAL device: %s (%d)",
5085 halRequest->frame_number, strerror(-res), res);
5086 return INVALID_OPERATION;
5087 }
5088
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005089 {
5090 // Correct metadata regions for distortion correction if enabled
5091 sp<Camera3Device> parent = mParent.promote();
5092 if (parent != nullptr) {
5093 res = parent->mDistortionMapper.correctCaptureRequest(
5094 &(captureRequest->mSettingsList.begin()->metadata));
5095 if (res != OK) {
5096 SET_ERR("RequestThread: Unable to correct capture requests "
5097 "for lens distortion for request %d: %s (%d)",
5098 halRequest->frame_number, strerror(-res), res);
5099 return INVALID_OPERATION;
5100 }
5101 }
5102 }
5103
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005104 /**
5105 * The request should be presorted so accesses in HAL
5106 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5107 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005108 captureRequest->mSettingsList.begin()->metadata.sort();
5109 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005110 mPrevRequest = captureRequest;
5111 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5112
5113 IF_ALOGV() {
5114 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5115 find_camera_metadata_ro_entry(
5116 halRequest->settings,
5117 ANDROID_CONTROL_AF_TRIGGER,
5118 &e
5119 );
5120 if (e.count > 0) {
5121 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5122 __FUNCTION__,
5123 halRequest->frame_number,
5124 e.data.u8[0]);
5125 }
5126 }
5127 } else {
5128 // leave request.settings NULL to indicate 'reuse latest given'
5129 ALOGVV("%s: Request settings are REUSED",
5130 __FUNCTION__);
5131 }
5132
Emilian Peevaebbe412018-01-15 13:53:24 +00005133 if (captureRequest->mSettingsList.size() > 1) {
5134 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5135 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005136 if (newRequest) {
5137 halRequest->physcam_settings =
5138 new const camera_metadata* [halRequest->num_physcam_settings];
5139 } else {
5140 halRequest->physcam_settings = nullptr;
5141 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005142 auto it = ++captureRequest->mSettingsList.begin();
5143 size_t i = 0;
5144 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5145 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005146 if (newRequest) {
5147 it->metadata.sort();
5148 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5149 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005150 }
5151 }
5152
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005153 uint32_t totalNumBuffers = 0;
5154
5155 // Fill in buffers
5156 if (captureRequest->mInputStream != NULL) {
5157 halRequest->input_buffer = &captureRequest->mInputBuffer;
5158 totalNumBuffers += 1;
5159 } else {
5160 halRequest->input_buffer = NULL;
5161 }
5162
5163 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5164 captureRequest->mOutputStreams.size());
5165 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005166 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005167
5168 sp<Camera3Device> parent = mParent.promote();
5169 if (parent == NULL) {
5170 // Should not happen, and nowhere to send errors to, so just log it
5171 CLOGE("RequestThread: Parent is gone");
5172 return INVALID_OPERATION;
5173 }
5174 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5175
Shuzhen Wang4a472662017-02-26 23:29:04 -08005176 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
5177 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005178
5179 // Prepare video buffers for high speed recording on the first video request.
5180 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5181 // Only try to prepare video stream on the first video request.
5182 mPrepareVideoStream = false;
5183
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005184 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5185 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005186 while (res == NOT_ENOUGH_DATA) {
5187 res = outputStream->prepareNextBuffer();
5188 }
5189 if (res != OK) {
5190 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5191 __FUNCTION__, strerror(-res), res);
5192 outputStream->cancelPrepare();
5193 }
5194 }
5195
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005196 if (mUseHalBufManager) {
5197 // HAL will request buffer through requestStreamBuffer API
5198 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5199 buffer.stream = outputStream->asHalStream();
5200 buffer.buffer = nullptr;
5201 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5202 buffer.acquire_fence = -1;
5203 buffer.release_fence = -1;
5204 } else {
5205 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5206 waitDuration,
5207 captureRequest->mOutputSurfaces[outputStream->getId()]);
5208 if (res != OK) {
5209 // Can't get output buffer from gralloc queue - this could be due to
5210 // abandoned queue or other consumer misbehavior, so not a fatal
5211 // error
5212 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5213 " %s (%d)", strerror(-res), res);
5214
5215 return TIMED_OUT;
5216 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005217 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005218
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005219 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5220
5221 if (!physicalCameraId.isEmpty()) {
5222 // Physical stream isn't supported for input request.
5223 if (halRequest->input_buffer) {
5224 CLOGE("Physical stream is not supported for input request");
5225 return INVALID_OPERATION;
5226 }
5227 requestedPhysicalCameras.insert(physicalCameraId);
5228 }
5229 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005230 }
5231 totalNumBuffers += halRequest->num_output_buffers;
5232
5233 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005234 // If this request list is for constrained high speed recording (not
5235 // preview), and the current request is not the last one in the batch,
5236 // do not send callback to the app.
5237 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005238 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005239 hasCallback = false;
5240 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005241 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005242 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005243 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5244 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5245 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5246 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5247 isStillCapture = true;
5248 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5249 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005250
5251 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5252 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5253 isZslCapture = true;
5254 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005255 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005256 res = parent->registerInFlight(halRequest->frame_number,
5257 totalNumBuffers, captureRequest->mResultExtras,
5258 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005259 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005260 calculateMaxExpectedDuration(halRequest->settings),
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005261 requestedPhysicalCameras, isStillCapture, isZslCapture);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005262 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5263 ", burstId = %" PRId32 ".",
5264 __FUNCTION__,
5265 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5266 captureRequest->mResultExtras.burstId);
5267 if (res != OK) {
5268 SET_ERR("RequestThread: Unable to register new in-flight request:"
5269 " %s (%d)", strerror(-res), res);
5270 return INVALID_OPERATION;
5271 }
5272 }
5273
5274 return OK;
5275}
5276
Igor Murashkin1e479c02013-09-06 16:55:14 -07005277CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005278 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005279 Mutex::Autolock al(mLatestRequestMutex);
5280
5281 ALOGV("RequestThread::%s", __FUNCTION__);
5282
5283 return mLatestRequest;
5284}
5285
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005286bool Camera3Device::RequestThread::isStreamPending(
5287 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005288 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005289 Mutex::Autolock l(mRequestLock);
5290
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005291 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005292 if (!nextRequest.submitted) {
5293 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5294 if (stream == s) return true;
5295 }
5296 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005297 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005298 }
5299
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005300 for (const auto& request : mRequestQueue) {
5301 for (const auto& s : request->mOutputStreams) {
5302 if (stream == s) return true;
5303 }
5304 if (stream == request->mInputStream) return true;
5305 }
5306
5307 for (const auto& request : mRepeatingRequests) {
5308 for (const auto& s : request->mOutputStreams) {
5309 if (stream == s) return true;
5310 }
5311 if (stream == request->mInputStream) return true;
5312 }
5313
5314 return false;
5315}
Jianing Weicb0652e2014-03-12 18:29:36 -07005316
Emilian Peev40ead602017-09-26 15:46:36 +01005317bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5318 ATRACE_CALL();
5319 Mutex::Autolock l(mRequestLock);
5320
5321 for (const auto& nextRequest : mNextRequests) {
5322 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5323 if (s.first == streamId) {
5324 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5325 if (it != s.second.end()) {
5326 return true;
5327 }
5328 }
5329 }
5330 }
5331
5332 for (const auto& request : mRequestQueue) {
5333 for (const auto& s : request->mOutputSurfaces) {
5334 if (s.first == streamId) {
5335 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5336 if (it != s.second.end()) {
5337 return true;
5338 }
5339 }
5340 }
5341 }
5342
5343 for (const auto& request : mRepeatingRequests) {
5344 for (const auto& s : request->mOutputSurfaces) {
5345 if (s.first == streamId) {
5346 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5347 if (it != s.second.end()) {
5348 return true;
5349 }
5350 }
5351 }
5352 }
5353
5354 return false;
5355}
5356
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005357nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005358 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005359 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005360 return mExpectedInflightDuration > kMinInflightDuration ?
5361 mExpectedInflightDuration : kMinInflightDuration;
5362}
5363
Emilian Peevaebbe412018-01-15 13:53:24 +00005364void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5365 camera3_capture_request_t *halRequest) {
5366 if ((request == nullptr) || (halRequest == nullptr)) {
5367 ALOGE("%s: Invalid request!", __FUNCTION__);
5368 return;
5369 }
5370
5371 if (halRequest->num_physcam_settings > 0) {
5372 if (halRequest->physcam_id != nullptr) {
5373 delete [] halRequest->physcam_id;
5374 halRequest->physcam_id = nullptr;
5375 }
5376 if (halRequest->physcam_settings != nullptr) {
5377 auto it = ++(request->mSettingsList.begin());
5378 size_t i = 0;
5379 for (; it != request->mSettingsList.end(); it++, i++) {
5380 it->metadata.unlock(halRequest->physcam_settings[i]);
5381 }
5382 delete [] halRequest->physcam_settings;
5383 halRequest->physcam_settings = nullptr;
5384 }
5385 }
5386}
5387
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005388void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5389 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005390 return;
5391 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005392
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005393 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005394 // Skip the ones that have been submitted successfully.
5395 if (nextRequest.submitted) {
5396 continue;
5397 }
5398
5399 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5400 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5401 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5402
5403 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005404 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005405 }
5406
Emilian Peevaebbe412018-01-15 13:53:24 +00005407 cleanupPhysicalSettings(captureRequest, halRequest);
5408
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005409 if (captureRequest->mInputStream != NULL) {
5410 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5411 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5412 }
5413
5414 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005415 //Buffers that failed processing could still have
5416 //valid acquire fence.
5417 int acquireFence = (*outputBuffers)[i].acquire_fence;
5418 if (0 <= acquireFence) {
5419 close(acquireFence);
5420 outputBuffers->editItemAt(i).acquire_fence = -1;
5421 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005422 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5423 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5424 }
5425
5426 if (sendRequestError) {
5427 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005428 sp<NotificationListener> listener = mListener.promote();
5429 if (listener != NULL) {
5430 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005431 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005432 captureRequest->mResultExtras);
5433 }
5434 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005435
5436 // Remove yet-to-be submitted inflight request from inflightMap
5437 {
5438 sp<Camera3Device> parent = mParent.promote();
5439 if (parent != NULL) {
5440 Mutex::Autolock l(parent->mInFlightLock);
5441 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5442 if (idx >= 0) {
5443 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5444 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5445 parent->removeInFlightMapEntryLocked(idx);
5446 }
5447 }
5448 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005449 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005450
5451 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005452 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005453}
5454
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005455void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005456 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005457 // Optimized a bit for the simple steady-state case (single repeating
5458 // request), to avoid putting that request in the queue temporarily.
5459 Mutex::Autolock l(mRequestLock);
5460
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005461 assert(mNextRequests.empty());
5462
5463 NextRequest nextRequest;
5464 nextRequest.captureRequest = waitForNextRequestLocked();
5465 if (nextRequest.captureRequest == nullptr) {
5466 return;
5467 }
5468
5469 nextRequest.halRequest = camera3_capture_request_t();
5470 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005471 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005472
5473 // Wait for additional requests
5474 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5475
5476 for (size_t i = 1; i < batchSize; i++) {
5477 NextRequest additionalRequest;
5478 additionalRequest.captureRequest = waitForNextRequestLocked();
5479 if (additionalRequest.captureRequest == nullptr) {
5480 break;
5481 }
5482
5483 additionalRequest.halRequest = camera3_capture_request_t();
5484 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005485 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005486 }
5487
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005488 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005489 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005490 mNextRequests.size(), batchSize);
5491 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005492 }
5493
5494 return;
5495}
5496
5497sp<Camera3Device::CaptureRequest>
5498 Camera3Device::RequestThread::waitForNextRequestLocked() {
5499 status_t res;
5500 sp<CaptureRequest> nextRequest;
5501
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005502 while (mRequestQueue.empty()) {
5503 if (!mRepeatingRequests.empty()) {
5504 // Always atomically enqueue all requests in a repeating request
5505 // list. Guarantees a complete in-sequence set of captures to
5506 // application.
5507 const RequestList &requests = mRepeatingRequests;
5508 RequestList::const_iterator firstRequest =
5509 requests.begin();
5510 nextRequest = *firstRequest;
5511 mRequestQueue.insert(mRequestQueue.end(),
5512 ++firstRequest,
5513 requests.end());
5514 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005515
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005516 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005517
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005518 break;
5519 }
5520
5521 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5522
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005523 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5524 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005525 Mutex::Autolock pl(mPauseLock);
5526 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005527 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005528 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005529 // Let the tracker know
5530 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5531 if (statusTracker != 0) {
5532 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5533 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005534 }
5535 // Stop waiting for now and let thread management happen
5536 return NULL;
5537 }
5538 }
5539
5540 if (nextRequest == NULL) {
5541 // Don't have a repeating request already in hand, so queue
5542 // must have an entry now.
5543 RequestList::iterator firstRequest =
5544 mRequestQueue.begin();
5545 nextRequest = *firstRequest;
5546 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005547 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5548 sp<NotificationListener> listener = mListener.promote();
5549 if (listener != NULL) {
5550 listener->notifyRequestQueueEmpty();
5551 }
5552 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005553 }
5554
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005555 // In case we've been unpaused by setPaused clearing mDoPause, need to
5556 // update internal pause state (capture/setRepeatingRequest unpause
5557 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005558 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005559 if (mPaused) {
5560 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5561 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5562 if (statusTracker != 0) {
5563 statusTracker->markComponentActive(mStatusId);
5564 }
5565 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005566 mPaused = false;
5567
5568 // Check if we've reconfigured since last time, and reset the preview
5569 // request if so. Can't use 'NULL request == repeat' across configure calls.
5570 if (mReconfigured) {
5571 mPrevRequest.clear();
5572 mReconfigured = false;
5573 }
5574
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005575 if (nextRequest != NULL) {
5576 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005577 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5578 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005579
5580 // Since RequestThread::clear() removes buffers from the input stream,
5581 // get the right buffer here before unlocking mRequestLock
5582 if (nextRequest->mInputStream != NULL) {
5583 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5584 if (res != OK) {
5585 // Can't get input buffer from gralloc queue - this could be due to
5586 // disconnected queue or other producer misbehavior, so not a fatal
5587 // error
5588 ALOGE("%s: Can't get input buffer, skipping request:"
5589 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005590
5591 sp<NotificationListener> listener = mListener.promote();
5592 if (listener != NULL) {
5593 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005594 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005595 nextRequest->mResultExtras);
5596 }
5597 return NULL;
5598 }
5599 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005600 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005601
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005602 return nextRequest;
5603}
5604
5605bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005606 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005607 status_t res;
5608 Mutex::Autolock l(mPauseLock);
5609 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005610 if (mPaused == false) {
5611 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005612 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5613 // Let the tracker know
5614 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5615 if (statusTracker != 0) {
5616 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5617 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005618 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005619
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005620 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005621 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005622 return true;
5623 }
5624 }
5625 // We don't set mPaused to false here, because waitForNextRequest needs
5626 // to further manage the paused state in case of starvation.
5627 return false;
5628}
5629
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005630void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005631 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005632 // With work to do, mark thread as unpaused.
5633 // If paused by request (setPaused), don't resume, to avoid
5634 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005635 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005636 Mutex::Autolock p(mPauseLock);
5637 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005638 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5639 if (mPaused) {
5640 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5641 if (statusTracker != 0) {
5642 statusTracker->markComponentActive(mStatusId);
5643 }
5644 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005645 mPaused = false;
5646 }
5647}
5648
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005649void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5650 sp<Camera3Device> parent = mParent.promote();
5651 if (parent != NULL) {
5652 va_list args;
5653 va_start(args, fmt);
5654
5655 parent->setErrorStateV(fmt, args);
5656
5657 va_end(args);
5658 }
5659}
5660
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005661status_t Camera3Device::RequestThread::insertTriggers(
5662 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005663 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005664 Mutex::Autolock al(mTriggerMutex);
5665
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005666 sp<Camera3Device> parent = mParent.promote();
5667 if (parent == NULL) {
5668 CLOGE("RequestThread: Parent is gone");
5669 return DEAD_OBJECT;
5670 }
5671
Emilian Peevaebbe412018-01-15 13:53:24 +00005672 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005673 size_t count = mTriggerMap.size();
5674
5675 for (size_t i = 0; i < count; ++i) {
5676 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005677 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005678
5679 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5680 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5681 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005682 if (isAeTrigger) {
5683 request->mResultExtras.precaptureTriggerId = triggerId;
5684 mCurrentPreCaptureTriggerId = triggerId;
5685 } else {
5686 request->mResultExtras.afTriggerId = triggerId;
5687 mCurrentAfTriggerId = triggerId;
5688 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005689 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005690 }
5691
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005692 camera_metadata_entry entry = metadata.find(tag);
5693
5694 if (entry.count > 0) {
5695 /**
5696 * Already has an entry for this trigger in the request.
5697 * Rewrite it with our requested trigger value.
5698 */
5699 RequestTrigger oldTrigger = trigger;
5700
5701 oldTrigger.entryValue = entry.data.u8[0];
5702
5703 mTriggerReplacedMap.add(tag, oldTrigger);
5704 } else {
5705 /**
5706 * More typical, no trigger entry, so we just add it
5707 */
5708 mTriggerRemovedMap.add(tag, trigger);
5709 }
5710
5711 status_t res;
5712
5713 switch (trigger.getTagType()) {
5714 case TYPE_BYTE: {
5715 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5716 res = metadata.update(tag,
5717 &entryValue,
5718 /*count*/1);
5719 break;
5720 }
5721 case TYPE_INT32:
5722 res = metadata.update(tag,
5723 &trigger.entryValue,
5724 /*count*/1);
5725 break;
5726 default:
5727 ALOGE("%s: Type not supported: 0x%x",
5728 __FUNCTION__,
5729 trigger.getTagType());
5730 return INVALID_OPERATION;
5731 }
5732
5733 if (res != OK) {
5734 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5735 ", value %d", __FUNCTION__, trigger.getTagName(),
5736 trigger.entryValue);
5737 return res;
5738 }
5739
5740 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5741 trigger.getTagName(),
5742 trigger.entryValue);
5743 }
5744
5745 mTriggerMap.clear();
5746
5747 return count;
5748}
5749
5750status_t Camera3Device::RequestThread::removeTriggers(
5751 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005752 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005753 Mutex::Autolock al(mTriggerMutex);
5754
Emilian Peevaebbe412018-01-15 13:53:24 +00005755 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005756
5757 /**
5758 * Replace all old entries with their old values.
5759 */
5760 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5761 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5762
5763 status_t res;
5764
5765 uint32_t tag = trigger.metadataTag;
5766 switch (trigger.getTagType()) {
5767 case TYPE_BYTE: {
5768 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5769 res = metadata.update(tag,
5770 &entryValue,
5771 /*count*/1);
5772 break;
5773 }
5774 case TYPE_INT32:
5775 res = metadata.update(tag,
5776 &trigger.entryValue,
5777 /*count*/1);
5778 break;
5779 default:
5780 ALOGE("%s: Type not supported: 0x%x",
5781 __FUNCTION__,
5782 trigger.getTagType());
5783 return INVALID_OPERATION;
5784 }
5785
5786 if (res != OK) {
5787 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5788 ", trigger value %d", __FUNCTION__,
5789 trigger.getTagName(), trigger.entryValue);
5790 return res;
5791 }
5792 }
5793 mTriggerReplacedMap.clear();
5794
5795 /**
5796 * Remove all new entries.
5797 */
5798 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5799 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5800 status_t res = metadata.erase(trigger.metadataTag);
5801
5802 if (res != OK) {
5803 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5804 ", trigger value %d", __FUNCTION__,
5805 trigger.getTagName(), trigger.entryValue);
5806 return res;
5807 }
5808 }
5809 mTriggerRemovedMap.clear();
5810
5811 return OK;
5812}
5813
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005814status_t Camera3Device::RequestThread::addDummyTriggerIds(
5815 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005816 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005817 static const int32_t dummyTriggerId = 1;
5818 status_t res;
5819
Emilian Peevaebbe412018-01-15 13:53:24 +00005820 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005821
5822 // If AF trigger is active, insert a dummy AF trigger ID if none already
5823 // exists
5824 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5825 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5826 if (afTrigger.count > 0 &&
5827 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5828 afId.count == 0) {
5829 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5830 if (res != OK) return res;
5831 }
5832
5833 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5834 // if none already exists
5835 camera_metadata_entry pcTrigger =
5836 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5837 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5838 if (pcTrigger.count > 0 &&
5839 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5840 pcId.count == 0) {
5841 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5842 &dummyTriggerId, 1);
5843 if (res != OK) return res;
5844 }
5845
5846 return OK;
5847}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005848
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005849/**
5850 * PreparerThread inner class methods
5851 */
5852
5853Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005854 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005855 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005856}
5857
5858Camera3Device::PreparerThread::~PreparerThread() {
5859 Thread::requestExitAndWait();
5860 if (mCurrentStream != nullptr) {
5861 mCurrentStream->cancelPrepare();
5862 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5863 mCurrentStream.clear();
5864 }
5865 clear();
5866}
5867
Ruben Brunkc78ac262015-08-13 17:58:46 -07005868status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005869 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005870 status_t res;
5871
5872 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005873 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005874
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005875 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005876 if (res == OK) {
5877 // No preparation needed, fire listener right off
5878 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005879 if (listener != NULL) {
5880 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005881 }
5882 return OK;
5883 } else if (res != NOT_ENOUGH_DATA) {
5884 return res;
5885 }
5886
5887 // Need to prepare, start up thread if necessary
5888 if (!mActive) {
5889 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5890 // isn't running
5891 Thread::requestExitAndWait();
5892 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5893 if (res != OK) {
5894 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005895 if (listener != NULL) {
5896 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005897 }
5898 return res;
5899 }
5900 mCancelNow = false;
5901 mActive = true;
5902 ALOGV("%s: Preparer stream started", __FUNCTION__);
5903 }
5904
5905 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005906 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005907 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5908
5909 return OK;
5910}
5911
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005912void Camera3Device::PreparerThread::pause() {
5913 ATRACE_CALL();
5914
5915 Mutex::Autolock l(mLock);
5916
5917 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5918 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5919 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5920 int currentMaxCount = mCurrentMaxCount;
5921 mPendingStreams.clear();
5922 mCancelNow = true;
5923 while (mActive) {
5924 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5925 if (res == TIMED_OUT) {
5926 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5927 return;
5928 } else if (res != OK) {
5929 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5930 return;
5931 }
5932 }
5933
5934 //Check whether the prepare thread was able to complete the current
5935 //stream. In case work is still pending emplace it along with the rest
5936 //of the streams in the pending list.
5937 if (currentStream != nullptr) {
5938 if (!mCurrentPrepareComplete) {
5939 pendingStreams.emplace(currentMaxCount, currentStream);
5940 }
5941 }
5942
5943 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5944 for (const auto& it : mPendingStreams) {
5945 it.second->cancelPrepare();
5946 }
5947}
5948
5949status_t Camera3Device::PreparerThread::resume() {
5950 ATRACE_CALL();
5951 status_t res;
5952
5953 Mutex::Autolock l(mLock);
5954 sp<NotificationListener> listener = mListener.promote();
5955
5956 if (mActive) {
5957 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5958 return NO_INIT;
5959 }
5960
5961 auto it = mPendingStreams.begin();
5962 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005963 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005964 if (res == OK) {
5965 if (listener != NULL) {
5966 listener->notifyPrepared(it->second->getId());
5967 }
5968 it = mPendingStreams.erase(it);
5969 } else if (res != NOT_ENOUGH_DATA) {
5970 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5971 res, strerror(-res));
5972 it = mPendingStreams.erase(it);
5973 } else {
5974 it++;
5975 }
5976 }
5977
5978 if (mPendingStreams.empty()) {
5979 return OK;
5980 }
5981
5982 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5983 if (res != OK) {
5984 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5985 __FUNCTION__, res, strerror(-res));
5986 return res;
5987 }
5988 mCancelNow = false;
5989 mActive = true;
5990 ALOGV("%s: Preparer stream started", __FUNCTION__);
5991
5992 return OK;
5993}
5994
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005995status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005996 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005997 Mutex::Autolock l(mLock);
5998
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005999 for (const auto& it : mPendingStreams) {
6000 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006001 }
6002 mPendingStreams.clear();
6003 mCancelNow = true;
6004
6005 return OK;
6006}
6007
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006008void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006009 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006010 Mutex::Autolock l(mLock);
6011 mListener = listener;
6012}
6013
6014bool Camera3Device::PreparerThread::threadLoop() {
6015 status_t res;
6016 {
6017 Mutex::Autolock l(mLock);
6018 if (mCurrentStream == nullptr) {
6019 // End thread if done with work
6020 if (mPendingStreams.empty()) {
6021 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6022 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6023 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6024 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006025 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006026 return false;
6027 }
6028
6029 // Get next stream to prepare
6030 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006031 mCurrentStream = it->second;
6032 mCurrentMaxCount = it->first;
6033 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006034 mPendingStreams.erase(it);
6035 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6036 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6037 } else if (mCancelNow) {
6038 mCurrentStream->cancelPrepare();
6039 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6040 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6041 mCurrentStream.clear();
6042 mCancelNow = false;
6043 return true;
6044 }
6045 }
6046
6047 res = mCurrentStream->prepareNextBuffer();
6048 if (res == NOT_ENOUGH_DATA) return true;
6049 if (res != OK) {
6050 // Something bad happened; try to recover by cancelling prepare and
6051 // signalling listener anyway
6052 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6053 mCurrentStream->getId(), res, strerror(-res));
6054 mCurrentStream->cancelPrepare();
6055 }
6056
6057 // This stream has finished, notify listener
6058 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006059 sp<NotificationListener> listener = mListener.promote();
6060 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006061 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6062 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006063 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006064 }
6065
6066 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6067 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006068 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006069
6070 return true;
6071}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006072
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006073}; // namespace android