blob: 7d4125603885ba48edd7f0668c3931883232c999 [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;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700129 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700130 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;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -0700989 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
990 if (outputStream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700991 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 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700996
997 bufRet.streamId = streamId;
998 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
999 size_t totalHandout = outputStream->getOutstandingBuffersCount() + numBuffersRequested;
1000 if (totalHandout > outputStream->asHalStream()->max_buffers) {
1001 // Not able to allocate enough buffer. Exit early for this stream
1002 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1003 allReqsSucceeds = false;
1004 continue;
1005 }
1006
1007 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1008 bool currentReqSucceeds = true;
1009 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1010 size_t numAllocatedBuffers = 0;
1011 size_t numPushedInflightBuffers = 0;
1012 for (size_t b = 0; b < numBuffersRequested; b++) {
1013 camera3_stream_buffer_t& sb = streamBuffers[b];
1014 // Since this method can run concurrently with request thread
1015 // We need to update the wait duration everytime we call getbuffer
1016 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1017 status_t res = outputStream->getBuffer(&sb, waitDuration);
1018 if (res != OK) {
1019 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1020 __FUNCTION__, streamId, strerror(-res), res);
1021 if (res == NO_INIT || res == DEAD_OBJECT) {
1022 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1023 } else if (res == TIMED_OUT || res == NO_MEMORY) {
1024 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1025 } else {
1026 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1027 }
1028 currentReqSucceeds = false;
1029 break;
1030 }
1031 numAllocatedBuffers++;
1032
1033 buffer_handle_t *buffer = sb.buffer;
1034 auto pair = mInterface->getBufferId(*buffer, streamId);
1035 bool isNewBuffer = pair.first;
1036 uint64_t bufferId = pair.second;
1037 StreamBuffer& hBuf = tmpRetBuffers[b];
1038
1039 hBuf.streamId = streamId;
1040 hBuf.bufferId = bufferId;
1041 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1042 hBuf.status = BufferStatus::OK;
1043 hBuf.releaseFence = nullptr;
1044
1045 native_handle_t *acquireFence = nullptr;
1046 if (sb.acquire_fence != -1) {
1047 acquireFence = native_handle_create(1,0);
1048 acquireFence->data[0] = sb.acquire_fence;
1049 }
1050 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1051 hBuf.releaseFence = nullptr;
1052
1053 res = mInterface->pushInflightRequestBuffer(bufferId, buffer);
1054 if (res != OK) {
1055 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1056 __FUNCTION__, streamId, strerror(-res), res);
1057 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1058 currentReqSucceeds = false;
1059 break;
1060 }
1061 numPushedInflightBuffers++;
1062 }
1063 if (currentReqSucceeds) {
1064 bufRet.val.buffers(std::move(tmpRetBuffers));
1065 oneReqSucceeds = true;
1066 } else {
1067 allReqsSucceeds = false;
1068 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1069 StreamBuffer& hBuf = tmpRetBuffers[b];
1070 buffer_handle_t* buffer;
1071 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1072 if (res != OK) {
1073 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1074 __FUNCTION__, streamId, strerror(-res), res);
1075 }
1076 }
1077 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1078 }
1079 }
1080 // End of mOutputStreams access
1081
1082 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1083 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1084 BufferRequestStatus::FAILED_UNKNOWN,
1085 bufRets);
1086 return hardware::Void();
1087}
1088
1089hardware::Return<void> Camera3Device::returnStreamBuffers(
1090 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1091 if (!mUseHalBufManager) {
1092 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1093 __FUNCTION__, mId.string());
1094 return hardware::Void();
1095 }
1096
1097 for (const auto& buf : buffers) {
1098 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1099 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1100 continue;
1101 }
1102
1103 buffer_handle_t* buffer;
1104 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1105
1106 if (res != OK) {
1107 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1108 __FUNCTION__, buf.bufferId, buf.streamId);
1109 continue;
1110 }
1111
1112 camera3_stream_buffer_t streamBuffer;
1113 streamBuffer.buffer = buffer;
1114 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1115 streamBuffer.acquire_fence = -1;
1116 streamBuffer.release_fence = -1;
1117
1118 if (buf.releaseFence == nullptr) {
1119 streamBuffer.release_fence = -1;
1120 } else if (buf.releaseFence->numFds == 1) {
1121 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1122 } else {
1123 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1124 __FUNCTION__, buf.releaseFence->numFds);
1125 continue;
1126 }
1127
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001128 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1129 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001130 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1131 continue;
1132 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001133 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001134 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1135 }
1136 return hardware::Void();
1137}
1138
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001139hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001140 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001141 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001142 // Ideally we should grab mLock, but that can lead to deadlock, and
1143 // it's not super important to get up to date value of mStatus for this
1144 // warning print, hence skipping the lock here
1145 if (mStatus == STATUS_ERROR) {
1146 // Per API contract, HAL should act as closed after device error
1147 // But mStatus can be set to error by framework as well, so just log
1148 // a warning here.
1149 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001150 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001151
1152 if (mProcessCaptureResultLock.tryLock() != OK) {
1153 // This should never happen; it indicates a wrong client implementation
1154 // that doesn't follow the contract. But, we can be tolerant here.
1155 ALOGE("%s: callback overlapped! waiting 1s...",
1156 __FUNCTION__);
1157 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1158 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1159 __FUNCTION__);
1160 // really don't know what to do, so bail out.
1161 return hardware::Void();
1162 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001163 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001164 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001165 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001166 }
1167 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001168 return hardware::Void();
1169}
1170
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001171// Only one processCaptureResult should be called at a time, so
1172// the locks won't block. The locks are present here simply to enforce this.
1173hardware::Return<void> Camera3Device::processCaptureResult(
1174 const hardware::hidl_vec<
1175 hardware::camera::device::V3_2::CaptureResult>& results) {
1176 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1177
1178 // Ideally we should grab mLock, but that can lead to deadlock, and
1179 // it's not super important to get up to date value of mStatus for this
1180 // warning print, hence skipping the lock here
1181 if (mStatus == STATUS_ERROR) {
1182 // Per API contract, HAL should act as closed after device error
1183 // But mStatus can be set to error by framework as well, so just log
1184 // a warning here.
1185 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1186 }
1187
1188 if (mProcessCaptureResultLock.tryLock() != OK) {
1189 // This should never happen; it indicates a wrong client implementation
1190 // that doesn't follow the contract. But, we can be tolerant here.
1191 ALOGE("%s: callback overlapped! waiting 1s...",
1192 __FUNCTION__);
1193 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1194 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1195 __FUNCTION__);
1196 // really don't know what to do, so bail out.
1197 return hardware::Void();
1198 }
1199 }
1200 for (const auto& result : results) {
1201 processOneCaptureResultLocked(result, noPhysMetadata);
1202 }
1203 mProcessCaptureResultLock.unlock();
1204 return hardware::Void();
1205}
1206
1207status_t Camera3Device::readOneCameraMetadataLocked(
1208 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1209 const hardware::camera::device::V3_2::CameraMetadata& result) {
1210 if (fmqResultSize > 0) {
1211 resultMetadata.resize(fmqResultSize);
1212 if (mResultMetadataQueue == nullptr) {
1213 return NO_MEMORY; // logged in initialize()
1214 }
1215 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1216 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1217 __FUNCTION__, fmqResultSize);
1218 return INVALID_OPERATION;
1219 }
1220 } else {
1221 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1222 result.size());
1223 }
1224
1225 if (resultMetadata.size() != 0) {
1226 status_t res;
1227 const camera_metadata_t* metadata =
1228 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1229 size_t expected_metadata_size = resultMetadata.size();
1230 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1231 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1232 __FUNCTION__, strerror(-res), res);
1233 return INVALID_OPERATION;
1234 }
1235 }
1236
1237 return OK;
1238}
1239
Yifan Honga640c5a2017-04-12 16:30:31 -07001240void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001241 const hardware::camera::device::V3_2::CaptureResult& result,
1242 const hardware::hidl_vec<
1243 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001244 camera3_capture_result r;
1245 status_t res;
1246 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001247
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001248 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001249 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001250 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1251 if (res != OK) {
1252 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1253 __FUNCTION__, result.frameNumber);
1254 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001255 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001256 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001257
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001258 // Read and validate physical camera metadata
1259 size_t physResultCount = physicalCameraMetadatas.size();
1260 std::vector<const char*> physCamIds(physResultCount);
1261 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1262 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1263 physResultMetadata.resize(physResultCount);
1264 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1265 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1266 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1267 if (res != OK) {
1268 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1269 __FUNCTION__, result.frameNumber,
1270 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001271 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001272 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001273 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1274 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1275 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001276 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001277 r.num_physcam_metadata = physResultCount;
1278 r.physcam_ids = physCamIds.data();
1279 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001280
1281 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1282 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1283 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1284 auto& bDst = outputBuffers[i];
1285 const StreamBuffer &bSrc = result.outputBuffers[i];
1286
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001287 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1288 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001289 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1290 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001291 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001292 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001293 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001294
1295 buffer_handle_t *buffer;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001296 if (mUseHalBufManager) {
1297 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1298 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1299 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1300 return;
1301 }
1302 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1303 } else {
1304 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1305 }
1306
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001307 if (res != OK) {
1308 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1309 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001310 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001311 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001312
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001313 bDst.buffer = buffer;
1314 bDst.status = mapHidlBufferStatus(bSrc.status);
1315 bDst.acquire_fence = -1;
1316 if (bSrc.releaseFence == nullptr) {
1317 bDst.release_fence = -1;
1318 } else if (bSrc.releaseFence->numFds == 1) {
1319 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1320 } else {
1321 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1322 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001323 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001324 }
1325 }
1326 r.num_output_buffers = outputBuffers.size();
1327 r.output_buffers = outputBuffers.data();
1328
1329 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001330 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001331 r.input_buffer = nullptr;
1332 } else {
1333 if (mInputStream->getId() != result.inputBuffer.streamId) {
1334 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1335 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001336 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001337 }
1338 inputBuffer.stream = mInputStream->asHalStream();
1339 buffer_handle_t *buffer;
1340 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1341 &buffer);
1342 if (res != OK) {
1343 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1344 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001345 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001346 }
1347 inputBuffer.buffer = buffer;
1348 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1349 inputBuffer.acquire_fence = -1;
1350 if (result.inputBuffer.releaseFence == nullptr) {
1351 inputBuffer.release_fence = -1;
1352 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1353 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1354 } else {
1355 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1356 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001357 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001358 }
1359 r.input_buffer = &inputBuffer;
1360 }
1361
1362 r.partial_result = result.partialResult;
1363
1364 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001365}
1366
1367hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001368 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001369 // Ideally we should grab mLock, but that can lead to deadlock, and
1370 // it's not super important to get up to date value of mStatus for this
1371 // warning print, hence skipping the lock here
1372 if (mStatus == STATUS_ERROR) {
1373 // Per API contract, HAL should act as closed after device error
1374 // But mStatus can be set to error by framework as well, so just log
1375 // a warning here.
1376 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001377 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001378
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001379 for (const auto& msg : msgs) {
1380 notify(msg);
1381 }
1382 return hardware::Void();
1383}
1384
1385void Camera3Device::notify(
1386 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1387
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001388 camera3_notify_msg m;
1389 switch (msg.type) {
1390 case MsgType::ERROR:
1391 m.type = CAMERA3_MSG_ERROR;
1392 m.message.error.frame_number = msg.msg.error.frameNumber;
1393 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001394 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1395 if (stream == nullptr) {
1396 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1397 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001398 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001399 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001400 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001401 } else {
1402 m.message.error.error_stream = nullptr;
1403 }
1404 switch (msg.msg.error.errorCode) {
1405 case ErrorCode::ERROR_DEVICE:
1406 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1407 break;
1408 case ErrorCode::ERROR_REQUEST:
1409 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1410 break;
1411 case ErrorCode::ERROR_RESULT:
1412 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1413 break;
1414 case ErrorCode::ERROR_BUFFER:
1415 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1416 break;
1417 }
1418 break;
1419 case MsgType::SHUTTER:
1420 m.type = CAMERA3_MSG_SHUTTER;
1421 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1422 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1423 break;
1424 }
1425 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001426}
1427
Emilian Peevaebbe412018-01-15 13:53:24 +00001428status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001429 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001430 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001431 ATRACE_CALL();
1432
Emilian Peevaebbe412018-01-15 13:53:24 +00001433 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001434}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001435
Jianing Weicb0652e2014-03-12 18:29:36 -07001436status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1437 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001438 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001439
Emilian Peevaebbe412018-01-15 13:53:24 +00001440 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001441 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001442 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001443
Emilian Peevaebbe412018-01-15 13:53:24 +00001444 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001445 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001446}
1447
Emilian Peevaebbe412018-01-15 13:53:24 +00001448status_t Camera3Device::setStreamingRequestList(
1449 const List<const PhysicalCameraSettingsList> &requestsList,
1450 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001451 ATRACE_CALL();
1452
Emilian Peevaebbe412018-01-15 13:53:24 +00001453 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001454}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001455
1456sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001457 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001458 status_t res;
1459
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001460 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001461 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1462 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001463 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1464 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001465 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001466 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001467 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001468 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001469 } else if (mStatus == STATUS_UNCONFIGURED) {
1470 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001471 CLOGE("No streams configured");
1472 return NULL;
1473 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001474 }
1475
Shuzhen Wang0129d522016-10-30 22:43:41 -07001476 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001477 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001478}
1479
Jianing Weicb0652e2014-03-12 18:29:36 -07001480status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001481 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001482 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001483 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001484
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 switch (mStatus) {
1486 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001487 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001488 return INVALID_OPERATION;
1489 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001490 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001491 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001492 case STATUS_UNCONFIGURED:
1493 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 case STATUS_ACTIVE:
1495 // OK
1496 break;
1497 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001498 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001499 return INVALID_OPERATION;
1500 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001501 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001502
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001503 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001504}
1505
1506status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1507 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001508 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001509
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001510 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001511}
1512
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001513status_t Camera3Device::createInputStream(
1514 uint32_t width, uint32_t height, int format, int *id) {
1515 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001516 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001517 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001518 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001519 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1520 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001521
1522 status_t res;
1523 bool wasActive = false;
1524
1525 switch (mStatus) {
1526 case STATUS_ERROR:
1527 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1528 return INVALID_OPERATION;
1529 case STATUS_UNINITIALIZED:
1530 ALOGE("%s: Device not initialized", __FUNCTION__);
1531 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001532 case STATUS_UNCONFIGURED:
1533 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001534 // OK
1535 break;
1536 case STATUS_ACTIVE:
1537 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001538 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001539 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001540 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001541 return res;
1542 }
1543 wasActive = true;
1544 break;
1545 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001546 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001547 return INVALID_OPERATION;
1548 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001549 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001550
1551 if (mInputStream != 0) {
1552 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1553 return INVALID_OPERATION;
1554 }
1555
1556 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1557 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001558 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001559
1560 mInputStream = newStream;
1561
1562 *id = mNextStreamId++;
1563
1564 // Continue captures if active at start
1565 if (wasActive) {
1566 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001567 // Reuse current operating mode and session parameters for new stream config
1568 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001569 if (res != OK) {
1570 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1571 __FUNCTION__, mNextStreamId, strerror(-res), res);
1572 return res;
1573 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001574 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001575 }
1576
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001577 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001578 return OK;
1579}
1580
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001581status_t Camera3Device::StreamSet::add(
1582 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1583 if (stream == nullptr) {
1584 ALOGE("%s: cannot add null stream", __FUNCTION__);
1585 return BAD_VALUE;
1586 }
1587 std::lock_guard<std::mutex> lock(mLock);
1588 return mData.add(streamId, stream);
1589}
1590
1591ssize_t Camera3Device::StreamSet::remove(int streamId) {
1592 std::lock_guard<std::mutex> lock(mLock);
1593 return mData.removeItem(streamId);
1594}
1595
1596sp<camera3::Camera3OutputStreamInterface>
1597Camera3Device::StreamSet::get(int streamId) {
1598 std::lock_guard<std::mutex> lock(mLock);
1599 ssize_t idx = mData.indexOfKey(streamId);
1600 if (idx == NAME_NOT_FOUND) {
1601 return nullptr;
1602 }
1603 return mData.editValueAt(idx);
1604}
1605
1606sp<camera3::Camera3OutputStreamInterface>
1607Camera3Device::StreamSet::operator[] (size_t index) {
1608 std::lock_guard<std::mutex> lock(mLock);
1609 return mData.editValueAt(index);
1610}
1611
1612size_t Camera3Device::StreamSet::size() const {
1613 std::lock_guard<std::mutex> lock(mLock);
1614 return mData.size();
1615}
1616
1617void Camera3Device::StreamSet::clear() {
1618 std::lock_guard<std::mutex> lock(mLock);
1619 return mData.clear();
1620}
1621
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001622std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1623 std::lock_guard<std::mutex> lock(mLock);
1624 std::vector<int> streamIds(mData.size());
1625 for (size_t i = 0; i < mData.size(); i++) {
1626 streamIds[i] = mData.keyAt(i);
1627 }
1628 return streamIds;
1629}
1630
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001631status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001632 uint32_t width, uint32_t height, int format,
1633 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001634 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001635 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001636 ATRACE_CALL();
1637
1638 if (consumer == nullptr) {
1639 ALOGE("%s: consumer must not be null", __FUNCTION__);
1640 return BAD_VALUE;
1641 }
1642
1643 std::vector<sp<Surface>> consumers;
1644 consumers.push_back(consumer);
1645
1646 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001647 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1648 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001649}
1650
1651status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1652 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1653 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001654 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001655 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001656 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001657
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001658 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001659 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001660 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001661 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001662 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1663 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1664 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001665
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001666 status_t res;
1667 bool wasActive = false;
1668
1669 switch (mStatus) {
1670 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001671 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001672 return INVALID_OPERATION;
1673 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001674 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001675 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001676 case STATUS_UNCONFIGURED:
1677 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001678 // OK
1679 break;
1680 case STATUS_ACTIVE:
1681 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001682 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001683 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001684 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001685 return res;
1686 }
1687 wasActive = true;
1688 break;
1689 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001690 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001691 return INVALID_OPERATION;
1692 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001693 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001694
1695 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001696
Shuzhen Wang0129d522016-10-30 22:43:41 -07001697 if (consumers.size() == 0 && !hasDeferredConsumer) {
1698 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1699 return BAD_VALUE;
1700 }
Zhijun He5d677d12016-05-29 16:52:39 -07001701
Shuzhen Wang0129d522016-10-30 22:43:41 -07001702 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001703 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1704 return BAD_VALUE;
1705 }
1706
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001707 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001708 ssize_t blobBufferSize;
1709 if (dataSpace != HAL_DATASPACE_DEPTH) {
1710 blobBufferSize = getJpegBufferSize(width, height);
1711 if (blobBufferSize <= 0) {
1712 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1713 return BAD_VALUE;
1714 }
1715 } else {
1716 blobBufferSize = getPointCloudBufferSize();
1717 if (blobBufferSize <= 0) {
1718 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1719 return BAD_VALUE;
1720 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001721 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001722 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001723 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001724 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001725 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1726 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1727 if (rawOpaqueBufferSize <= 0) {
1728 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1729 return BAD_VALUE;
1730 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001731 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001732 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001733 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001734 } else if (isShared) {
1735 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1736 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001737 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001738 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001739 newStream = new Camera3OutputStream(mNextStreamId,
1740 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001741 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001742 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001743 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001744 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001745 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001746 }
Emilian Peev40ead602017-09-26 15:46:36 +01001747
1748 size_t consumerCount = consumers.size();
1749 for (size_t i = 0; i < consumerCount; i++) {
1750 int id = newStream->getSurfaceId(consumers[i]);
1751 if (id < 0) {
1752 SET_ERR_L("Invalid surface id");
1753 return BAD_VALUE;
1754 }
1755 if (surfaceIds != nullptr) {
1756 surfaceIds->push_back(id);
1757 }
1758 }
1759
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001760 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001761
Emilian Peev08dd2452017-04-06 16:55:14 +01001762 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001763
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001764 res = mOutputStreams.add(mNextStreamId, newStream);
1765 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001766 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001767 return res;
1768 }
1769
1770 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001771 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001772
1773 // Continue captures if active at start
1774 if (wasActive) {
1775 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001776 // Reuse current operating mode and session parameters for new stream config
1777 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001778 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001779 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1780 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001781 return res;
1782 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001783 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001784 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001785 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001786 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001787}
1788
Emilian Peev710c1422017-08-30 11:19:38 +01001789status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001790 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001791 if (nullptr == streamInfo) {
1792 return BAD_VALUE;
1793 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001794 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001795 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001796
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001797 switch (mStatus) {
1798 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001799 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001800 return INVALID_OPERATION;
1801 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001802 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001803 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001804 case STATUS_UNCONFIGURED:
1805 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001806 case STATUS_ACTIVE:
1807 // OK
1808 break;
1809 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001810 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001811 return INVALID_OPERATION;
1812 }
1813
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001814 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1815 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001816 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001817 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001818 }
1819
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001820 streamInfo->width = stream->getWidth();
1821 streamInfo->height = stream->getHeight();
1822 streamInfo->format = stream->getFormat();
1823 streamInfo->dataSpace = stream->getDataSpace();
1824 streamInfo->formatOverridden = stream->isFormatOverridden();
1825 streamInfo->originalFormat = stream->getOriginalFormat();
1826 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1827 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001828 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001829}
1830
1831status_t Camera3Device::setStreamTransform(int id,
1832 int transform) {
1833 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001834 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001835 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001836
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001837 switch (mStatus) {
1838 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001839 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001840 return INVALID_OPERATION;
1841 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001842 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001843 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001844 case STATUS_UNCONFIGURED:
1845 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001846 case STATUS_ACTIVE:
1847 // OK
1848 break;
1849 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001850 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001851 return INVALID_OPERATION;
1852 }
1853
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001854 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1855 if (stream == nullptr) {
1856 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001857 return BAD_VALUE;
1858 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001859 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001860}
1861
1862status_t Camera3Device::deleteStream(int id) {
1863 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001864 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001865 Mutex::Autolock l(mLock);
1866 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001867
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001868 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001869
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001870 // CameraDevice semantics require device to already be idle before
1871 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001872 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001873 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001874 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001875 }
1876
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001877 if (mStatus == STATUS_ERROR) {
1878 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1879 __FUNCTION__, mId.string());
1880 return -EBUSY;
1881 }
1882
Igor Murashkin2fba5842013-04-22 14:03:54 -07001883 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001884 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001885 if (mInputStream != NULL && id == mInputStream->getId()) {
1886 deletedStream = mInputStream;
1887 mInputStream.clear();
1888 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001889 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001890 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001891 return BAD_VALUE;
1892 }
Zhijun He5f446352014-01-22 09:49:33 -08001893 }
1894
1895 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001896 if (stream != nullptr) {
1897 deletedStream = stream;
1898 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001899 }
1900
1901 // Free up the stream endpoint so that it can be used by some other stream
1902 res = deletedStream->disconnect();
1903 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001904 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001905 // fall through since we want to still list the stream as deleted.
1906 }
1907 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001908 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001909
1910 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001911}
1912
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001913status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001914 ATRACE_CALL();
1915 ALOGV("%s: E", __FUNCTION__);
1916
1917 Mutex::Autolock il(mInterfaceLock);
1918 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001919
Emilian Peev811d2952018-05-25 11:08:40 +01001920 // In case the client doesn't include any session parameter, try a
1921 // speculative configuration using the values from the last cached
1922 // default request.
1923 if (sessionParams.isEmpty() &&
1924 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1925 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1926 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1927 mLastTemplateId);
1928 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1929 operatingMode);
1930 }
1931
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001932 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1933}
1934
1935status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1936 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001937 //Filter out any incoming session parameters
1938 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001939 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1940 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001941 CameraMetadata filteredParams(availableSessionKeys.count);
1942 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1943 filteredParams.getAndLock());
1944 set_camera_metadata_vendor_id(meta, mVendorTagId);
1945 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001946 if (availableSessionKeys.count > 0) {
1947 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1948 camera_metadata_ro_entry entry = params.find(
1949 availableSessionKeys.data.i32[i]);
1950 if (entry.count > 0) {
1951 filteredParams.update(entry);
1952 }
1953 }
1954 }
1955
1956 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001957}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001958
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001959status_t Camera3Device::getInputBufferProducer(
1960 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001961 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001962 Mutex::Autolock il(mInterfaceLock);
1963 Mutex::Autolock l(mLock);
1964
1965 if (producer == NULL) {
1966 return BAD_VALUE;
1967 } else if (mInputStream == NULL) {
1968 return INVALID_OPERATION;
1969 }
1970
1971 return mInputStream->getInputBufferProducer(producer);
1972}
1973
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001974status_t Camera3Device::createDefaultRequest(int templateId,
1975 CameraMetadata *request) {
1976 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001977 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001978
1979 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1980 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001981 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001982 return BAD_VALUE;
1983 }
1984
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001985 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001986
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001987 {
1988 Mutex::Autolock l(mLock);
1989 switch (mStatus) {
1990 case STATUS_ERROR:
1991 CLOGE("Device has encountered a serious error");
1992 return INVALID_OPERATION;
1993 case STATUS_UNINITIALIZED:
1994 CLOGE("Device is not initialized!");
1995 return INVALID_OPERATION;
1996 case STATUS_UNCONFIGURED:
1997 case STATUS_CONFIGURED:
1998 case STATUS_ACTIVE:
1999 // OK
2000 break;
2001 default:
2002 SET_ERR_L("Unexpected status: %d", mStatus);
2003 return INVALID_OPERATION;
2004 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002005
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002006 if (!mRequestTemplateCache[templateId].isEmpty()) {
2007 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002008 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002009 return OK;
2010 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002011 }
2012
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002013 camera_metadata_t *rawRequest;
2014 status_t res = mInterface->constructDefaultRequestSettings(
2015 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002016
2017 {
2018 Mutex::Autolock l(mLock);
2019 if (res == BAD_VALUE) {
2020 ALOGI("%s: template %d is not supported on this camera device",
2021 __FUNCTION__, templateId);
2022 return res;
2023 } else if (res != OK) {
2024 CLOGE("Unable to construct request template %d: %s (%d)",
2025 templateId, strerror(-res), res);
2026 return res;
2027 }
2028
2029 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2030 mRequestTemplateCache[templateId].acquire(rawRequest);
2031
2032 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002033 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002034 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002035 return OK;
2036}
2037
2038status_t Camera3Device::waitUntilDrained() {
2039 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002040 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002041 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002042 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002043
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002044 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002045}
2046
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002047status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002048 switch (mStatus) {
2049 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002050 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002051 ALOGV("%s: Already idle", __FUNCTION__);
2052 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002053 case STATUS_CONFIGURED:
2054 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002055 case STATUS_ERROR:
2056 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002057 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002058 break;
2059 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002060 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002061 return INVALID_OPERATION;
2062 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002063 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2064 maxExpectedDuration);
2065 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002066 if (res != OK) {
2067 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2068 res);
2069 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002070 return res;
2071}
2072
Ruben Brunk183f0562015-08-12 12:55:02 -07002073
2074void Camera3Device::internalUpdateStatusLocked(Status status) {
2075 mStatus = status;
2076 mRecentStatusUpdates.add(mStatus);
2077 mStatusChanged.broadcast();
2078}
2079
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002080void Camera3Device::pauseStateNotify(bool enable) {
2081 Mutex::Autolock il(mInterfaceLock);
2082 Mutex::Autolock l(mLock);
2083
2084 mPauseStateNotify = enable;
2085}
2086
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002087// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002088status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002089 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002090
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002091 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2092 maxExpectedDuration);
2093 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002094 if (res != OK) {
2095 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002096 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002097 }
2098
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002099 return res;
2100}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002101
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002102// Resume after internalPauseAndWaitLocked
2103status_t Camera3Device::internalResumeLocked() {
2104 status_t res;
2105
2106 mRequestThread->setPaused(false);
2107
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002108 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2109 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002110 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2111 if (res != OK) {
2112 SET_ERR_L("Can't transition to active in %f seconds!",
2113 kActiveTimeout/1e9);
2114 }
2115 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002116 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002117}
2118
Ruben Brunk183f0562015-08-12 12:55:02 -07002119status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002120 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002121
2122 size_t startIndex = 0;
2123 if (mStatusWaiters == 0) {
2124 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2125 // this status list
2126 mRecentStatusUpdates.clear();
2127 } else {
2128 // If other threads are waiting on updates to this status list, set the position of the
2129 // first element that this list will check rather than clearing the list.
2130 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002131 }
2132
Ruben Brunk183f0562015-08-12 12:55:02 -07002133 mStatusWaiters++;
2134
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002135 bool stateSeen = false;
2136 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002137 if (active == (mStatus == STATUS_ACTIVE)) {
2138 // Desired state is current
2139 break;
2140 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002141
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07002142 // Notify HAL to start draining
2143 if (!active && mUseHalBufManager) {
2144 auto streamIds = mOutputStreams.getStreamIds();
2145 mRequestThread->signalPipelineDrain(streamIds);
2146 }
2147
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002148 res = mStatusChanged.waitRelative(mLock, timeout);
2149 if (res != OK) break;
2150
Ruben Brunk183f0562015-08-12 12:55:02 -07002151 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2152 // transitions.
2153 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2154 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2155 __FUNCTION__);
2156
2157 // Encountered desired state since we began waiting
2158 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002159 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2160 stateSeen = true;
2161 break;
2162 }
2163 }
2164 } while (!stateSeen);
2165
Ruben Brunk183f0562015-08-12 12:55:02 -07002166 mStatusWaiters--;
2167
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002168 return res;
2169}
2170
2171
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002172status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002173 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002174 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002175
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002176 if (listener != NULL && mListener != NULL) {
2177 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2178 }
2179 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002180 mRequestThread->setNotificationListener(listener);
2181 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002182
2183 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002184}
2185
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002186bool Camera3Device::willNotify3A() {
2187 return false;
2188}
2189
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002190status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002191 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002192 status_t res;
2193 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002194
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002195 while (mResultQueue.empty()) {
2196 res = mResultSignal.waitRelative(mOutputLock, timeout);
2197 if (res == TIMED_OUT) {
2198 return res;
2199 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002200 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2201 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002202 return res;
2203 }
2204 }
2205 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002206}
2207
Jianing Weicb0652e2014-03-12 18:29:36 -07002208status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002209 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002210 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002211
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002212 if (mResultQueue.empty()) {
2213 return NOT_ENOUGH_DATA;
2214 }
2215
Jianing Weicb0652e2014-03-12 18:29:36 -07002216 if (frame == NULL) {
2217 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2218 return BAD_VALUE;
2219 }
2220
2221 CaptureResult &result = *(mResultQueue.begin());
2222 frame->mResultExtras = result.mResultExtras;
2223 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002224 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002225 mResultQueue.erase(mResultQueue.begin());
2226
2227 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002228}
2229
2230status_t Camera3Device::triggerAutofocus(uint32_t id) {
2231 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002232 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002233
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002234 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2235 // Mix-in this trigger into the next request and only the next request.
2236 RequestTrigger trigger[] = {
2237 {
2238 ANDROID_CONTROL_AF_TRIGGER,
2239 ANDROID_CONTROL_AF_TRIGGER_START
2240 },
2241 {
2242 ANDROID_CONTROL_AF_TRIGGER_ID,
2243 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002244 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002245 };
2246
2247 return mRequestThread->queueTrigger(trigger,
2248 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002249}
2250
2251status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2252 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002253 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002254
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002255 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2256 // Mix-in this trigger into the next request and only the next request.
2257 RequestTrigger trigger[] = {
2258 {
2259 ANDROID_CONTROL_AF_TRIGGER,
2260 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2261 },
2262 {
2263 ANDROID_CONTROL_AF_TRIGGER_ID,
2264 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002265 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002266 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002267
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002268 return mRequestThread->queueTrigger(trigger,
2269 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002270}
2271
2272status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2273 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002274 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002275
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002276 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2277 // Mix-in this trigger into the next request and only the next request.
2278 RequestTrigger trigger[] = {
2279 {
2280 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2281 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2282 },
2283 {
2284 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2285 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002286 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002287 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002288
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002289 return mRequestThread->queueTrigger(trigger,
2290 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002291}
2292
Jianing Weicb0652e2014-03-12 18:29:36 -07002293status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002294 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002295 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002296 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002297
Zhijun He7ef20392014-04-21 16:04:17 -07002298 {
2299 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002300
2301 // b/116514106 "disconnect()" can get called twice for the same device. The
2302 // camera device will not be initialized during the second run.
2303 if (mStatus == STATUS_UNINITIALIZED) {
2304 return OK;
2305 }
2306
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002307 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002308 }
2309
Emilian Peev08dd2452017-04-06 16:55:14 +01002310 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002311}
2312
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002313status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002314 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2315}
2316
2317status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002318 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002319 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002320 Mutex::Autolock il(mInterfaceLock);
2321 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002322
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002323 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2324 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002325 CLOGE("Stream %d does not exist", streamId);
2326 return BAD_VALUE;
2327 }
2328
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002329 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002330 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002331 return BAD_VALUE;
2332 }
2333
2334 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002335 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002336 return BAD_VALUE;
2337 }
2338
Ruben Brunkc78ac262015-08-13 17:58:46 -07002339 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002340}
2341
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002342status_t Camera3Device::tearDown(int streamId) {
2343 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002344 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002345 Mutex::Autolock il(mInterfaceLock);
2346 Mutex::Autolock l(mLock);
2347
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002348 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2349 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002350 CLOGE("Stream %d does not exist", streamId);
2351 return BAD_VALUE;
2352 }
2353
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002354 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2355 CLOGE("Stream %d is a target of a in-progress request", streamId);
2356 return BAD_VALUE;
2357 }
2358
2359 return stream->tearDown();
2360}
2361
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002362status_t Camera3Device::addBufferListenerForStream(int streamId,
2363 wp<Camera3StreamBufferListener> listener) {
2364 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002365 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002366 Mutex::Autolock il(mInterfaceLock);
2367 Mutex::Autolock l(mLock);
2368
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002369 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2370 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002371 CLOGE("Stream %d does not exist", streamId);
2372 return BAD_VALUE;
2373 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002374 stream->addBufferListener(listener);
2375
2376 return OK;
2377}
2378
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002379/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002380 * Methods called by subclasses
2381 */
2382
2383void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002384 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002385 {
2386 // Need mLock to safely update state and synchronize to current
2387 // state of methods in flight.
2388 Mutex::Autolock l(mLock);
2389 // We can get various system-idle notices from the status tracker
2390 // while starting up. Only care about them if we've actually sent
2391 // in some requests recently.
2392 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2393 return;
2394 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002395 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2396 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002397 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002398
2399 // Skip notifying listener if we're doing some user-transparent
2400 // state changes
2401 if (mPauseStateNotify) return;
2402 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002403
2404 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002405 {
2406 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002407 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002408 }
2409 if (idle && listener != NULL) {
2410 listener->notifyIdle();
2411 }
2412}
2413
Shuzhen Wang758c2152017-01-10 18:26:18 -08002414status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002415 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002416 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002417 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2418 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002419
2420 if (surfaceIds == nullptr) {
2421 return BAD_VALUE;
2422 }
2423
Zhijun He5d677d12016-05-29 16:52:39 -07002424 Mutex::Autolock il(mInterfaceLock);
2425 Mutex::Autolock l(mLock);
2426
Shuzhen Wang758c2152017-01-10 18:26:18 -08002427 if (consumers.size() == 0) {
2428 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002429 return BAD_VALUE;
2430 }
2431
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002432 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2433 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002434 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002435 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002436 }
Shuzhen Wang758c2152017-01-10 18:26:18 -08002437 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002438 if (res != OK) {
2439 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2440 return res;
2441 }
2442
Emilian Peev40ead602017-09-26 15:46:36 +01002443 for (auto &consumer : consumers) {
2444 int id = stream->getSurfaceId(consumer);
2445 if (id < 0) {
2446 CLOGE("Invalid surface id!");
2447 return BAD_VALUE;
2448 }
2449 surfaceIds->push_back(id);
2450 }
2451
Shuzhen Wang0129d522016-10-30 22:43:41 -07002452 if (stream->isConsumerConfigurationDeferred()) {
2453 if (!stream->isConfiguring()) {
2454 CLOGE("Stream %d was already fully configured.", streamId);
2455 return INVALID_OPERATION;
2456 }
Zhijun He5d677d12016-05-29 16:52:39 -07002457
Shuzhen Wang0129d522016-10-30 22:43:41 -07002458 res = stream->finishConfiguration();
2459 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002460 // If finishConfiguration fails due to abandoned surface, do not set
2461 // device to error state.
2462 bool isSurfaceAbandoned =
2463 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2464 if (!isSurfaceAbandoned) {
2465 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2466 stream->getId(), strerror(-res), res);
2467 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002468 return res;
2469 }
Zhijun He5d677d12016-05-29 16:52:39 -07002470 }
2471
2472 return OK;
2473}
2474
Emilian Peev40ead602017-09-26 15:46:36 +01002475status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2476 const std::vector<OutputStreamInfo> &outputInfo,
2477 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2478 Mutex::Autolock il(mInterfaceLock);
2479 Mutex::Autolock l(mLock);
2480
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002481 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2482 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002483 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002484 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002485 }
2486
2487 for (const auto &it : removedSurfaceIds) {
2488 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2489 CLOGE("Shared surface still part of a pending request!");
2490 return -EBUSY;
2491 }
2492 }
2493
Emilian Peev40ead602017-09-26 15:46:36 +01002494 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2495 if (res != OK) {
2496 CLOGE("Stream %d failed to update stream (error %d %s) ",
2497 streamId, res, strerror(-res));
2498 if (res == UNKNOWN_ERROR) {
2499 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2500 __FUNCTION__);
2501 }
2502 return res;
2503 }
2504
2505 return res;
2506}
2507
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002508status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2509 Mutex::Autolock il(mInterfaceLock);
2510 Mutex::Autolock l(mLock);
2511
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002512 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2513 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002514 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2515 return BAD_VALUE;
2516 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002517 return stream->dropBuffers(dropping);
2518}
2519
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002520/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002521 * Camera3Device private methods
2522 */
2523
2524sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002525 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002526 ATRACE_CALL();
2527 status_t res;
2528
2529 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002530 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002531
2532 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002533 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002534 if (inputStreams.count > 0) {
2535 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002536 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002537 CLOGE("Request references unknown input stream %d",
2538 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002539 return NULL;
2540 }
2541 // Lazy completion of stream configuration (allocation/registration)
2542 // on first use
2543 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002544 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002545 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002546 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002547 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002548 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002549 return NULL;
2550 }
2551 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002552 // Check if stream prepare is blocking requests.
2553 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002554 CLOGE("Request references an input stream that's being prepared!");
2555 return NULL;
2556 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002557
2558 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002559 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002560 }
2561
2562 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002563 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002564 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002565 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002566 return NULL;
2567 }
2568
2569 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002570 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2571 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002572 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002573 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002574 return NULL;
2575 }
Zhijun He5d677d12016-05-29 16:52:39 -07002576 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002577 auto iter = surfaceMap.find(streams.data.i32[i]);
2578 if (iter != surfaceMap.end()) {
2579 const std::vector<size_t>& surfaces = iter->second;
2580 for (const auto& surface : surfaces) {
2581 if (stream->isConsumerConfigurationDeferred(surface)) {
2582 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2583 "due to deferred consumer", stream->getId(), surface);
2584 return NULL;
2585 }
2586 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002587 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002588 }
2589
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002590 // Lazy completion of stream configuration (allocation/registration)
2591 // on first use
2592 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002593 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002594 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002595 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2596 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002597 return NULL;
2598 }
2599 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002600 // Check if stream prepare is blocking requests.
2601 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002602 CLOGE("Request references an output stream that's being prepared!");
2603 return NULL;
2604 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002605
2606 newRequest->mOutputStreams.push(stream);
2607 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002608 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002609 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002610
2611 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002612}
2613
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002614bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2615 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2616 Size size = mSupportedOpaqueInputSizes[i];
2617 if (size.width == width && size.height == height) {
2618 return true;
2619 }
2620 }
2621
2622 return false;
2623}
2624
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002625void Camera3Device::cancelStreamsConfigurationLocked() {
2626 int res = OK;
2627 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2628 res = mInputStream->cancelConfiguration();
2629 if (res != OK) {
2630 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2631 mInputStream->getId(), strerror(-res), res);
2632 }
2633 }
2634
2635 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002636 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002637 if (outputStream->isConfiguring()) {
2638 res = outputStream->cancelConfiguration();
2639 if (res != OK) {
2640 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2641 outputStream->getId(), strerror(-res), res);
2642 }
2643 }
2644 }
2645
2646 // Return state to that at start of call, so that future configures
2647 // properly clean things up
2648 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2649 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002650
2651 res = mPreparerThread->resume();
2652 if (res != OK) {
2653 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2654 }
2655}
2656
2657bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2658 ATRACE_CALL();
2659 bool ret = false;
2660
2661 Mutex::Autolock il(mInterfaceLock);
2662 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2663
2664 Mutex::Autolock l(mLock);
2665 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2666 if (rc == NO_ERROR) {
2667 mNeedConfig = true;
2668 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2669 if (rc == NO_ERROR) {
2670 ret = true;
2671 mPauseStateNotify = false;
2672 //Moving to active state while holding 'mLock' is important.
2673 //There could be pending calls to 'create-/deleteStream' which
2674 //will trigger another stream configuration while the already
2675 //present streams end up with outstanding buffers that will
2676 //not get drained.
2677 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002678 } else if (rc == DEAD_OBJECT) {
2679 // DEAD_OBJECT can be returned if either the consumer surface is
2680 // abandoned, or the HAL has died.
2681 // - If the HAL has died, configureStreamsLocked call will set
2682 // device to error state,
2683 // - If surface is abandoned, we should not set device to error
2684 // state.
2685 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002686 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002687 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002688 }
2689 } else {
2690 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2691 }
2692
2693 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002694}
2695
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002696status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002697 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002698 ATRACE_CALL();
2699 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002700
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002701 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002702 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002703 return INVALID_OPERATION;
2704 }
2705
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002706 if (operatingMode < 0) {
2707 CLOGE("Invalid operating mode: %d", operatingMode);
2708 return BAD_VALUE;
2709 }
2710
2711 bool isConstrainedHighSpeed =
2712 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2713 operatingMode;
2714
2715 if (mOperatingMode != operatingMode) {
2716 mNeedConfig = true;
2717 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2718 mOperatingMode = operatingMode;
2719 }
2720
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002721 if (!mNeedConfig) {
2722 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2723 return OK;
2724 }
2725
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002726 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2727 // adding a dummy stream instead.
2728 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2729 if (mOutputStreams.size() == 0) {
2730 addDummyStreamLocked();
2731 } else {
2732 tryRemoveDummyStreamLocked();
2733 }
2734
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002735 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002736 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002737
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002738 mPreparerThread->pause();
2739
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002740 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002741 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002742 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2743
2744 Vector<camera3_stream_t*> streams;
2745 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002746 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002747
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002748
2749 if (mInputStream != NULL) {
2750 camera3_stream_t *inputStream;
2751 inputStream = mInputStream->startConfiguration();
2752 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002753 CLOGE("Can't start input stream configuration");
2754 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002755 return INVALID_OPERATION;
2756 }
2757 streams.add(inputStream);
2758 }
2759
2760 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002761
2762 // Don't configure bidi streams twice, nor add them twice to the list
2763 if (mOutputStreams[i].get() ==
2764 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2765
2766 config.num_streams--;
2767 continue;
2768 }
2769
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002770 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002771 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002772 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002773 CLOGE("Can't start output stream configuration");
2774 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002775 return INVALID_OPERATION;
2776 }
2777 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002778
2779 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2780 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002781 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2782 // always occupy the initial entry.
2783 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002784 getJpegBufferSize(outputStream->width, outputStream->height));
2785 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002786 }
2787
2788 config.streams = streams.editArray();
2789
2790 // Do the HAL configuration; will potentially touch stream
2791 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002792
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002793 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002794 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002795 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002796
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002797 if (res == BAD_VALUE) {
2798 // HAL rejected this set of streams as unsupported, clean up config
2799 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002800 CLOGE("Set of requested inputs/outputs not supported by HAL");
2801 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002802 return BAD_VALUE;
2803 } else if (res != OK) {
2804 // Some other kind of error from configure_streams - this is not
2805 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002806 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2807 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002808 return res;
2809 }
2810
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002811 // Finish all stream configuration immediately.
2812 // TODO: Try to relax this later back to lazy completion, which should be
2813 // faster
2814
Igor Murashkin073f8572013-05-02 14:59:28 -07002815 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002816 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002817 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002818 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002819 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002820 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002821 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2822 return DEAD_OBJECT;
2823 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002824 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002825 }
2826 }
2827
2828 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002829 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002830 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002831 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002832 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002833 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002834 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002835 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002836 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2837 return DEAD_OBJECT;
2838 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002839 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002840 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002841 }
2842 }
2843
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002844 // Request thread needs to know to avoid using repeat-last-settings protocol
2845 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002846 if (notifyRequestThread) {
2847 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2848 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002849
Zhijun He90f7c372016-08-16 16:19:43 -07002850 char value[PROPERTY_VALUE_MAX];
2851 property_get("camera.fifo.disable", value, "0");
2852 int32_t disableFifo = atoi(value);
2853 if (disableFifo != 1) {
2854 // Boost priority of request thread to SCHED_FIFO.
2855 pid_t requestThreadTid = mRequestThread->getTid();
2856 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002857 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002858 if (res != OK) {
2859 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2860 strerror(-res), res);
2861 } else {
2862 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2863 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002864 }
2865
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002866 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002867 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2868 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2869 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2870 sessionParams.unlock(newSessionParams);
2871 mSessionParams.unlock(currentSessionParams);
2872 if (updateSessionParams) {
2873 mSessionParams = sessionParams;
2874 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002875
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002876 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002877
Ruben Brunk183f0562015-08-12 12:55:02 -07002878 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2879 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002880
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002881 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002882
Zhijun He0a210512014-07-24 13:45:15 -07002883 // tear down the deleted streams after configure streams.
2884 mDeletedStreams.clear();
2885
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002886 auto rc = mPreparerThread->resume();
2887 if (rc != OK) {
2888 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2889 return rc;
2890 }
2891
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002892 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002893}
2894
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002895status_t Camera3Device::addDummyStreamLocked() {
2896 ATRACE_CALL();
2897 status_t res;
2898
2899 if (mDummyStreamId != NO_STREAM) {
2900 // Should never be adding a second dummy stream when one is already
2901 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002902 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2903 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002904 return INVALID_OPERATION;
2905 }
2906
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002907 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002908
2909 sp<Camera3OutputStreamInterface> dummyStream =
2910 new Camera3DummyStream(mNextStreamId);
2911
2912 res = mOutputStreams.add(mNextStreamId, dummyStream);
2913 if (res < 0) {
2914 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2915 return res;
2916 }
2917
2918 mDummyStreamId = mNextStreamId;
2919 mNextStreamId++;
2920
2921 return OK;
2922}
2923
2924status_t Camera3Device::tryRemoveDummyStreamLocked() {
2925 ATRACE_CALL();
2926 status_t res;
2927
2928 if (mDummyStreamId == NO_STREAM) return OK;
2929 if (mOutputStreams.size() == 1) return OK;
2930
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002931 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002932
2933 // Ok, have a dummy stream and there's at least one other output stream,
2934 // so remove the dummy
2935
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002936 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2937 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002938 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2939 return INVALID_OPERATION;
2940 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002941 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002942
2943 // Free up the stream endpoint so that it can be used by some other stream
2944 res = deletedStream->disconnect();
2945 if (res != OK) {
2946 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2947 // fall through since we want to still list the stream as deleted.
2948 }
2949 mDeletedStreams.add(deletedStream);
2950 mDummyStreamId = NO_STREAM;
2951
2952 return res;
2953}
2954
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002955void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002956 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002957 Mutex::Autolock l(mLock);
2958 va_list args;
2959 va_start(args, fmt);
2960
2961 setErrorStateLockedV(fmt, args);
2962
2963 va_end(args);
2964}
2965
2966void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002967 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002968 Mutex::Autolock l(mLock);
2969 setErrorStateLockedV(fmt, args);
2970}
2971
2972void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2973 va_list args;
2974 va_start(args, fmt);
2975
2976 setErrorStateLockedV(fmt, args);
2977
2978 va_end(args);
2979}
2980
2981void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002982 // Print out all error messages to log
2983 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002984 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002985
2986 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002987 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002988
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002989 mErrorCause = errorCause;
2990
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002991 if (mRequestThread != nullptr) {
2992 mRequestThread->setPaused(true);
2993 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002994 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002995
2996 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002997 sp<NotificationListener> listener = mListener.promote();
2998 if (listener != NULL) {
2999 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003000 CaptureResultExtras());
3001 }
3002
3003 // Save stack trace. View by dumping it later.
3004 CameraTraces::saveTrace();
3005 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003006}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003007
3008/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003009 * In-flight request management
3010 */
3011
Jianing Weicb0652e2014-03-12 18:29:36 -07003012status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003013 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003014 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003015 std::set<String8>& physicalCameraIds, bool isStillCapture,
3016 bool isZslCapture) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003017 ATRACE_CALL();
3018 Mutex::Autolock l(mInFlightLock);
3019
3020 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003021 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003022 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003023 if (res < 0) return res;
3024
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003025 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003026 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3027 // avoid a deadlock during reprocess requests.
3028 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003029 if (mStatusTracker != nullptr) {
3030 mStatusTracker->markComponentActive(mInFlightStatusId);
3031 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003032 }
3033
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003034 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003035 return OK;
3036}
3037
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003038void Camera3Device::returnOutputBuffers(
3039 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003040 nsecs_t timestamp, bool timestampIncreasing) {
3041
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003042 for (size_t i = 0; i < numBuffers; i++)
3043 {
3044 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003045 status_t res = stream->returnBuffer(outputBuffers[i], timestamp, timestampIncreasing);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003046 // Note: stream may be deallocated at this point, if this buffer was
3047 // the last reference to it.
3048 if (res != OK) {
3049 ALOGE("Can't return buffer to its stream: %s (%d)",
3050 strerror(-res), res);
3051 }
3052 }
3053}
3054
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003055void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003056 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003057 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003058 mInFlightMap.removeItemsAt(idx, 1);
3059
3060 // Indicate idle inFlightMap to the status tracker
3061 if (mInFlightMap.size() == 0) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003062 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3063 // avoid a deadlock during reprocess requests.
3064 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003065 if (mStatusTracker != nullptr) {
3066 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3067 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003068 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003069 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003070}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003071
3072void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3073
3074 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3075 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3076
3077 nsecs_t sensorTimestamp = request.sensorTimestamp;
3078 nsecs_t shutterTimestamp = request.shutterTimestamp;
3079
3080 // Check if it's okay to remove the request from InFlightMap:
3081 // In the case of a successful request:
3082 // all input and output buffers, all result metadata, shutter callback
3083 // arrived.
3084 // In the case of a unsuccessful request:
3085 // all input and output buffers arrived.
3086 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003087 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003088 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003089 if (request.stillCapture) {
3090 ATRACE_ASYNC_END("still capture", frameNumber);
3091 }
3092
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003093 ATRACE_ASYNC_END("frame capture", frameNumber);
3094
Shuzhen Wang403044a2017-02-26 23:29:04 -08003095 // Sanity check - if sensor timestamp matches shutter timestamp in the
3096 // case of request having callback.
3097 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003098 sensorTimestamp != shutterTimestamp) {
3099 SET_ERR("sensor timestamp (%" PRId64
3100 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3101 sensorTimestamp, frameNumber, shutterTimestamp);
3102 }
3103
3104 // for an unsuccessful request, it may have pending output buffers to
3105 // return.
3106 assert(request.requestStatus != OK ||
3107 request.pendingOutputBuffers.size() == 0);
3108 returnOutputBuffers(request.pendingOutputBuffers.array(),
3109 request.pendingOutputBuffers.size(), 0);
3110
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003111 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003112 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3113 }
3114
3115 // Sanity check - if we have too many in-flight frames, something has
3116 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003117 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003118 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003119 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3120 kInFlightWarnLimitHighSpeed) {
3121 CLOGE("In-flight list too large for high speed configuration: %zu",
3122 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003123 }
3124}
3125
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003126void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003127 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003128 { // First return buffers cached in mInFlightMap
3129 Mutex::Autolock l(mInFlightLock);
3130 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3131 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3132 returnOutputBuffers(request.pendingOutputBuffers.array(),
3133 request.pendingOutputBuffers.size(), 0);
3134 }
3135 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003136 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003137 }
3138
3139 // Then return all inflight buffers not returned by HAL
3140 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3141 mInterface->getInflightBufferKeys(&inflightKeys);
3142
3143 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3144 for (auto& pair : inflightKeys) {
3145 int32_t frameNumber = pair.first;
3146 int32_t streamId = pair.second;
3147 buffer_handle_t* buffer;
3148 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3149 if (res != OK) {
3150 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3151 __FUNCTION__, frameNumber, streamId);
3152 continue;
3153 }
3154
3155 camera3_stream_buffer_t streamBuffer;
3156 streamBuffer.buffer = buffer;
3157 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3158 streamBuffer.acquire_fence = -1;
3159 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003160
3161 // First check if the buffer belongs to deleted stream
3162 bool streamDeleted = false;
3163 for (auto& stream : mDeletedStreams) {
3164 if (streamId == stream->getId()) {
3165 streamDeleted = true;
3166 // Return buffer to deleted stream
3167 camera3_stream* halStream = stream->asHalStream();
3168 streamBuffer.stream = halStream;
3169 switch (halStream->stream_type) {
3170 case CAMERA3_STREAM_OUTPUT:
3171 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
3172 if (res != OK) {
3173 ALOGE("%s: Can't return output buffer for frame %d to"
3174 " stream %d: %s (%d)", __FUNCTION__,
3175 frameNumber, streamId, strerror(-res), res);
3176 }
3177 break;
3178 case CAMERA3_STREAM_INPUT:
3179 res = stream->returnInputBuffer(streamBuffer);
3180 if (res != OK) {
3181 ALOGE("%s: Can't return input buffer for frame %d to"
3182 " stream %d: %s (%d)", __FUNCTION__,
3183 frameNumber, streamId, strerror(-res), res);
3184 }
3185 break;
3186 default: // Bi-direcitonal stream is deprecated
3187 ALOGE("%s: stream %d has unknown stream type %d",
3188 __FUNCTION__, streamId, halStream->stream_type);
3189 break;
3190 }
3191 break;
3192 }
3193 }
3194 if (streamDeleted) {
3195 continue;
3196 }
3197
3198 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003199 if (streamId == inputStreamId) {
3200 streamBuffer.stream = mInputStream->asHalStream();
3201 res = mInputStream->returnInputBuffer(streamBuffer);
3202 if (res != OK) {
3203 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003204 " stream %d: %s (%d)", __FUNCTION__,
3205 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003206 }
3207 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003208 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3209 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003210 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3211 continue;
3212 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003213 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003214 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3215 }
3216 }
3217}
3218
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003219void Camera3Device::insertResultLocked(CaptureResult *result,
3220 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003221 if (result == nullptr) return;
3222
Emilian Peev71c73a22017-03-21 16:35:51 +00003223 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3224 result->mMetadata.getAndLock());
3225 set_camera_metadata_vendor_id(meta, mVendorTagId);
3226 result->mMetadata.unlock(meta);
3227
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003228 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3229 (int32_t*)&frameNumber, 1) != OK) {
3230 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3231 return;
3232 }
3233
3234 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3235 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3236 return;
3237 }
3238
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003239 // Valid result, insert into queue
3240 List<CaptureResult>::iterator queuedResult =
3241 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3242 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3243 ", burstId = %" PRId32, __FUNCTION__,
3244 queuedResult->mResultExtras.requestId,
3245 queuedResult->mResultExtras.frameNumber,
3246 queuedResult->mResultExtras.burstId);
3247
3248 mResultSignal.signal();
3249}
3250
3251
3252void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003253 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003254 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003255 Mutex::Autolock l(mOutputLock);
3256
3257 CaptureResult captureResult;
3258 captureResult.mResultExtras = resultExtras;
3259 captureResult.mMetadata = partialResult;
3260
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003261 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003262}
3263
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003264
3265void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3266 CaptureResultExtras &resultExtras,
3267 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003268 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003269 bool reprocess,
3270 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003271 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003272 if (pendingMetadata.isEmpty())
3273 return;
3274
3275 Mutex::Autolock l(mOutputLock);
3276
3277 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003278 if (reprocess) {
3279 if (frameNumber < mNextReprocessResultFrameNumber) {
3280 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003281 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003282 frameNumber, mNextReprocessResultFrameNumber);
3283 return;
3284 }
3285 mNextReprocessResultFrameNumber = frameNumber + 1;
3286 } else {
3287 if (frameNumber < mNextResultFrameNumber) {
3288 SET_ERR("Out-of-order capture result metadata submitted! "
3289 "(got frame number %d, expecting %d)",
3290 frameNumber, mNextResultFrameNumber);
3291 return;
3292 }
3293 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003294 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003295
3296 CaptureResult captureResult;
3297 captureResult.mResultExtras = resultExtras;
3298 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003299 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003300
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003301 // Append any previous partials to form a complete result
3302 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3303 captureResult.mMetadata.append(collectedPartialResult);
3304 }
3305
3306 captureResult.mMetadata.sort();
3307
3308 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003309 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3310 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003311 SET_ERR("No timestamp provided by HAL for frame %d!",
3312 frameNumber);
3313 return;
3314 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003315 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3316 camera_metadata_entry timestamp =
3317 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3318 if (timestamp.count == 0) {
3319 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3320 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3321 return;
3322 }
3323 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003324
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003325 // Fix up some result metadata to account for HAL-level distortion correction
3326 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3327 if (res != OK) {
3328 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3329 frameNumber, strerror(res), res);
3330 return;
3331 }
3332
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003333 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3334 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3335
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003336 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003337}
3338
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003339/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003340 * Camera HAL device callback methods
3341 */
3342
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003343void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003344 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003345
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003346 status_t res;
3347
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003348 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003349 if (result->result == NULL && result->num_output_buffers == 0 &&
3350 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003351 SET_ERR("No result data provided by HAL for frame %d",
3352 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003353 return;
3354 }
Zhijun He204e3292014-07-14 17:09:23 -07003355
Zhijun He204e3292014-07-14 17:09:23 -07003356 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003357 result->result != NULL &&
3358 result->partial_result != 1) {
3359 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3360 " if partial result is not supported",
3361 frameNumber, result->partial_result);
3362 return;
3363 }
3364
3365 bool isPartialResult = false;
3366 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003367 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003368
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003369 // Get shutter timestamp and resultExtras from list of in-flight requests,
3370 // where it was added by the shutter notification for this frame. If the
3371 // shutter timestamp isn't received yet, append the output buffers to the
3372 // in-flight request and they will be returned when the shutter timestamp
3373 // arrives. Update the in-flight status and remove the in-flight entry if
3374 // all result data and shutter timestamp have been received.
3375 nsecs_t shutterTimestamp = 0;
3376
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003377 {
3378 Mutex::Autolock l(mInFlightLock);
3379 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3380 if (idx == NAME_NOT_FOUND) {
3381 SET_ERR("Unknown frame number for capture result: %d",
3382 frameNumber);
3383 return;
3384 }
3385 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003386 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3387 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003388 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003389 __FUNCTION__, request.resultExtras.requestId,
3390 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003391 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003392 // Always update the partial count to the latest one if it's not 0
3393 // (buffers only). When framework aggregates adjacent partial results
3394 // into one, the latest partial count will be used.
3395 if (result->partial_result != 0)
3396 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003397
3398 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003399 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003400 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3401 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3402 " the range of [1, %d] when metadata is included in the result",
3403 frameNumber, result->partial_result, mNumPartialResults);
3404 return;
3405 }
3406 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003407 if (isPartialResult && result->num_physcam_metadata) {
3408 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3409 " physical camera result", frameNumber);
3410 return;
3411 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003412 if (isPartialResult) {
3413 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003414 }
3415
Shuzhen Wang4a472662017-02-26 23:29:04 -08003416 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003417 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003418 sendPartialCaptureResult(result->result, request.resultExtras,
3419 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003420 }
3421 }
3422
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003423 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003424 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003425
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003426 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003427 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003428 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3429 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3430 request.physicalCameraIds.size(), result->num_physcam_metadata);
3431 return;
3432 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003433 if (request.haveResultMetadata) {
3434 SET_ERR("Called multiple times with metadata for frame %d",
3435 frameNumber);
3436 return;
3437 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003438 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3439 String8 physicalId(result->physcam_ids[i]);
3440 std::set<String8>::iterator cameraIdIter =
3441 request.physicalCameraIds.find(physicalId);
3442 if (cameraIdIter != request.physicalCameraIds.end()) {
3443 request.physicalCameraIds.erase(cameraIdIter);
3444 } else {
3445 SET_ERR("Total result for frame %d has already returned for camera %s",
3446 frameNumber, physicalId.c_str());
3447 return;
3448 }
3449 }
Zhijun He204e3292014-07-14 17:09:23 -07003450 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003451 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003452 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003453 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003454 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003455 request.haveResultMetadata = true;
3456 }
3457
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003458 uint32_t numBuffersReturned = result->num_output_buffers;
3459 if (result->input_buffer != NULL) {
3460 if (hasInputBufferInRequest) {
3461 numBuffersReturned += 1;
3462 } else {
3463 ALOGW("%s: Input buffer should be NULL if there is no input"
3464 " buffer sent in the request",
3465 __FUNCTION__);
3466 }
3467 }
3468 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003469 if (request.numBuffersLeft < 0) {
3470 SET_ERR("Too many buffers returned for frame %d",
3471 frameNumber);
3472 return;
3473 }
3474
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003475 camera_metadata_ro_entry_t entry;
3476 res = find_camera_metadata_ro_entry(result->result,
3477 ANDROID_SENSOR_TIMESTAMP, &entry);
3478 if (res == OK && entry.count == 1) {
3479 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003480 }
3481
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003482 // If shutter event isn't received yet, append the output buffers to
3483 // the in-flight request. Otherwise, return the output buffers to
3484 // streams.
3485 if (shutterTimestamp == 0) {
3486 request.pendingOutputBuffers.appendArray(result->output_buffers,
3487 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003488 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003489 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003490 returnOutputBuffers(result->output_buffers,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003491 result->num_output_buffers, shutterTimestamp, timestampIncreasing);
Igor Murashkind2c90692013-04-02 12:32:32 -07003492 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003493
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003494 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003495 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3496 CameraMetadata physicalMetadata;
3497 physicalMetadata.append(result->physcam_metadata[i]);
3498 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3499 physicalMetadata});
3500 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003501 if (shutterTimestamp == 0) {
3502 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003503 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003504 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003505 CameraMetadata metadata;
3506 metadata = result->result;
3507 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003508 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003509 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003510 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003511 }
3512
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003513 removeInFlightRequestIfReadyLocked(idx);
3514 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003515
Zhijun Hef0d962a2014-06-30 10:24:11 -07003516 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003517 if (hasInputBufferInRequest) {
3518 Camera3Stream *stream =
3519 Camera3Stream::cast(result->input_buffer->stream);
3520 res = stream->returnInputBuffer(*(result->input_buffer));
3521 // Note: stream may be deallocated at this point, if this buffer was the
3522 // last reference to it.
3523 if (res != OK) {
3524 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3525 " its stream:%s (%d)", __FUNCTION__,
3526 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003527 }
3528 } else {
3529 ALOGW("%s: Input buffer should be NULL if there is no input"
3530 " buffer sent in the request, skipping input buffer return.",
3531 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003532 }
3533 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003534}
3535
3536void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003537 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003538 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003539 {
3540 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003541 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003542 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003543
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003544 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003545 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003546 return;
3547 }
3548
3549 switch (msg->type) {
3550 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003551 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003552 break;
3553 }
3554 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003555 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003556 break;
3557 }
3558 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003559 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003560 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003561 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003562}
3563
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003564void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003565 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003566 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003567 // Map camera HAL error codes to ICameraDeviceCallback error codes
3568 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003569 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003570 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003571 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003572 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003573 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003574 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003575 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003576 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003577 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003578 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003579 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003580 };
3581
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003582 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003583 ((msg.error_code >= 0) &&
3584 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3585 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003586 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003587
3588 int streamId = 0;
3589 if (msg.error_stream != NULL) {
3590 Camera3Stream *stream =
3591 Camera3Stream::cast(msg.error_stream);
3592 streamId = stream->getId();
3593 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003594 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3595 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003596 streamId, msg.error_code);
3597
3598 CaptureResultExtras resultExtras;
3599 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003600 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003601 // SET_ERR calls notifyError
3602 SET_ERR("Camera HAL reported serious device error");
3603 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003604 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3605 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3606 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003607 {
3608 Mutex::Autolock l(mInFlightLock);
3609 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3610 if (idx >= 0) {
3611 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3612 r.requestStatus = msg.error_code;
3613 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003614 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3615 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3616 errorCode) {
3617 r.skipResultMetadata = true;
3618 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003619 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3620 errorCode) {
3621 // In case of missing result check whether the buffers
3622 // returned. If they returned, then remove inflight
3623 // request.
3624 removeInFlightRequestIfReadyLocked(idx);
3625 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003626 } else {
3627 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003628 ALOGE("Camera %s: %s: cannot find in-flight request on "
3629 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003630 resultExtras.frameNumber);
3631 }
3632 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003633 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003634 if (listener != NULL) {
3635 listener->notifyError(errorCode, resultExtras);
3636 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003637 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003638 }
3639 break;
3640 default:
3641 // SET_ERR calls notifyError
3642 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3643 break;
3644 }
3645}
3646
3647void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003648 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003649 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003650 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003651
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003652 // Set timestamp for the request in the in-flight tracking
3653 // and get the request ID to send upstream
3654 {
3655 Mutex::Autolock l(mInFlightLock);
3656 idx = mInFlightMap.indexOfKey(msg.frame_number);
3657 if (idx >= 0) {
3658 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003659
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003660 // Verify ordering of shutter notifications
3661 {
3662 Mutex::Autolock l(mOutputLock);
3663 // TODO: need to track errors for tighter bounds on expected frame number.
3664 if (r.hasInputBuffer) {
3665 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3666 SET_ERR("Shutter notification out-of-order. Expected "
3667 "notification for frame %d, got frame %d",
3668 mNextReprocessShutterFrameNumber, msg.frame_number);
3669 return;
3670 }
3671 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3672 } else {
3673 if (msg.frame_number < mNextShutterFrameNumber) {
3674 SET_ERR("Shutter notification out-of-order. Expected "
3675 "notification for frame %d, got frame %d",
3676 mNextShutterFrameNumber, msg.frame_number);
3677 return;
3678 }
3679 mNextShutterFrameNumber = msg.frame_number + 1;
3680 }
3681 }
3682
Shuzhen Wang4a472662017-02-26 23:29:04 -08003683 r.shutterTimestamp = msg.timestamp;
3684 if (r.hasCallback) {
3685 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003686 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003687 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003688 // Call listener, if any
3689 if (listener != NULL) {
3690 listener->notifyShutter(r.resultExtras, msg.timestamp);
3691 }
3692 // send pending result and buffers
3693 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3694 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003695 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003696 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003697 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003698 returnOutputBuffers(r.pendingOutputBuffers.array(),
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003699 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003700 r.pendingOutputBuffers.clear();
3701
3702 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003703 }
3704 }
3705 if (idx < 0) {
3706 SET_ERR("Shutter notification for non-existent frame number %d",
3707 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003708 }
3709}
3710
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003711CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003712 ALOGV("%s", __FUNCTION__);
3713
Igor Murashkin1e479c02013-09-06 16:55:14 -07003714 CameraMetadata retVal;
3715
3716 if (mRequestThread != NULL) {
3717 retVal = mRequestThread->getLatestRequest();
3718 }
3719
Igor Murashkin1e479c02013-09-06 16:55:14 -07003720 return retVal;
3721}
3722
Jianing Weicb0652e2014-03-12 18:29:36 -07003723
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003724void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3725 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3726 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3727}
3728
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003729/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003730 * HalInterface inner class methods
3731 */
3732
Yifan Hongf79b5542017-04-11 14:44:25 -07003733Camera3Device::HalInterface::HalInterface(
3734 sp<ICameraDeviceSession> &session,
3735 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003736 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003737 mRequestMetadataQueue(queue) {
3738 // Check with hardware service manager if we can downcast these interfaces
3739 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003740 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3741 if (castResult_3_5.isOk()) {
3742 mHidlSession_3_5 = castResult_3_5;
3743 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003744 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3745 if (castResult_3_4.isOk()) {
3746 mHidlSession_3_4 = castResult_3_4;
3747 }
3748 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3749 if (castResult_3_3.isOk()) {
3750 mHidlSession_3_3 = castResult_3_3;
3751 }
3752}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003753
Emilian Peev31abd0a2017-05-11 18:37:46 +01003754Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003755
3756Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003757 mHidlSession(other.mHidlSession),
3758 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003759
3760bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003761 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003762}
3763
3764void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003765 mHidlSession_3_4.clear();
3766 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003767 mHidlSession.clear();
3768}
3769
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003770bool Camera3Device::HalInterface::supportBatchRequest() {
3771 return mHidlSession != nullptr;
3772}
3773
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003774status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3775 camera3_request_template_t templateId,
3776 /*out*/ camera_metadata_t **requestTemplate) {
3777 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3778 if (!valid()) return INVALID_OPERATION;
3779 status_t res = OK;
3780
Emilian Peev31abd0a2017-05-11 18:37:46 +01003781 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003782
3783 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003784 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003785 status = s;
3786 if (status == common::V1_0::Status::OK) {
3787 const camera_metadata *r =
3788 reinterpret_cast<const camera_metadata_t*>(request.data());
3789 size_t expectedSize = request.size();
3790 int ret = validate_camera_metadata_structure(r, &expectedSize);
3791 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3792 *requestTemplate = clone_camera_metadata(r);
3793 if (*requestTemplate == nullptr) {
3794 ALOGE("%s: Unable to clone camera metadata received from HAL",
3795 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003796 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003797 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003798 } else {
3799 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3800 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003801 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003802 }
3803 };
3804 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003805 RequestTemplate id;
3806 switch (templateId) {
3807 case CAMERA3_TEMPLATE_PREVIEW:
3808 id = RequestTemplate::PREVIEW;
3809 break;
3810 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3811 id = RequestTemplate::STILL_CAPTURE;
3812 break;
3813 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3814 id = RequestTemplate::VIDEO_RECORD;
3815 break;
3816 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3817 id = RequestTemplate::VIDEO_SNAPSHOT;
3818 break;
3819 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3820 id = RequestTemplate::ZERO_SHUTTER_LAG;
3821 break;
3822 case CAMERA3_TEMPLATE_MANUAL:
3823 id = RequestTemplate::MANUAL;
3824 break;
3825 default:
3826 // Unknown template ID, or this HAL is too old to support it
3827 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003828 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003829 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003830
Emilian Peev31abd0a2017-05-11 18:37:46 +01003831 if (!err.isOk()) {
3832 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3833 res = DEAD_OBJECT;
3834 } else {
3835 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003836 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003837
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003838 return res;
3839}
3840
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003841status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003842 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003843 ATRACE_NAME("CameraHal::configureStreams");
3844 if (!valid()) return INVALID_OPERATION;
3845 status_t res = OK;
3846
Emilian Peev31abd0a2017-05-11 18:37:46 +01003847 // Convert stream config to HIDL
3848 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003849 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3850 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3851 requestedConfiguration3_2.streams.resize(config->num_streams);
3852 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003853 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003854 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3855 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003856 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003857
Emilian Peev31abd0a2017-05-11 18:37:46 +01003858 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3859 cam3stream->setBufferFreedListener(this);
3860 int streamId = cam3stream->getId();
3861 StreamType streamType;
3862 switch (src->stream_type) {
3863 case CAMERA3_STREAM_OUTPUT:
3864 streamType = StreamType::OUTPUT;
3865 break;
3866 case CAMERA3_STREAM_INPUT:
3867 streamType = StreamType::INPUT;
3868 break;
3869 default:
3870 ALOGE("%s: Stream %d: Unsupported stream type %d",
3871 __FUNCTION__, streamId, config->streams[i]->stream_type);
3872 return BAD_VALUE;
3873 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003874 dst3_2.id = streamId;
3875 dst3_2.streamType = streamType;
3876 dst3_2.width = src->width;
3877 dst3_2.height = src->height;
3878 dst3_2.format = mapToPixelFormat(src->format);
3879 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3880 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3881 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3882 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003883 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003884 if (src->physical_camera_id != nullptr) {
3885 dst3_4.physicalCameraId = src->physical_camera_id;
3886 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003887
3888 activeStreams.insert(streamId);
3889 // Create Buffer ID map if necessary
3890 if (mBufferIdMaps.count(streamId) == 0) {
3891 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3892 }
3893 }
3894 // remove BufferIdMap for deleted streams
3895 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3896 int streamId = it->first;
3897 bool active = activeStreams.count(streamId) > 0;
3898 if (!active) {
3899 it = mBufferIdMaps.erase(it);
3900 } else {
3901 ++it;
3902 }
3903 }
3904
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003905 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003906 res = mapToStreamConfigurationMode(
3907 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003908 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003909 if (res != OK) {
3910 return res;
3911 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003912 requestedConfiguration3_2.operationMode = operationMode;
3913 requestedConfiguration3_4.operationMode = operationMode;
3914 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003915 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3916 get_camera_metadata_size(sessionParams));
3917
Emilian Peev31abd0a2017-05-11 18:37:46 +01003918 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003919 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003920 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003921 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003922
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003923 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003924 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3925 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003926 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003927 };
3928
3929 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3930 (hardware::Return<void>& err) -> status_t {
3931 if (!err.isOk()) {
3932 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3933 return DEAD_OBJECT;
3934 }
3935 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3936 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3937 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3938 }
3939 return OK;
3940 };
3941
3942 // See if we have v3.4 or v3.3 HAL
3943 if (mHidlSession_3_5 != nullptr) {
3944 ALOGV("%s: v3.5 device found", __FUNCTION__);
3945 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3946 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3947 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3948 auto err = mHidlSession_3_5->configureStreams_3_5(
3949 requestedConfiguration3_5, configStream34Cb);
3950 res = postprocConfigStream34(err);
3951 if (res != OK) {
3952 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003953 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003954 } else if (mHidlSession_3_4 != nullptr) {
3955 // We do; use v3.4 for the call
3956 ALOGV("%s: v3.4 device found", __FUNCTION__);
3957 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
3958 auto err = mHidlSession_3_4->configureStreams_3_4(
3959 requestedConfiguration3_4, configStream34Cb);
3960 res = postprocConfigStream34(err);
3961 if (res != OK) {
3962 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003963 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003964 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003965 // We do; use v3.3 for the call
3966 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003967 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003968 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003969 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003970 finalConfiguration = halConfiguration;
3971 status = s;
3972 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003973 if (!err.isOk()) {
3974 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3975 return DEAD_OBJECT;
3976 }
3977 } else {
3978 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3979 ALOGV("%s: v3.2 device found", __FUNCTION__);
3980 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003981 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003982 [&status, &finalConfiguration_3_2]
3983 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3984 finalConfiguration_3_2 = halConfiguration;
3985 status = s;
3986 });
3987 if (!err.isOk()) {
3988 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3989 return DEAD_OBJECT;
3990 }
3991 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3992 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3993 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3994 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003995 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003996 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003997 }
3998
3999 if (status != common::V1_0::Status::OK ) {
4000 return CameraProviderManager::mapToStatusT(status);
4001 }
4002
4003 // And convert output stream configuration from HIDL
4004
4005 for (size_t i = 0; i < config->num_streams; i++) {
4006 camera3_stream_t *dst = config->streams[i];
4007 int streamId = Camera3Stream::cast(dst)->getId();
4008
4009 // Start scan at i, with the assumption that the stream order matches
4010 size_t realIdx = i;
4011 bool found = false;
4012 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004013 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004014 found = true;
4015 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004016 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004017 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4018 }
4019 if (!found) {
4020 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4021 __FUNCTION__, streamId);
4022 return INVALID_OPERATION;
4023 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004024 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004025
Emilian Peev710c1422017-08-30 11:19:38 +01004026 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4027 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004028 dstStream->setDataSpaceOverride(false);
4029 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4030 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4031
Emilian Peev31abd0a2017-05-11 18:37:46 +01004032 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4033 if (dst->format != overrideFormat) {
4034 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4035 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004036 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004037 if (dst->data_space != overrideDataSpace) {
4038 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4039 streamId, dst->format);
4040 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004041 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004042 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004043 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4044
Emilian Peev31abd0a2017-05-11 18:37:46 +01004045 // Override allowed with IMPLEMENTATION_DEFINED
4046 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004047 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004048 }
4049
Emilian Peev31abd0a2017-05-11 18:37:46 +01004050 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004051 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004052 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004053 __FUNCTION__, streamId);
4054 return INVALID_OPERATION;
4055 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004056 dstStream->setUsage(
4057 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004058 } else {
4059 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004060 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004061 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4062 __FUNCTION__, streamId);
4063 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004064 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004065 dstStream->setUsage(
4066 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004067 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004068 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004069 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004070
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004071 return res;
4072}
4073
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004074void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
4075 /*out*/device::V3_2::CaptureRequest* captureRequest,
4076 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004077 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004078 if (captureRequest == nullptr || handlesCreated == nullptr) {
4079 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4080 __FUNCTION__, captureRequest, handlesCreated);
4081 return;
4082 }
4083
4084 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004085
4086 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004087
4088 {
4089 std::lock_guard<std::mutex> lock(mInflightLock);
4090 if (request->input_buffer != nullptr) {
4091 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4092 buffer_handle_t buf = *(request->input_buffer->buffer);
4093 auto pair = getBufferId(buf, streamId);
4094 bool isNewBuffer = pair.first;
4095 uint64_t bufferId = pair.second;
4096 captureRequest->inputBuffer.streamId = streamId;
4097 captureRequest->inputBuffer.bufferId = bufferId;
4098 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4099 captureRequest->inputBuffer.status = BufferStatus::OK;
4100 native_handle_t *acquireFence = nullptr;
4101 if (request->input_buffer->acquire_fence != -1) {
4102 acquireFence = native_handle_create(1,0);
4103 acquireFence->data[0] = request->input_buffer->acquire_fence;
4104 handlesCreated->push_back(acquireFence);
4105 }
4106 captureRequest->inputBuffer.acquireFence = acquireFence;
4107 captureRequest->inputBuffer.releaseFence = nullptr;
4108
4109 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4110 request->input_buffer->buffer,
4111 request->input_buffer->acquire_fence);
4112 } else {
4113 captureRequest->inputBuffer.streamId = -1;
4114 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4115 }
4116
4117 captureRequest->outputBuffers.resize(request->num_output_buffers);
4118 for (size_t i = 0; i < request->num_output_buffers; i++) {
4119 const camera3_stream_buffer_t *src = request->output_buffers + i;
4120 StreamBuffer &dst = captureRequest->outputBuffers[i];
4121 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
4122 buffer_handle_t buf = *(src->buffer);
4123 auto pair = getBufferId(buf, streamId);
4124 bool isNewBuffer = pair.first;
4125 dst.streamId = streamId;
4126 dst.bufferId = pair.second;
4127 dst.buffer = isNewBuffer ? buf : nullptr;
4128 dst.status = BufferStatus::OK;
4129 native_handle_t *acquireFence = nullptr;
4130 if (src->acquire_fence != -1) {
4131 acquireFence = native_handle_create(1,0);
4132 acquireFence->data[0] = src->acquire_fence;
4133 handlesCreated->push_back(acquireFence);
4134 }
4135 dst.acquireFence = acquireFence;
4136 dst.releaseFence = nullptr;
4137
4138 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4139 src->buffer, src->acquire_fence);
4140 }
4141 }
4142}
4143
4144status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4145 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4146 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4147 if (!valid()) return INVALID_OPERATION;
4148
Emilian Peevaebbe412018-01-15 13:53:24 +00004149 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4150 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4151 if (castResult_3_4.isOk()) {
4152 hidlSession_3_4 = castResult_3_4;
4153 }
4154
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004155 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004156 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004157 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004158 if (hidlSession_3_4 != nullptr) {
4159 captureRequests_3_4.resize(batchSize);
4160 } else {
4161 captureRequests.resize(batchSize);
4162 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004163 std::vector<native_handle_t*> handlesCreated;
4164
4165 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004166 if (hidlSession_3_4 != nullptr) {
4167 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
4168 /*out*/&handlesCreated);
4169 } else {
4170 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
4171 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004172 }
4173
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004174 std::vector<device::V3_2::BufferCache> cachesToRemove;
4175 {
4176 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4177 for (auto& pair : mFreedBuffers) {
4178 // The stream might have been removed since onBufferFreed
4179 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4180 cachesToRemove.push_back({pair.first, pair.second});
4181 }
4182 }
4183 mFreedBuffers.clear();
4184 }
4185
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004186 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4187 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004188
4189 // Write metadata to FMQ.
4190 for (size_t i = 0; i < batchSize; i++) {
4191 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004192 device::V3_2::CaptureRequest* captureRequest;
4193 if (hidlSession_3_4 != nullptr) {
4194 captureRequest = &captureRequests_3_4[i].v3_2;
4195 } else {
4196 captureRequest = &captureRequests[i];
4197 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004198
4199 if (request->settings != nullptr) {
4200 size_t settingsSize = get_camera_metadata_size(request->settings);
4201 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4202 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4203 captureRequest->settings.resize(0);
4204 captureRequest->fmqSettingsSize = settingsSize;
4205 } else {
4206 if (mRequestMetadataQueue != nullptr) {
4207 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4208 }
4209 captureRequest->settings.setToExternal(
4210 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4211 get_camera_metadata_size(request->settings));
4212 captureRequest->fmqSettingsSize = 0u;
4213 }
4214 } else {
4215 // A null request settings maps to a size-0 CameraMetadata
4216 captureRequest->settings.resize(0);
4217 captureRequest->fmqSettingsSize = 0u;
4218 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004219
4220 if (hidlSession_3_4 != nullptr) {
4221 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4222 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004223 if (request->physcam_settings != nullptr) {
4224 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4225 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4226 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4227 settingsSize)) {
4228 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4229 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4230 settingsSize;
4231 } else {
4232 if (mRequestMetadataQueue != nullptr) {
4233 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4234 }
4235 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4236 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4237 request->physcam_settings[j])),
4238 get_camera_metadata_size(request->physcam_settings[j]));
4239 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004240 }
Emilian Peev00420d22018-02-05 21:33:13 +00004241 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004242 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004243 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004244 }
4245 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4246 request->physcam_id[j];
4247 }
4248 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004249 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004250
4251 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004252 auto resultCallback =
4253 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4254 status = s;
4255 *numRequestProcessed = n;
4256 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004257 if (hidlSession_3_4 != nullptr) {
4258 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004259 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004260 } else {
4261 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004262 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004263 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004264 if (!err.isOk()) {
4265 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4266 return DEAD_OBJECT;
4267 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004268 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4269 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4270 __FUNCTION__, *numRequestProcessed, batchSize);
4271 status = common::V1_0::Status::INTERNAL_ERROR;
4272 }
4273
4274 for (auto& handle : handlesCreated) {
4275 native_handle_delete(handle);
4276 }
4277 return CameraProviderManager::mapToStatusT(status);
4278}
4279
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004280status_t Camera3Device::HalInterface::processCaptureRequest(
4281 camera3_capture_request_t *request) {
4282 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004283 if (!valid()) return INVALID_OPERATION;
4284 status_t res = OK;
4285
Emilian Peev31abd0a2017-05-11 18:37:46 +01004286 uint32_t numRequestProcessed = 0;
4287 std::vector<camera3_capture_request_t*> requests(1);
4288 requests[0] = request;
4289 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4290
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004291 return res;
4292}
4293
4294status_t Camera3Device::HalInterface::flush() {
4295 ATRACE_NAME("CameraHal::flush");
4296 if (!valid()) return INVALID_OPERATION;
4297 status_t res = OK;
4298
Emilian Peev31abd0a2017-05-11 18:37:46 +01004299 auto err = mHidlSession->flush();
4300 if (!err.isOk()) {
4301 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4302 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004303 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004304 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004305 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004306
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004307 return res;
4308}
4309
Emilian Peev31abd0a2017-05-11 18:37:46 +01004310status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004311 ATRACE_NAME("CameraHal::dump");
4312 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004313
Emilian Peev31abd0a2017-05-11 18:37:46 +01004314 // Handled by CameraProviderManager::dump
4315
4316 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004317}
4318
4319status_t Camera3Device::HalInterface::close() {
4320 ATRACE_NAME("CameraHal::close()");
4321 if (!valid()) return INVALID_OPERATION;
4322 status_t res = OK;
4323
Emilian Peev31abd0a2017-05-11 18:37:46 +01004324 auto err = mHidlSession->close();
4325 // Interface will be dead shortly anyway, so don't log errors
4326 if (!err.isOk()) {
4327 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004328 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004329
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004330 return res;
4331}
4332
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004333void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4334 ATRACE_NAME("CameraHal::signalPipelineDrain");
4335 if (!valid() || mHidlSession_3_5 == nullptr) {
4336 ALOGE("%s called on invalid camera!", __FUNCTION__);
4337 return;
4338 }
4339
4340 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter);
4341 if (!err.isOk()) {
4342 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4343 return;
4344 }
4345}
4346
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004347void Camera3Device::HalInterface::getInflightBufferKeys(
4348 std::vector<std::pair<int32_t, int32_t>>* out) {
4349 std::lock_guard<std::mutex> lock(mInflightLock);
4350 out->clear();
4351 out->reserve(mInflightBufferMap.size());
4352 for (auto& pair : mInflightBufferMap) {
4353 uint64_t key = pair.first;
4354 int32_t streamId = key & 0xFFFFFFFF;
4355 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4356 out->push_back(std::make_pair(frameNumber, streamId));
4357 }
4358 return;
4359}
4360
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004361status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004362 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004363 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004364 auto pair = std::make_pair(buffer, acquireFence);
4365 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004366 return OK;
4367}
4368
4369status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004370 int32_t frameNumber, int32_t streamId,
4371 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004372 std::lock_guard<std::mutex> lock(mInflightLock);
4373
4374 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4375 auto it = mInflightBufferMap.find(key);
4376 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004377 auto pair = it->second;
4378 *buffer = pair.first;
4379 int acquireFence = pair.second;
4380 if (acquireFence > 0) {
4381 ::close(acquireFence);
4382 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004383 mInflightBufferMap.erase(it);
4384 return OK;
4385}
4386
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004387status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4388 uint64_t bufferId, buffer_handle_t* buf) {
4389 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4390 auto pair = mRequestedBuffers.insert({bufferId, buf});
4391 if (!pair.second) {
4392 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4393 __FUNCTION__, bufferId);
4394 return BAD_VALUE;
4395 }
4396 return OK;
4397}
4398
4399// Find and pop a buffer_handle_t based on bufferId
4400status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4401 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4402 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4403 auto it = mRequestedBuffers.find(bufferId);
4404 if (it == mRequestedBuffers.end()) {
4405 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4406 __FUNCTION__, bufferId);
4407 return BAD_VALUE;
4408 }
4409 *buffer = it->second;
4410 mRequestedBuffers.erase(it);
4411 return OK;
4412}
4413
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004414std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4415 const buffer_handle_t& buf, int streamId) {
4416 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4417
4418 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4419 auto it = bIdMap.find(buf);
4420 if (it == bIdMap.end()) {
4421 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004422 ALOGV("stream %d now have %zu buffer caches, buf %p",
4423 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004424 return std::make_pair(true, mNextBufferId - 1);
4425 } else {
4426 return std::make_pair(false, it->second);
4427 }
4428}
4429
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004430void Camera3Device::HalInterface::onBufferFreed(
4431 int streamId, const native_handle_t* handle) {
4432 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4433 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4434 auto mapIt = mBufferIdMaps.find(streamId);
4435 if (mapIt == mBufferIdMaps.end()) {
4436 // streamId might be from a deleted stream here
4437 ALOGI("%s: stream %d has been removed",
4438 __FUNCTION__, streamId);
4439 return;
4440 }
4441 BufferIdMap& bIdMap = mapIt->second;
4442 auto it = bIdMap.find(handle);
4443 if (it == bIdMap.end()) {
4444 ALOGW("%s: cannot find buffer %p in stream %d",
4445 __FUNCTION__, handle, streamId);
4446 return;
4447 } else {
4448 bufferId = it->second;
4449 bIdMap.erase(it);
4450 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4451 __FUNCTION__, streamId, bIdMap.size(), handle);
4452 }
4453 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4454}
4455
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004456/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004457 * RequestThread inner class methods
4458 */
4459
4460Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004461 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004462 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4463 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004464 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004465 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004466 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004467 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004468 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004469 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004470 mReconfigured(false),
4471 mDoPause(false),
4472 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004473 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004474 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004475 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004476 mCurrentAfTriggerId(0),
4477 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004478 mRepeatingLastFrameNumber(
4479 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004480 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004481 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004482 mRequestLatency(kRequestLatencyBinSize),
4483 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004484 mLatestSessionParams(sessionParamKeys.size()),
4485 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004486 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004487}
4488
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004489Camera3Device::RequestThread::~RequestThread() {}
4490
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004491void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004492 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004493 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004494 Mutex::Autolock l(mRequestLock);
4495 mListener = listener;
4496}
4497
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004498void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4499 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004500 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004501 Mutex::Autolock l(mRequestLock);
4502 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004503 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004504 // Prepare video stream for high speed recording.
4505 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004506 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004507}
4508
Jianing Wei90e59c92014-03-12 18:29:36 -07004509status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004510 List<sp<CaptureRequest> > &requests,
4511 /*out*/
4512 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004513 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004514 Mutex::Autolock l(mRequestLock);
4515 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4516 ++it) {
4517 mRequestQueue.push_back(*it);
4518 }
4519
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004520 if (lastFrameNumber != NULL) {
4521 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4522 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4523 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4524 *lastFrameNumber);
4525 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004526
Jianing Wei90e59c92014-03-12 18:29:36 -07004527 unpauseForNewRequests();
4528
4529 return OK;
4530}
4531
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004532
4533status_t Camera3Device::RequestThread::queueTrigger(
4534 RequestTrigger trigger[],
4535 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004536 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004537 Mutex::Autolock l(mTriggerMutex);
4538 status_t ret;
4539
4540 for (size_t i = 0; i < count; ++i) {
4541 ret = queueTriggerLocked(trigger[i]);
4542
4543 if (ret != OK) {
4544 return ret;
4545 }
4546 }
4547
4548 return OK;
4549}
4550
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004551const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4552 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004553 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004554 if (d != nullptr) return d->mId;
4555 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004556}
4557
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004558status_t Camera3Device::RequestThread::queueTriggerLocked(
4559 RequestTrigger trigger) {
4560
4561 uint32_t tag = trigger.metadataTag;
4562 ssize_t index = mTriggerMap.indexOfKey(tag);
4563
4564 switch (trigger.getTagType()) {
4565 case TYPE_BYTE:
4566 // fall-through
4567 case TYPE_INT32:
4568 break;
4569 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004570 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4571 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004572 return INVALID_OPERATION;
4573 }
4574
4575 /**
4576 * Collect only the latest trigger, since we only have 1 field
4577 * in the request settings per trigger tag, and can't send more than 1
4578 * trigger per request.
4579 */
4580 if (index != NAME_NOT_FOUND) {
4581 mTriggerMap.editValueAt(index) = trigger;
4582 } else {
4583 mTriggerMap.add(tag, trigger);
4584 }
4585
4586 return OK;
4587}
4588
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004589status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004590 const RequestList &requests,
4591 /*out*/
4592 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004593 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004594 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004595 if (lastFrameNumber != NULL) {
4596 *lastFrameNumber = mRepeatingLastFrameNumber;
4597 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004598 mRepeatingRequests.clear();
4599 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4600 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004601
4602 unpauseForNewRequests();
4603
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004604 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004605 return OK;
4606}
4607
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004608bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004609 if (mRepeatingRequests.empty()) {
4610 return false;
4611 }
4612 int32_t requestId = requestIn->mResultExtras.requestId;
4613 const RequestList &repeatRequests = mRepeatingRequests;
4614 // All repeating requests are guaranteed to have same id so only check first quest
4615 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4616 return (firstRequest->mResultExtras.requestId == requestId);
4617}
4618
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004619status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004620 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004621 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004622 return clearRepeatingRequestsLocked(lastFrameNumber);
4623
4624}
4625
4626status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004627 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004628 if (lastFrameNumber != NULL) {
4629 *lastFrameNumber = mRepeatingLastFrameNumber;
4630 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004631 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004632 return OK;
4633}
4634
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004635status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004636 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004637 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004638 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004639 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004640
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004641 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004642
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004643 // Send errors for all requests pending in the request queue, including
4644 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004645 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004646 if (listener != NULL) {
4647 for (RequestList::iterator it = mRequestQueue.begin();
4648 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004649 // Abort the input buffers for reprocess requests.
4650 if ((*it)->mInputStream != NULL) {
4651 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004652 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4653 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004654 if (res != OK) {
4655 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4656 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4657 } else {
4658 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4659 if (res != OK) {
4660 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4661 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4662 }
4663 }
4664 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004665 // Set the frame number this request would have had, if it
4666 // had been submitted; this frame number will not be reused.
4667 // The requestId and burstId fields were set when the request was
4668 // submitted originally (in convertMetadataListToRequestListLocked)
4669 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004670 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004671 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004672 }
4673 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004674 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004675
4676 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004677 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004678 if (lastFrameNumber != NULL) {
4679 *lastFrameNumber = mRepeatingLastFrameNumber;
4680 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004681 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004682 return OK;
4683}
4684
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004685status_t Camera3Device::RequestThread::flush() {
4686 ATRACE_CALL();
4687 Mutex::Autolock l(mFlushLock);
4688
Emilian Peev08dd2452017-04-06 16:55:14 +01004689 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004690}
4691
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004692void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004693 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004694 Mutex::Autolock l(mPauseLock);
4695 mDoPause = paused;
4696 mDoPauseSignal.signal();
4697}
4698
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004699status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4700 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004701 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004702 Mutex::Autolock l(mLatestRequestMutex);
4703 status_t res;
4704 while (mLatestRequestId != requestId) {
4705 nsecs_t startTime = systemTime();
4706
4707 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4708 if (res != OK) return res;
4709
4710 timeout -= (systemTime() - startTime);
4711 }
4712
4713 return OK;
4714}
4715
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004716void Camera3Device::RequestThread::requestExit() {
4717 // Call parent to set up shutdown
4718 Thread::requestExit();
4719 // The exit from any possible waits
4720 mDoPauseSignal.signal();
4721 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004722
4723 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4724 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004725}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004726
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004727void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004728 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004729 bool surfaceAbandoned = false;
4730 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004731 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004732 {
4733 Mutex::Autolock l(mRequestLock);
4734 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4735 // repeating requests.
4736 for (const auto& request : mRepeatingRequests) {
4737 for (const auto& s : request->mOutputStreams) {
4738 if (s->isAbandoned()) {
4739 surfaceAbandoned = true;
4740 clearRepeatingRequestsLocked(&lastFrameNumber);
4741 break;
4742 }
4743 }
4744 if (surfaceAbandoned) {
4745 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004746 }
4747 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004748 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004749 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004750
4751 if (listener != NULL && surfaceAbandoned) {
4752 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004753 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004754}
4755
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004756bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004757 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004758 status_t res;
4759 size_t batchSize = mNextRequests.size();
4760 std::vector<camera3_capture_request_t*> requests(batchSize);
4761 uint32_t numRequestProcessed = 0;
4762 for (size_t i = 0; i < batchSize; i++) {
4763 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004764 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004765 }
4766
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004767 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4768
4769 bool triggerRemoveFailed = false;
4770 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4771 for (size_t i = 0; i < numRequestProcessed; i++) {
4772 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4773 nextRequest.submitted = true;
4774
4775
4776 // Update the latest request sent to HAL
4777 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4778 Mutex::Autolock al(mLatestRequestMutex);
4779
4780 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4781 mLatestRequest.acquire(cloned);
4782
4783 sp<Camera3Device> parent = mParent.promote();
4784 if (parent != NULL) {
4785 parent->monitorMetadata(TagMonitor::REQUEST,
4786 nextRequest.halRequest.frame_number,
4787 0, mLatestRequest);
4788 }
4789 }
4790
4791 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004792 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4793 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004794 }
4795
Emilian Peevaebbe412018-01-15 13:53:24 +00004796 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4797
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004798 if (!triggerRemoveFailed) {
4799 // Remove any previously queued triggers (after unlock)
4800 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4801 if (removeTriggerRes != OK) {
4802 triggerRemoveFailed = true;
4803 triggerFailedRequest = nextRequest;
4804 }
4805 }
4806 }
4807
4808 if (triggerRemoveFailed) {
4809 SET_ERR("RequestThread: Unable to remove triggers "
4810 "(capture request %d, HAL device: %s (%d)",
4811 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4812 cleanUpFailedRequests(/*sendRequestError*/ false);
4813 return false;
4814 }
4815
4816 if (res != OK) {
4817 // Should only get a failure here for malformed requests or device-level
4818 // errors, so consider all errors fatal. Bad metadata failures should
4819 // come through notify.
4820 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4821 mNextRequests[numRequestProcessed].halRequest.frame_number,
4822 strerror(-res), res);
4823 cleanUpFailedRequests(/*sendRequestError*/ false);
4824 return false;
4825 }
4826 return true;
4827}
4828
4829bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4830 status_t res;
4831
4832 for (auto& nextRequest : mNextRequests) {
4833 // Submit request and block until ready for next one
4834 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4835 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4836
4837 if (res != OK) {
4838 // Should only get a failure here for malformed requests or device-level
4839 // errors, so consider all errors fatal. Bad metadata failures should
4840 // come through notify.
4841 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4842 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4843 res);
4844 cleanUpFailedRequests(/*sendRequestError*/ false);
4845 return false;
4846 }
4847
4848 // Mark that the request has be submitted successfully.
4849 nextRequest.submitted = true;
4850
4851 // Update the latest request sent to HAL
4852 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4853 Mutex::Autolock al(mLatestRequestMutex);
4854
4855 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4856 mLatestRequest.acquire(cloned);
4857
4858 sp<Camera3Device> parent = mParent.promote();
4859 if (parent != NULL) {
4860 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4861 0, mLatestRequest);
4862 }
4863 }
4864
4865 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004866 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4867 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004868 }
4869
Emilian Peevaebbe412018-01-15 13:53:24 +00004870 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4871
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004872 // Remove any previously queued triggers (after unlock)
4873 res = removeTriggers(mPrevRequest);
4874 if (res != OK) {
4875 SET_ERR("RequestThread: Unable to remove triggers "
4876 "(capture request %d, HAL device: %s (%d)",
4877 nextRequest.halRequest.frame_number, strerror(-res), res);
4878 cleanUpFailedRequests(/*sendRequestError*/ false);
4879 return false;
4880 }
4881 }
4882 return true;
4883}
4884
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004885nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4886 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4887 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4888 find_camera_metadata_ro_entry(request,
4889 ANDROID_CONTROL_AE_MODE,
4890 &e);
4891 if (e.count == 0) return maxExpectedDuration;
4892
4893 switch (e.data.u8[0]) {
4894 case ANDROID_CONTROL_AE_MODE_OFF:
4895 find_camera_metadata_ro_entry(request,
4896 ANDROID_SENSOR_EXPOSURE_TIME,
4897 &e);
4898 if (e.count > 0) {
4899 maxExpectedDuration = e.data.i64[0];
4900 }
4901 find_camera_metadata_ro_entry(request,
4902 ANDROID_SENSOR_FRAME_DURATION,
4903 &e);
4904 if (e.count > 0) {
4905 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4906 }
4907 break;
4908 default:
4909 find_camera_metadata_ro_entry(request,
4910 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4911 &e);
4912 if (e.count > 1) {
4913 maxExpectedDuration = 1e9 / e.data.u8[0];
4914 }
4915 break;
4916 }
4917
4918 return maxExpectedDuration;
4919}
4920
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004921bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4922 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4923 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4924 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4925 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4926 return true;
4927 }
4928
4929 return false;
4930}
4931
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004932bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4933 ATRACE_CALL();
4934 bool updatesDetected = false;
4935
4936 for (auto tag : mSessionParamKeys) {
4937 camera_metadata_ro_entry entry = settings.find(tag);
4938 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4939
4940 if (entry.count > 0) {
4941 bool isDifferent = false;
4942 if (lastEntry.count > 0) {
4943 // Have a last value, compare to see if changed
4944 if (lastEntry.type == entry.type &&
4945 lastEntry.count == entry.count) {
4946 // Same type and count, compare values
4947 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4948 size_t entryBytes = bytesPerValue * lastEntry.count;
4949 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4950 if (cmp != 0) {
4951 isDifferent = true;
4952 }
4953 } else {
4954 // Count or type has changed
4955 isDifferent = true;
4956 }
4957 } else {
4958 // No last entry, so always consider to be different
4959 isDifferent = true;
4960 }
4961
4962 if (isDifferent) {
4963 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004964 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4965 updatesDetected = true;
4966 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004967 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004968 }
4969 } else if (lastEntry.count > 0) {
4970 // Value has been removed
4971 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4972 mLatestSessionParams.erase(tag);
4973 updatesDetected = true;
4974 }
4975 }
4976
4977 return updatesDetected;
4978}
4979
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004980bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004981 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004982 status_t res;
4983
4984 // Handle paused state.
4985 if (waitIfPaused()) {
4986 return true;
4987 }
4988
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004989 // Wait for the next batch of requests.
4990 waitForNextRequestBatch();
4991 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004992 return true;
4993 }
4994
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004995 // Get the latest request ID, if any
4996 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004997 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004998 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004999 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005000 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005001 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005002 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5003 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005004 }
5005
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005006 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5007 // or a single request from streaming or burst. In either case the first element
5008 // should contain the latest camera settings that we need to check for any session
5009 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005010 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005011 res = OK;
5012
5013 //Input stream buffers are already acquired at this point so an input stream
5014 //will not be able to move to idle state unless we force it.
5015 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5016 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5017 if (res != OK) {
5018 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5019 cleanUpFailedRequests(/*sendRequestError*/ false);
5020 return false;
5021 }
5022 }
5023
5024 if (res == OK) {
5025 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5026 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005027 sp<Camera3Device> parent = mParent.promote();
5028 if (parent != nullptr) {
5029 parent->pauseStateNotify(true);
5030 }
5031
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005032 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5033
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005034 if (parent != nullptr) {
5035 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5036 }
5037
5038 statusTracker->markComponentActive(mStatusId);
5039 setPaused(false);
5040 }
5041
5042 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5043 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5044 if (res != OK) {
5045 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5046 cleanUpFailedRequests(/*sendRequestError*/ false);
5047 return false;
5048 }
5049 }
5050 }
5051 }
5052
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005053 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005054 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005055 if (res == TIMED_OUT) {
5056 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005057 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005058 // Check if any stream is abandoned.
5059 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005060 return true;
5061 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005062 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005063 return false;
5064 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005065
Zhijun Hecc27e112013-10-03 16:12:43 -07005066 // Inform waitUntilRequestProcessed thread of a new request ID
5067 {
5068 Mutex::Autolock al(mLatestRequestMutex);
5069
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005070 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005071 mLatestRequestSignal.signal();
5072 }
5073
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005074 // Submit a batch of requests to HAL.
5075 // Use flush lock only when submitting multilple requests in a batch.
5076 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5077 // which may take a long time to finish so synchronizing flush() and
5078 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5079 // For now, only synchronize for high speed recording and we should figure something out for
5080 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005081 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005082
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005083 if (useFlushLock) {
5084 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005085 }
5086
Zhijun Hef0645c12016-08-02 00:58:11 -07005087 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005088 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005089
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005090 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005091 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005092 if (mInterface->supportBatchRequest()) {
5093 submitRequestSuccess = sendRequestsBatch();
5094 } else {
5095 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005096 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005097 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5098 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005099
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005100 if (useFlushLock) {
5101 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005102 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005103
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005104 // Unset as current request
5105 {
5106 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005107 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005108 }
5109
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005110 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005111}
5112
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005113status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005114 ATRACE_CALL();
5115
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005116 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005117 for (size_t i = 0; i < mNextRequests.size(); i++) {
5118 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005119 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5120 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5121 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5122
5123 // Prepare a request to HAL
5124 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5125
5126 // Insert any queued triggers (before metadata is locked)
5127 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005128 if (res < 0) {
5129 SET_ERR("RequestThread: Unable to insert triggers "
5130 "(capture request %d, HAL device: %s (%d)",
5131 halRequest->frame_number, strerror(-res), res);
5132 return INVALID_OPERATION;
5133 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005134
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005135 int triggerCount = res;
5136 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5137 mPrevTriggers = triggerCount;
5138
5139 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005140 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5141 // Request settings are all the same within one batch, so only treat the first
5142 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005143 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005144 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005145 /**
5146 * HAL workaround:
5147 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5148 */
5149 res = addDummyTriggerIds(captureRequest);
5150 if (res != OK) {
5151 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5152 "(capture request %d, HAL device: %s (%d)",
5153 halRequest->frame_number, strerror(-res), res);
5154 return INVALID_OPERATION;
5155 }
5156
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005157 {
5158 // Correct metadata regions for distortion correction if enabled
5159 sp<Camera3Device> parent = mParent.promote();
5160 if (parent != nullptr) {
5161 res = parent->mDistortionMapper.correctCaptureRequest(
5162 &(captureRequest->mSettingsList.begin()->metadata));
5163 if (res != OK) {
5164 SET_ERR("RequestThread: Unable to correct capture requests "
5165 "for lens distortion for request %d: %s (%d)",
5166 halRequest->frame_number, strerror(-res), res);
5167 return INVALID_OPERATION;
5168 }
5169 }
5170 }
5171
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005172 /**
5173 * The request should be presorted so accesses in HAL
5174 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5175 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005176 captureRequest->mSettingsList.begin()->metadata.sort();
5177 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005178 mPrevRequest = captureRequest;
5179 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5180
5181 IF_ALOGV() {
5182 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5183 find_camera_metadata_ro_entry(
5184 halRequest->settings,
5185 ANDROID_CONTROL_AF_TRIGGER,
5186 &e
5187 );
5188 if (e.count > 0) {
5189 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5190 __FUNCTION__,
5191 halRequest->frame_number,
5192 e.data.u8[0]);
5193 }
5194 }
5195 } else {
5196 // leave request.settings NULL to indicate 'reuse latest given'
5197 ALOGVV("%s: Request settings are REUSED",
5198 __FUNCTION__);
5199 }
5200
Emilian Peevaebbe412018-01-15 13:53:24 +00005201 if (captureRequest->mSettingsList.size() > 1) {
5202 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5203 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005204 if (newRequest) {
5205 halRequest->physcam_settings =
5206 new const camera_metadata* [halRequest->num_physcam_settings];
5207 } else {
5208 halRequest->physcam_settings = nullptr;
5209 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005210 auto it = ++captureRequest->mSettingsList.begin();
5211 size_t i = 0;
5212 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5213 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005214 if (newRequest) {
5215 it->metadata.sort();
5216 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5217 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005218 }
5219 }
5220
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005221 uint32_t totalNumBuffers = 0;
5222
5223 // Fill in buffers
5224 if (captureRequest->mInputStream != NULL) {
5225 halRequest->input_buffer = &captureRequest->mInputBuffer;
5226 totalNumBuffers += 1;
5227 } else {
5228 halRequest->input_buffer = NULL;
5229 }
5230
5231 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5232 captureRequest->mOutputStreams.size());
5233 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005234 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005235
5236 sp<Camera3Device> parent = mParent.promote();
5237 if (parent == NULL) {
5238 // Should not happen, and nowhere to send errors to, so just log it
5239 CLOGE("RequestThread: Parent is gone");
5240 return INVALID_OPERATION;
5241 }
5242 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5243
Shuzhen Wang4a472662017-02-26 23:29:04 -08005244 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
5245 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005246
5247 // Prepare video buffers for high speed recording on the first video request.
5248 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5249 // Only try to prepare video stream on the first video request.
5250 mPrepareVideoStream = false;
5251
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005252 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5253 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005254 while (res == NOT_ENOUGH_DATA) {
5255 res = outputStream->prepareNextBuffer();
5256 }
5257 if (res != OK) {
5258 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5259 __FUNCTION__, strerror(-res), res);
5260 outputStream->cancelPrepare();
5261 }
5262 }
5263
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005264 if (mUseHalBufManager) {
5265 // HAL will request buffer through requestStreamBuffer API
5266 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5267 buffer.stream = outputStream->asHalStream();
5268 buffer.buffer = nullptr;
5269 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5270 buffer.acquire_fence = -1;
5271 buffer.release_fence = -1;
5272 } else {
5273 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5274 waitDuration,
5275 captureRequest->mOutputSurfaces[outputStream->getId()]);
5276 if (res != OK) {
5277 // Can't get output buffer from gralloc queue - this could be due to
5278 // abandoned queue or other consumer misbehavior, so not a fatal
5279 // error
5280 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5281 " %s (%d)", strerror(-res), res);
5282
5283 return TIMED_OUT;
5284 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005285 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005286
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005287 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5288
5289 if (!physicalCameraId.isEmpty()) {
5290 // Physical stream isn't supported for input request.
5291 if (halRequest->input_buffer) {
5292 CLOGE("Physical stream is not supported for input request");
5293 return INVALID_OPERATION;
5294 }
5295 requestedPhysicalCameras.insert(physicalCameraId);
5296 }
5297 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005298 }
5299 totalNumBuffers += halRequest->num_output_buffers;
5300
5301 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005302 // If this request list is for constrained high speed recording (not
5303 // preview), and the current request is not the last one in the batch,
5304 // do not send callback to the app.
5305 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005306 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005307 hasCallback = false;
5308 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005309 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005310 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005311 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5312 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5313 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5314 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5315 isStillCapture = true;
5316 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5317 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005318
5319 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5320 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5321 isZslCapture = true;
5322 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005323 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005324 res = parent->registerInFlight(halRequest->frame_number,
5325 totalNumBuffers, captureRequest->mResultExtras,
5326 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005327 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005328 calculateMaxExpectedDuration(halRequest->settings),
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005329 requestedPhysicalCameras, isStillCapture, isZslCapture);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005330 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5331 ", burstId = %" PRId32 ".",
5332 __FUNCTION__,
5333 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5334 captureRequest->mResultExtras.burstId);
5335 if (res != OK) {
5336 SET_ERR("RequestThread: Unable to register new in-flight request:"
5337 " %s (%d)", strerror(-res), res);
5338 return INVALID_OPERATION;
5339 }
5340 }
5341
5342 return OK;
5343}
5344
Igor Murashkin1e479c02013-09-06 16:55:14 -07005345CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005346 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005347 Mutex::Autolock al(mLatestRequestMutex);
5348
5349 ALOGV("RequestThread::%s", __FUNCTION__);
5350
5351 return mLatestRequest;
5352}
5353
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005354bool Camera3Device::RequestThread::isStreamPending(
5355 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005356 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005357 Mutex::Autolock l(mRequestLock);
5358
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005359 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005360 if (!nextRequest.submitted) {
5361 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5362 if (stream == s) return true;
5363 }
5364 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005365 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005366 }
5367
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005368 for (const auto& request : mRequestQueue) {
5369 for (const auto& s : request->mOutputStreams) {
5370 if (stream == s) return true;
5371 }
5372 if (stream == request->mInputStream) return true;
5373 }
5374
5375 for (const auto& request : mRepeatingRequests) {
5376 for (const auto& s : request->mOutputStreams) {
5377 if (stream == s) return true;
5378 }
5379 if (stream == request->mInputStream) return true;
5380 }
5381
5382 return false;
5383}
Jianing Weicb0652e2014-03-12 18:29:36 -07005384
Emilian Peev40ead602017-09-26 15:46:36 +01005385bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5386 ATRACE_CALL();
5387 Mutex::Autolock l(mRequestLock);
5388
5389 for (const auto& nextRequest : mNextRequests) {
5390 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5391 if (s.first == streamId) {
5392 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5393 if (it != s.second.end()) {
5394 return true;
5395 }
5396 }
5397 }
5398 }
5399
5400 for (const auto& request : mRequestQueue) {
5401 for (const auto& s : request->mOutputSurfaces) {
5402 if (s.first == streamId) {
5403 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5404 if (it != s.second.end()) {
5405 return true;
5406 }
5407 }
5408 }
5409 }
5410
5411 for (const auto& request : mRepeatingRequests) {
5412 for (const auto& s : request->mOutputSurfaces) {
5413 if (s.first == streamId) {
5414 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5415 if (it != s.second.end()) {
5416 return true;
5417 }
5418 }
5419 }
5420 }
5421
5422 return false;
5423}
5424
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005425void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5426 if (!mUseHalBufManager) {
5427 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5428 return;
5429 }
5430
5431 Mutex::Autolock pl(mPauseLock);
5432 if (mPaused) {
5433 return mInterface->signalPipelineDrain(streamIds);
5434 }
5435 // If request thread is still busy, wait until paused then notify HAL
5436 mNotifyPipelineDrain = true;
5437 mStreamIdsToBeDrained = streamIds;
5438}
5439
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005440nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005441 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005442 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005443 return mExpectedInflightDuration > kMinInflightDuration ?
5444 mExpectedInflightDuration : kMinInflightDuration;
5445}
5446
Emilian Peevaebbe412018-01-15 13:53:24 +00005447void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5448 camera3_capture_request_t *halRequest) {
5449 if ((request == nullptr) || (halRequest == nullptr)) {
5450 ALOGE("%s: Invalid request!", __FUNCTION__);
5451 return;
5452 }
5453
5454 if (halRequest->num_physcam_settings > 0) {
5455 if (halRequest->physcam_id != nullptr) {
5456 delete [] halRequest->physcam_id;
5457 halRequest->physcam_id = nullptr;
5458 }
5459 if (halRequest->physcam_settings != nullptr) {
5460 auto it = ++(request->mSettingsList.begin());
5461 size_t i = 0;
5462 for (; it != request->mSettingsList.end(); it++, i++) {
5463 it->metadata.unlock(halRequest->physcam_settings[i]);
5464 }
5465 delete [] halRequest->physcam_settings;
5466 halRequest->physcam_settings = nullptr;
5467 }
5468 }
5469}
5470
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005471void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5472 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005473 return;
5474 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005475
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005476 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005477 // Skip the ones that have been submitted successfully.
5478 if (nextRequest.submitted) {
5479 continue;
5480 }
5481
5482 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5483 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5484 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5485
5486 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005487 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005488 }
5489
Emilian Peevaebbe412018-01-15 13:53:24 +00005490 cleanupPhysicalSettings(captureRequest, halRequest);
5491
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005492 if (captureRequest->mInputStream != NULL) {
5493 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5494 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5495 }
5496
5497 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005498 //Buffers that failed processing could still have
5499 //valid acquire fence.
5500 int acquireFence = (*outputBuffers)[i].acquire_fence;
5501 if (0 <= acquireFence) {
5502 close(acquireFence);
5503 outputBuffers->editItemAt(i).acquire_fence = -1;
5504 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005505 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5506 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5507 }
5508
5509 if (sendRequestError) {
5510 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005511 sp<NotificationListener> listener = mListener.promote();
5512 if (listener != NULL) {
5513 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005514 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005515 captureRequest->mResultExtras);
5516 }
5517 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005518
5519 // Remove yet-to-be submitted inflight request from inflightMap
5520 {
5521 sp<Camera3Device> parent = mParent.promote();
5522 if (parent != NULL) {
5523 Mutex::Autolock l(parent->mInFlightLock);
5524 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5525 if (idx >= 0) {
5526 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5527 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5528 parent->removeInFlightMapEntryLocked(idx);
5529 }
5530 }
5531 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005532 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005533
5534 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005535 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005536}
5537
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005538void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005539 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005540 // Optimized a bit for the simple steady-state case (single repeating
5541 // request), to avoid putting that request in the queue temporarily.
5542 Mutex::Autolock l(mRequestLock);
5543
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005544 assert(mNextRequests.empty());
5545
5546 NextRequest nextRequest;
5547 nextRequest.captureRequest = waitForNextRequestLocked();
5548 if (nextRequest.captureRequest == nullptr) {
5549 return;
5550 }
5551
5552 nextRequest.halRequest = camera3_capture_request_t();
5553 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005554 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005555
5556 // Wait for additional requests
5557 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5558
5559 for (size_t i = 1; i < batchSize; i++) {
5560 NextRequest additionalRequest;
5561 additionalRequest.captureRequest = waitForNextRequestLocked();
5562 if (additionalRequest.captureRequest == nullptr) {
5563 break;
5564 }
5565
5566 additionalRequest.halRequest = camera3_capture_request_t();
5567 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005568 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005569 }
5570
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005571 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005572 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005573 mNextRequests.size(), batchSize);
5574 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005575 }
5576
5577 return;
5578}
5579
5580sp<Camera3Device::CaptureRequest>
5581 Camera3Device::RequestThread::waitForNextRequestLocked() {
5582 status_t res;
5583 sp<CaptureRequest> nextRequest;
5584
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005585 while (mRequestQueue.empty()) {
5586 if (!mRepeatingRequests.empty()) {
5587 // Always atomically enqueue all requests in a repeating request
5588 // list. Guarantees a complete in-sequence set of captures to
5589 // application.
5590 const RequestList &requests = mRepeatingRequests;
5591 RequestList::const_iterator firstRequest =
5592 requests.begin();
5593 nextRequest = *firstRequest;
5594 mRequestQueue.insert(mRequestQueue.end(),
5595 ++firstRequest,
5596 requests.end());
5597 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005598
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005599 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005600
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005601 break;
5602 }
5603
5604 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5605
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005606 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5607 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005608 Mutex::Autolock pl(mPauseLock);
5609 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005610 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005611 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005612 // Let the tracker know
5613 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5614 if (statusTracker != 0) {
5615 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5616 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005617 if (mNotifyPipelineDrain) {
5618 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5619 mNotifyPipelineDrain = false;
5620 mStreamIdsToBeDrained.clear();
5621 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005622 }
5623 // Stop waiting for now and let thread management happen
5624 return NULL;
5625 }
5626 }
5627
5628 if (nextRequest == NULL) {
5629 // Don't have a repeating request already in hand, so queue
5630 // must have an entry now.
5631 RequestList::iterator firstRequest =
5632 mRequestQueue.begin();
5633 nextRequest = *firstRequest;
5634 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005635 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5636 sp<NotificationListener> listener = mListener.promote();
5637 if (listener != NULL) {
5638 listener->notifyRequestQueueEmpty();
5639 }
5640 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005641 }
5642
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005643 // In case we've been unpaused by setPaused clearing mDoPause, need to
5644 // update internal pause state (capture/setRepeatingRequest unpause
5645 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005646 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005647 if (mPaused) {
5648 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5649 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5650 if (statusTracker != 0) {
5651 statusTracker->markComponentActive(mStatusId);
5652 }
5653 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005654 mPaused = false;
5655
5656 // Check if we've reconfigured since last time, and reset the preview
5657 // request if so. Can't use 'NULL request == repeat' across configure calls.
5658 if (mReconfigured) {
5659 mPrevRequest.clear();
5660 mReconfigured = false;
5661 }
5662
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005663 if (nextRequest != NULL) {
5664 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005665 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5666 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005667
5668 // Since RequestThread::clear() removes buffers from the input stream,
5669 // get the right buffer here before unlocking mRequestLock
5670 if (nextRequest->mInputStream != NULL) {
5671 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5672 if (res != OK) {
5673 // Can't get input buffer from gralloc queue - this could be due to
5674 // disconnected queue or other producer misbehavior, so not a fatal
5675 // error
5676 ALOGE("%s: Can't get input buffer, skipping request:"
5677 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005678
5679 sp<NotificationListener> listener = mListener.promote();
5680 if (listener != NULL) {
5681 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005682 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005683 nextRequest->mResultExtras);
5684 }
5685 return NULL;
5686 }
5687 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005688 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005689
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005690 return nextRequest;
5691}
5692
5693bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005694 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005695 status_t res;
5696 Mutex::Autolock l(mPauseLock);
5697 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005698 if (mPaused == false) {
5699 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005700 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5701 // Let the tracker know
5702 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5703 if (statusTracker != 0) {
5704 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5705 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005706 if (mNotifyPipelineDrain) {
5707 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5708 mNotifyPipelineDrain = false;
5709 mStreamIdsToBeDrained.clear();
5710 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005711 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005712
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005713 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005714 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005715 return true;
5716 }
5717 }
5718 // We don't set mPaused to false here, because waitForNextRequest needs
5719 // to further manage the paused state in case of starvation.
5720 return false;
5721}
5722
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005723void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005724 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005725 // With work to do, mark thread as unpaused.
5726 // If paused by request (setPaused), don't resume, to avoid
5727 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005728 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005729 Mutex::Autolock p(mPauseLock);
5730 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005731 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5732 if (mPaused) {
5733 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5734 if (statusTracker != 0) {
5735 statusTracker->markComponentActive(mStatusId);
5736 }
5737 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005738 mPaused = false;
5739 }
5740}
5741
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005742void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5743 sp<Camera3Device> parent = mParent.promote();
5744 if (parent != NULL) {
5745 va_list args;
5746 va_start(args, fmt);
5747
5748 parent->setErrorStateV(fmt, args);
5749
5750 va_end(args);
5751 }
5752}
5753
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005754status_t Camera3Device::RequestThread::insertTriggers(
5755 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005756 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005757 Mutex::Autolock al(mTriggerMutex);
5758
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005759 sp<Camera3Device> parent = mParent.promote();
5760 if (parent == NULL) {
5761 CLOGE("RequestThread: Parent is gone");
5762 return DEAD_OBJECT;
5763 }
5764
Emilian Peevaebbe412018-01-15 13:53:24 +00005765 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005766 size_t count = mTriggerMap.size();
5767
5768 for (size_t i = 0; i < count; ++i) {
5769 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005770 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005771
5772 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5773 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5774 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005775 if (isAeTrigger) {
5776 request->mResultExtras.precaptureTriggerId = triggerId;
5777 mCurrentPreCaptureTriggerId = triggerId;
5778 } else {
5779 request->mResultExtras.afTriggerId = triggerId;
5780 mCurrentAfTriggerId = triggerId;
5781 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005782 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005783 }
5784
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005785 camera_metadata_entry entry = metadata.find(tag);
5786
5787 if (entry.count > 0) {
5788 /**
5789 * Already has an entry for this trigger in the request.
5790 * Rewrite it with our requested trigger value.
5791 */
5792 RequestTrigger oldTrigger = trigger;
5793
5794 oldTrigger.entryValue = entry.data.u8[0];
5795
5796 mTriggerReplacedMap.add(tag, oldTrigger);
5797 } else {
5798 /**
5799 * More typical, no trigger entry, so we just add it
5800 */
5801 mTriggerRemovedMap.add(tag, trigger);
5802 }
5803
5804 status_t res;
5805
5806 switch (trigger.getTagType()) {
5807 case TYPE_BYTE: {
5808 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5809 res = metadata.update(tag,
5810 &entryValue,
5811 /*count*/1);
5812 break;
5813 }
5814 case TYPE_INT32:
5815 res = metadata.update(tag,
5816 &trigger.entryValue,
5817 /*count*/1);
5818 break;
5819 default:
5820 ALOGE("%s: Type not supported: 0x%x",
5821 __FUNCTION__,
5822 trigger.getTagType());
5823 return INVALID_OPERATION;
5824 }
5825
5826 if (res != OK) {
5827 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5828 ", value %d", __FUNCTION__, trigger.getTagName(),
5829 trigger.entryValue);
5830 return res;
5831 }
5832
5833 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5834 trigger.getTagName(),
5835 trigger.entryValue);
5836 }
5837
5838 mTriggerMap.clear();
5839
5840 return count;
5841}
5842
5843status_t Camera3Device::RequestThread::removeTriggers(
5844 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005845 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005846 Mutex::Autolock al(mTriggerMutex);
5847
Emilian Peevaebbe412018-01-15 13:53:24 +00005848 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005849
5850 /**
5851 * Replace all old entries with their old values.
5852 */
5853 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5854 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5855
5856 status_t res;
5857
5858 uint32_t tag = trigger.metadataTag;
5859 switch (trigger.getTagType()) {
5860 case TYPE_BYTE: {
5861 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5862 res = metadata.update(tag,
5863 &entryValue,
5864 /*count*/1);
5865 break;
5866 }
5867 case TYPE_INT32:
5868 res = metadata.update(tag,
5869 &trigger.entryValue,
5870 /*count*/1);
5871 break;
5872 default:
5873 ALOGE("%s: Type not supported: 0x%x",
5874 __FUNCTION__,
5875 trigger.getTagType());
5876 return INVALID_OPERATION;
5877 }
5878
5879 if (res != OK) {
5880 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5881 ", trigger value %d", __FUNCTION__,
5882 trigger.getTagName(), trigger.entryValue);
5883 return res;
5884 }
5885 }
5886 mTriggerReplacedMap.clear();
5887
5888 /**
5889 * Remove all new entries.
5890 */
5891 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5892 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5893 status_t res = metadata.erase(trigger.metadataTag);
5894
5895 if (res != OK) {
5896 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5897 ", trigger value %d", __FUNCTION__,
5898 trigger.getTagName(), trigger.entryValue);
5899 return res;
5900 }
5901 }
5902 mTriggerRemovedMap.clear();
5903
5904 return OK;
5905}
5906
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005907status_t Camera3Device::RequestThread::addDummyTriggerIds(
5908 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005909 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005910 static const int32_t dummyTriggerId = 1;
5911 status_t res;
5912
Emilian Peevaebbe412018-01-15 13:53:24 +00005913 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005914
5915 // If AF trigger is active, insert a dummy AF trigger ID if none already
5916 // exists
5917 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5918 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5919 if (afTrigger.count > 0 &&
5920 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5921 afId.count == 0) {
5922 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5923 if (res != OK) return res;
5924 }
5925
5926 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5927 // if none already exists
5928 camera_metadata_entry pcTrigger =
5929 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5930 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5931 if (pcTrigger.count > 0 &&
5932 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5933 pcId.count == 0) {
5934 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5935 &dummyTriggerId, 1);
5936 if (res != OK) return res;
5937 }
5938
5939 return OK;
5940}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005941
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005942/**
5943 * PreparerThread inner class methods
5944 */
5945
5946Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005947 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005948 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005949}
5950
5951Camera3Device::PreparerThread::~PreparerThread() {
5952 Thread::requestExitAndWait();
5953 if (mCurrentStream != nullptr) {
5954 mCurrentStream->cancelPrepare();
5955 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5956 mCurrentStream.clear();
5957 }
5958 clear();
5959}
5960
Ruben Brunkc78ac262015-08-13 17:58:46 -07005961status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005962 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005963 status_t res;
5964
5965 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005966 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005967
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005968 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005969 if (res == OK) {
5970 // No preparation needed, fire listener right off
5971 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005972 if (listener != NULL) {
5973 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005974 }
5975 return OK;
5976 } else if (res != NOT_ENOUGH_DATA) {
5977 return res;
5978 }
5979
5980 // Need to prepare, start up thread if necessary
5981 if (!mActive) {
5982 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5983 // isn't running
5984 Thread::requestExitAndWait();
5985 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5986 if (res != OK) {
5987 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005988 if (listener != NULL) {
5989 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005990 }
5991 return res;
5992 }
5993 mCancelNow = false;
5994 mActive = true;
5995 ALOGV("%s: Preparer stream started", __FUNCTION__);
5996 }
5997
5998 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005999 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006000 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6001
6002 return OK;
6003}
6004
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006005void Camera3Device::PreparerThread::pause() {
6006 ATRACE_CALL();
6007
6008 Mutex::Autolock l(mLock);
6009
6010 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6011 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6012 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6013 int currentMaxCount = mCurrentMaxCount;
6014 mPendingStreams.clear();
6015 mCancelNow = true;
6016 while (mActive) {
6017 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6018 if (res == TIMED_OUT) {
6019 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6020 return;
6021 } else if (res != OK) {
6022 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6023 return;
6024 }
6025 }
6026
6027 //Check whether the prepare thread was able to complete the current
6028 //stream. In case work is still pending emplace it along with the rest
6029 //of the streams in the pending list.
6030 if (currentStream != nullptr) {
6031 if (!mCurrentPrepareComplete) {
6032 pendingStreams.emplace(currentMaxCount, currentStream);
6033 }
6034 }
6035
6036 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6037 for (const auto& it : mPendingStreams) {
6038 it.second->cancelPrepare();
6039 }
6040}
6041
6042status_t Camera3Device::PreparerThread::resume() {
6043 ATRACE_CALL();
6044 status_t res;
6045
6046 Mutex::Autolock l(mLock);
6047 sp<NotificationListener> listener = mListener.promote();
6048
6049 if (mActive) {
6050 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6051 return NO_INIT;
6052 }
6053
6054 auto it = mPendingStreams.begin();
6055 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006056 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006057 if (res == OK) {
6058 if (listener != NULL) {
6059 listener->notifyPrepared(it->second->getId());
6060 }
6061 it = mPendingStreams.erase(it);
6062 } else if (res != NOT_ENOUGH_DATA) {
6063 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6064 res, strerror(-res));
6065 it = mPendingStreams.erase(it);
6066 } else {
6067 it++;
6068 }
6069 }
6070
6071 if (mPendingStreams.empty()) {
6072 return OK;
6073 }
6074
6075 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6076 if (res != OK) {
6077 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6078 __FUNCTION__, res, strerror(-res));
6079 return res;
6080 }
6081 mCancelNow = false;
6082 mActive = true;
6083 ALOGV("%s: Preparer stream started", __FUNCTION__);
6084
6085 return OK;
6086}
6087
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006088status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006089 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006090 Mutex::Autolock l(mLock);
6091
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006092 for (const auto& it : mPendingStreams) {
6093 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006094 }
6095 mPendingStreams.clear();
6096 mCancelNow = true;
6097
6098 return OK;
6099}
6100
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006101void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006102 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006103 Mutex::Autolock l(mLock);
6104 mListener = listener;
6105}
6106
6107bool Camera3Device::PreparerThread::threadLoop() {
6108 status_t res;
6109 {
6110 Mutex::Autolock l(mLock);
6111 if (mCurrentStream == nullptr) {
6112 // End thread if done with work
6113 if (mPendingStreams.empty()) {
6114 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6115 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6116 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6117 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006118 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006119 return false;
6120 }
6121
6122 // Get next stream to prepare
6123 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006124 mCurrentStream = it->second;
6125 mCurrentMaxCount = it->first;
6126 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006127 mPendingStreams.erase(it);
6128 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6129 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6130 } else if (mCancelNow) {
6131 mCurrentStream->cancelPrepare();
6132 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6133 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6134 mCurrentStream.clear();
6135 mCancelNow = false;
6136 return true;
6137 }
6138 }
6139
6140 res = mCurrentStream->prepareNextBuffer();
6141 if (res == NOT_ENOUGH_DATA) return true;
6142 if (res != OK) {
6143 // Something bad happened; try to recover by cancelling prepare and
6144 // signalling listener anyway
6145 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6146 mCurrentStream->getId(), res, strerror(-res));
6147 mCurrentStream->cancelPrepare();
6148 }
6149
6150 // This stream has finished, notify listener
6151 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006152 sp<NotificationListener> listener = mListener.promote();
6153 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006154 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6155 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006156 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006157 }
6158
6159 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6160 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006161 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006162
6163 return true;
6164}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006165
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006166}; // namespace android