blob: 04d363928347d849a1468a5f3d195aaa9c04564c [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Shuzhen Wang5c22c152017-12-31 17:12:25 -080042#include <utility>
43
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080044#include <utils/Log.h>
45#include <utils/Trace.h>
46#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070047#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070048
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080049#include <android/hardware/camera2/ICameraDeviceUser.h>
50
Igor Murashkinff3e31d2013-10-23 16:40:06 -070051#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070052#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "device3/Camera3Device.h"
54#include "device3/Camera3OutputStream.h"
55#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070056#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070057#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070058#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070059#include "utils/CameraThreadState.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080060
61using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080062using namespace android::hardware::camera;
63using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080064
65namespace android {
66
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080067Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080068 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080069 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070070 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070071 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070072 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070073 mUsePartialResult(false),
74 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080075 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070076 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070077 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070078 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070079 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000080 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010081 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
82 mLastTemplateId(-1)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080083{
84 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080085 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080086}
87
88Camera3Device::~Camera3Device()
89{
90 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080091 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -070092 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080093}
94
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080095const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080096 return mId;
97}
98
Emilian Peevbd8c5032018-02-14 23:05:40 +000099status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800100 ATRACE_CALL();
101 Mutex::Autolock il(mInterfaceLock);
102 Mutex::Autolock l(mLock);
103
104 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
105 if (mStatus != STATUS_UNINITIALIZED) {
106 CLOGE("Already initialized!");
107 return INVALID_OPERATION;
108 }
109 if (manager == nullptr) return INVALID_OPERATION;
110
111 sp<ICameraDeviceSession> session;
112 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800113 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800114 /*out*/ &session);
115 ATRACE_END();
116 if (res != OK) {
117 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
118 return res;
119 }
120
Steven Moreland5ff9c912017-03-09 23:13:00 -0800121 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800122 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700123 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800124 session->close();
125 return res;
126 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800127
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700128 std::vector<std::string> physicalCameraIds;
129 bool isLogical = CameraProviderManager::isLogicalCamera(mDeviceInfo, &physicalCameraIds);
130 if (isLogical) {
131 for (auto& physicalId : physicalCameraIds) {
132 res = manager->getCameraCharacteristics(physicalId, &mPhysicalDeviceInfoMap[physicalId]);
133 if (res != OK) {
134 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
135 physicalId.c_str(), strerror(-res), res);
136 session->close();
137 return res;
138 }
139 }
140 }
141
Yifan Hongf79b5542017-04-11 14:44:25 -0700142 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700143 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
144 [&queue](const auto& descriptor) {
145 queue = std::make_shared<RequestMetadataQueue>(descriptor);
146 if (!queue->isValid() || queue->availableToWrite() <= 0) {
147 ALOGE("HAL returns empty request metadata fmq, not use it");
148 queue = nullptr;
149 // don't use the queue onwards.
150 }
151 });
152 if (!requestQueueRet.isOk()) {
153 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
154 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700155 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700156 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700157
158 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700159 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700160 [&resQueue](const auto& descriptor) {
161 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
162 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700163 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700164 resQueue = nullptr;
165 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700166 }
167 });
168 if (!resultQueueRet.isOk()) {
169 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
170 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700171 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700172 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700173 IF_ALOGV() {
174 session->interfaceChain([](
175 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
176 ALOGV("Session interface chain:");
177 for (auto iface : interfaceChain) {
178 ALOGV(" %s", iface.c_str());
179 }
180 });
181 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700182
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700183 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000184 std::string providerType;
185 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000186 mTagMonitor.initialize(mVendorTagId);
187 if (!monitorTags.isEmpty()) {
188 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
189 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800190
191 return initializeCommonLocked();
192}
193
194status_t Camera3Device::initializeCommonLocked() {
195
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700196 /** Start up status tracker thread */
197 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800198 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700199 if (res != OK) {
200 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
201 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800202 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700203 mStatusTracker.clear();
204 return res;
205 }
206
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700207 /** Register in-flight map to the status tracker */
208 mInFlightStatusId = mStatusTracker->addComponent();
209
Zhijun He125684a2015-12-26 15:07:30 -0800210 /** Create buffer manager */
211 mBufferManager = new Camera3BufferManager();
212
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000213 Vector<int32_t> sessionParamKeys;
214 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
215 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
216 if (sessionKeysEntry.count > 0) {
217 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
218 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700219
220 camera_metadata_entry bufMgrMode =
221 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
222 if (bufMgrMode.count > 0) {
223 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
224 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
225 }
226
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700227 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700228 mRequestThread = new RequestThread(
229 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800230 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800231 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700232 SET_ERR_L("Unable to start request queue thread: %s (%d)",
233 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800234 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800235 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800236 return res;
237 }
238
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700239 mPreparerThread = new PreparerThread();
240
Ruben Brunk183f0562015-08-12 12:55:02 -0700241 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800242 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700243 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700244 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700245 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800246
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800247 // Measure the clock domain offset between camera and video/hw_composer
248 camera_metadata_entry timestampSource =
249 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
250 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
251 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
252 mTimestampOffset = getMonoToBoottimeOffset();
253 }
254
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700255 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100256 camera_metadata_entry partialResultsCount =
257 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
258 if (partialResultsCount.count > 0) {
259 mNumPartialResults = partialResultsCount.data.i32[0];
260 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700261 }
262
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700263 camera_metadata_entry configs =
264 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
265 for (uint32_t i = 0; i < configs.count; i += 4) {
266 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
267 configs.data.i32[i + 3] ==
268 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
269 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
270 configs.data.i32[i + 2]));
271 }
272 }
273
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700274 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
275 res = mDistortionMapper.setupStaticInfo(mDeviceInfo);
276 if (res != OK) {
277 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
278 return res;
279 }
280 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800281 return OK;
282}
283
284status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700285 return disconnectImpl();
286}
287
288status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800289 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700290 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800291
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700292 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800293
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700294 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700295 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700296 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700297 {
298 Mutex::Autolock l(mLock);
299 if (mStatus == STATUS_UNINITIALIZED) return res;
300
301 if (mStatus == STATUS_ACTIVE ||
302 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
303 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700304 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700305 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700306 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700307 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700308 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700309 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700310 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
311 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700312 // Continue to close device even in case of error
313 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700314 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800315 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800316
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700317 if (mStatus == STATUS_ERROR) {
318 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700319 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700320
321 if (mStatusTracker != NULL) {
322 mStatusTracker->requestExit();
323 }
324
325 if (mRequestThread != NULL) {
326 mRequestThread->requestExit();
327 }
328
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700329 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
330 for (size_t i = 0; i < mOutputStreams.size(); i++) {
331 streams.push_back(mOutputStreams[i]);
332 }
333 if (mInputStream != nullptr) {
334 streams.push_back(mInputStream);
335 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700336 }
337
338 // Joining done without holding mLock, otherwise deadlocks may ensue
339 // as the threads try to access parent state
340 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
341 // HAL may be in a bad state, so waiting for request thread
342 // (which may be stuck in the HAL processCaptureRequest call)
343 // could be dangerous.
344 mRequestThread->join();
345 }
346
347 if (mStatusTracker != NULL) {
348 mStatusTracker->join();
349 }
350
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800351 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700352 {
353 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800354 mRequestThread.clear();
Emilian Peev2843c362018-09-26 08:49:40 +0100355 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700356 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800357 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700358 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800359
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700360 // Call close without internal mutex held, as the HAL close may need to
361 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800362 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700363
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700364 flushInflightRequests();
365
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700366 {
367 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800368 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700369 mOutputStreams.clear();
370 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700371 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700372 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700373 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700374 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800375
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700376 for (auto& weakStream : streams) {
377 sp<Camera3StreamInterface> stream = weakStream.promote();
378 if (stream != nullptr) {
379 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
380 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
381 }
382 }
383
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700384 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700385 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800386}
387
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700388// For dumping/debugging only -
389// try to acquire a lock a few times, eventually give up to proceed with
390// debug/dump operations
391bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
392 bool gotLock = false;
393 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
394 if (lock.tryLock() == NO_ERROR) {
395 gotLock = true;
396 break;
397 } else {
398 usleep(kDumpSleepDuration);
399 }
400 }
401 return gotLock;
402}
403
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700404Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
405 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100406 const int STREAM_CONFIGURATION_SIZE = 4;
407 const int STREAM_FORMAT_OFFSET = 0;
408 const int STREAM_WIDTH_OFFSET = 1;
409 const int STREAM_HEIGHT_OFFSET = 2;
410 const int STREAM_IS_INPUT_OFFSET = 3;
411 camera_metadata_ro_entry_t availableStreamConfigs =
412 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
413 if (availableStreamConfigs.count == 0 ||
414 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
415 return Size(0, 0);
416 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700417
Emilian Peev08dd2452017-04-06 16:55:14 +0100418 // Get max jpeg size (area-wise).
419 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
420 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
421 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
422 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
423 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
424 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
425 && format == HAL_PIXEL_FORMAT_BLOB &&
426 (width * height > maxJpegWidth * maxJpegHeight)) {
427 maxJpegWidth = width;
428 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700429 }
430 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100431
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700432 return Size(maxJpegWidth, maxJpegHeight);
433}
434
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800435nsecs_t Camera3Device::getMonoToBoottimeOffset() {
436 // try three times to get the clock offset, choose the one
437 // with the minimum gap in measurements.
438 const int tries = 3;
439 nsecs_t bestGap, measured;
440 for (int i = 0; i < tries; ++i) {
441 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
442 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
443 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
444 const nsecs_t gap = tmono2 - tmono;
445 if (i == 0 || gap < bestGap) {
446 bestGap = gap;
447 measured = tbase - ((tmono + tmono2) >> 1);
448 }
449 }
450 return measured;
451}
452
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800453hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
454 int frameworkFormat) {
455 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
456}
457
458DataspaceFlags Camera3Device::mapToHidlDataspace(
459 android_dataspace dataSpace) {
460 return dataSpace;
461}
462
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700463BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100464 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700465 return usage;
466}
467
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800468StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
469 switch (rotation) {
470 case CAMERA3_STREAM_ROTATION_0:
471 return StreamRotation::ROTATION_0;
472 case CAMERA3_STREAM_ROTATION_90:
473 return StreamRotation::ROTATION_90;
474 case CAMERA3_STREAM_ROTATION_180:
475 return StreamRotation::ROTATION_180;
476 case CAMERA3_STREAM_ROTATION_270:
477 return StreamRotation::ROTATION_270;
478 }
479 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
480 return StreamRotation::ROTATION_0;
481}
482
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800483status_t Camera3Device::mapToStreamConfigurationMode(
484 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
485 if (mode == nullptr) return BAD_VALUE;
486 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
487 switch(operationMode) {
488 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
489 *mode = StreamConfigurationMode::NORMAL_MODE;
490 break;
491 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
492 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
493 break;
494 default:
495 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
496 return BAD_VALUE;
497 }
498 } else {
499 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800500 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800501 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800502}
503
504camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
505 switch (status) {
506 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
507 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
508 }
509 return CAMERA3_BUFFER_STATUS_ERROR;
510}
511
512int Camera3Device::mapToFrameworkFormat(
513 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
514 return static_cast<uint32_t>(pixelFormat);
515}
516
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700517android_dataspace Camera3Device::mapToFrameworkDataspace(
518 DataspaceFlags dataSpace) {
519 return static_cast<android_dataspace>(dataSpace);
520}
521
Emilian Peev050f5dc2017-05-18 14:43:56 +0100522uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700523 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700524 return usage;
525}
526
Emilian Peev050f5dc2017-05-18 14:43:56 +0100527uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700528 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700529 return usage;
530}
531
Zhijun Hef7da0962014-04-24 13:27:56 -0700532ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700533 // Get max jpeg size (area-wise).
534 Size maxJpegResolution = getMaxJpegResolution();
535 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800536 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
537 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700538 return BAD_VALUE;
539 }
540
Zhijun Hef7da0962014-04-24 13:27:56 -0700541 // Get max jpeg buffer size
542 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700543 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
544 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800545 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
546 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700547 return BAD_VALUE;
548 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700549 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800550 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700551
552 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700553 float scaleFactor = ((float) (width * height)) /
554 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800555 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
556 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700557 if (jpegBufferSize > maxJpegBufferSize) {
558 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700559 }
560
561 return jpegBufferSize;
562}
563
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700564ssize_t Camera3Device::getPointCloudBufferSize() const {
565 const int FLOATS_PER_POINT=4;
566 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
567 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800568 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
569 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700570 return BAD_VALUE;
571 }
572 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
573 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
574 return maxBytesForPointCloud;
575}
576
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800577ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800578 const int PER_CONFIGURATION_SIZE = 3;
579 const int WIDTH_OFFSET = 0;
580 const int HEIGHT_OFFSET = 1;
581 const int SIZE_OFFSET = 2;
582 camera_metadata_ro_entry rawOpaqueSizes =
583 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800584 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800585 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800586 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
587 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800588 return BAD_VALUE;
589 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700590
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800591 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
592 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
593 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
594 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
595 }
596 }
597
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800598 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
599 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800600 return BAD_VALUE;
601}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700602
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800603status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
604 ATRACE_CALL();
605 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700606
607 // Try to lock, but continue in case of failure (to avoid blocking in
608 // deadlocks)
609 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
610 bool gotLock = tryLockSpinRightRound(mLock);
611
612 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800613 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
614 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700615 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800616 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
617 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700618
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800619 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700620
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800621 String16 templatesOption("-t");
622 int n = args.size();
623 for (int i = 0; i < n; i++) {
624 if (args[i] == templatesOption) {
625 dumpTemplates = true;
626 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000627 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700628 if (i + 1 < n) {
629 String8 monitorTags = String8(args[i + 1]);
630 if (monitorTags == "off") {
631 mTagMonitor.disableMonitoring();
632 } else {
633 mTagMonitor.parseTagsToMonitor(monitorTags);
634 }
635 } else {
636 mTagMonitor.disableMonitoring();
637 }
638 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800639 }
640
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800641 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800642
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800643 const char *status =
644 mStatus == STATUS_ERROR ? "ERROR" :
645 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700646 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
647 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800648 mStatus == STATUS_ACTIVE ? "ACTIVE" :
649 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700650
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800651 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700652 if (mStatus == STATUS_ERROR) {
653 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
654 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800655 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800656 const char *mode =
657 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
658 mOperatingMode == static_cast<int>(
659 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
660 "CUSTOM";
661 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800662
663 if (mInputStream != NULL) {
664 write(fd, lines.string(), lines.size());
665 mInputStream->dump(fd, args);
666 } else {
667 lines.appendFormat(" No input stream.\n");
668 write(fd, lines.string(), lines.size());
669 }
670 for (size_t i = 0; i < mOutputStreams.size(); i++) {
671 mOutputStreams[i]->dump(fd,args);
672 }
673
Zhijun He431503c2016-03-07 17:30:16 -0800674 if (mBufferManager != NULL) {
675 lines = String8(" Camera3 Buffer Manager:\n");
676 write(fd, lines.string(), lines.size());
677 mBufferManager->dump(fd, args);
678 }
Zhijun He125684a2015-12-26 15:07:30 -0800679
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700680 lines = String8(" In-flight requests:\n");
681 if (mInFlightMap.size() == 0) {
682 lines.append(" None\n");
683 } else {
684 for (size_t i = 0; i < mInFlightMap.size(); i++) {
685 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700686 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700687 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800688 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700689 r.numBuffersLeft);
690 }
691 }
692 write(fd, lines.string(), lines.size());
693
Shuzhen Wang686f6442017-06-20 16:16:04 -0700694 if (mRequestThread != NULL) {
695 mRequestThread->dumpCaptureRequestLatency(fd,
696 " ProcessCaptureRequest latency histogram:");
697 }
698
Igor Murashkin1e479c02013-09-06 16:55:14 -0700699 {
700 lines = String8(" Last request sent:\n");
701 write(fd, lines.string(), lines.size());
702
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700703 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700704 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
705 }
706
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800707 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800708 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800709 "TEMPLATE_PREVIEW",
710 "TEMPLATE_STILL_CAPTURE",
711 "TEMPLATE_VIDEO_RECORD",
712 "TEMPLATE_VIDEO_SNAPSHOT",
713 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800714 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800715 };
716
717 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800718 camera_metadata_t *templateRequest = nullptr;
719 mInterface->constructDefaultRequestSettings(
720 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800721 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800722 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800723 lines.append(" Not supported\n");
724 write(fd, lines.string(), lines.size());
725 } else {
726 write(fd, lines.string(), lines.size());
727 dump_indented_camera_metadata(templateRequest,
728 fd, /*verbosity*/2, /*indentation*/8);
729 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800730 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800731 }
732 }
733
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700734 mTagMonitor.dumpMonitoredMetadata(fd);
735
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800736 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800737 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800738 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800739 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800740 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800741
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700742 if (gotLock) mLock.unlock();
743 if (gotInterfaceLock) mInterfaceLock.unlock();
744
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800745 return OK;
746}
747
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700748const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800749 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800750 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
751 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700752 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800753 mStatus == STATUS_ERROR ?
754 "when in error state" : "before init");
755 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700756 if (physicalId.isEmpty()) {
757 return mDeviceInfo;
758 } else {
759 std::string id(physicalId.c_str());
760 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
761 return mPhysicalDeviceInfoMap.at(id);
762 } else {
763 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
764 return mDeviceInfo;
765 }
766 }
767}
768
769const CameraMetadata& Camera3Device::info() const {
770 String8 emptyId;
771 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800772}
773
Jianing Wei90e59c92014-03-12 18:29:36 -0700774status_t Camera3Device::checkStatusOkToCaptureLocked() {
775 switch (mStatus) {
776 case STATUS_ERROR:
777 CLOGE("Device has encountered a serious error");
778 return INVALID_OPERATION;
779 case STATUS_UNINITIALIZED:
780 CLOGE("Device not initialized");
781 return INVALID_OPERATION;
782 case STATUS_UNCONFIGURED:
783 case STATUS_CONFIGURED:
784 case STATUS_ACTIVE:
785 // OK
786 break;
787 default:
788 SET_ERR_L("Unexpected status: %d", mStatus);
789 return INVALID_OPERATION;
790 }
791 return OK;
792}
793
794status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000795 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700796 const std::list<const SurfaceMap> &surfaceMaps,
797 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700798 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700799 if (requestList == NULL) {
800 CLOGE("requestList cannot be NULL.");
801 return BAD_VALUE;
802 }
803
Jianing Weicb0652e2014-03-12 18:29:36 -0700804 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000805 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700806 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
807 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
808 ++metadataIt, ++surfaceMapIt) {
809 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700810 if (newRequest == 0) {
811 CLOGE("Can't create capture request");
812 return BAD_VALUE;
813 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700814
Shuzhen Wang9d066012016-09-30 11:30:20 -0700815 newRequest->mRepeating = repeating;
816
Jianing Weicb0652e2014-03-12 18:29:36 -0700817 // Setup burst Id and request Id
818 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000819 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
820 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700821 CLOGE("RequestID entry exists; but must not be empty in metadata");
822 return BAD_VALUE;
823 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000824 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
825 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700826 } else {
827 CLOGE("RequestID does not exist in metadata");
828 return BAD_VALUE;
829 }
830
Jianing Wei90e59c92014-03-12 18:29:36 -0700831 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700832
833 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700834 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700835 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
836 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
837 return BAD_VALUE;
838 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700839
840 // Setup batch size if this is a high speed video recording request.
841 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
842 auto firstRequest = requestList->begin();
843 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
844 if (outputStream->isVideoStream()) {
845 (*firstRequest)->mBatchSize = requestList->size();
846 break;
847 }
848 }
849 }
850
Jianing Wei90e59c92014-03-12 18:29:36 -0700851 return OK;
852}
853
Jianing Weicb0652e2014-03-12 18:29:36 -0700854status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800856
Emilian Peevaebbe412018-01-15 13:53:24 +0000857 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000859 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700860
Emilian Peevaebbe412018-01-15 13:53:24 +0000861 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700862}
863
Emilian Peevaebbe412018-01-15 13:53:24 +0000864void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700865 std::list<const SurfaceMap>& surfaceMaps,
866 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000867 PhysicalCameraSettingsList requestList;
868 requestList.push_back({std::string(getId().string()), request});
869 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700870
871 SurfaceMap surfaceMap;
872 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
873 // With no surface list passed in, stream and surface will have 1-to-1
874 // mapping. So the surface index is 0 for each stream in the surfaceMap.
875 for (size_t i = 0; i < streams.count; i++) {
876 surfaceMap[streams.data.i32[i]].push_back(0);
877 }
878 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800879}
880
Jianing Wei90e59c92014-03-12 18:29:36 -0700881status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000882 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700883 const std::list<const SurfaceMap> &surfaceMaps,
884 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700885 /*out*/
886 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700887 ATRACE_CALL();
888 Mutex::Autolock il(mInterfaceLock);
889 Mutex::Autolock l(mLock);
890
891 status_t res = checkStatusOkToCaptureLocked();
892 if (res != OK) {
893 // error logged by previous call
894 return res;
895 }
896
897 RequestList requestList;
898
Shuzhen Wang0129d522016-10-30 22:43:41 -0700899 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
900 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700901 if (res != OK) {
902 // error logged by previous call
903 return res;
904 }
905
906 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700907 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700908 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700909 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700910 }
911
912 if (res == OK) {
913 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
914 if (res != OK) {
915 SET_ERR_L("Can't transition to active in %f seconds!",
916 kActiveTimeout/1e9);
917 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800918 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700919 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700920 } else {
921 CLOGE("Cannot queue request. Impossible.");
922 return BAD_VALUE;
923 }
924
925 return res;
926}
927
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700928hardware::Return<void> Camera3Device::requestStreamBuffers(
929 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
930 requestStreamBuffers_cb _hidl_cb) {
931 using hardware::camera::device::V3_5::BufferRequestStatus;
932 using hardware::camera::device::V3_5::StreamBufferRet;
933 using hardware::camera::device::V3_5::StreamBufferRequestError;
934
935 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
936
937 hardware::hidl_vec<StreamBufferRet> bufRets;
938 if (!mUseHalBufManager) {
939 ALOGE("%s: Camera %s does not support HAL buffer management",
940 __FUNCTION__, mId.string());
941 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
942 return hardware::Void();
943 }
944
945 SortedVector<int32_t> streamIds;
946 ssize_t sz = streamIds.setCapacity(bufReqs.size());
947 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
948 ALOGE("%s: failed to allocate memory for %zu buffer requests",
949 __FUNCTION__, bufReqs.size());
950 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
951 return hardware::Void();
952 }
953
954 // Check for repeated streamId
955 for (const auto& bufReq : bufReqs) {
956 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
957 ALOGE("%s: Stream %d appear multiple times in buffer requests",
958 __FUNCTION__, bufReq.streamId);
959 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
960 return hardware::Void();
961 }
962 streamIds.add(bufReq.streamId);
963 }
964
965 // TODO: check we are not configuring streams. If so return FAILED_CONFIGURING
966 // Probably need to hook CameraDeviceClient::beginConfigure and figure something
967 // out for API1 client... maybe grab mLock and check mNeedConfig but then we will
968 // need to wait until mLock is released...
969 // _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
970 // return hardware::Void();
971
972 // TODO: here we start accessing mOutputStreams, might need mLock, but that
973 // might block incoming API calls. Not sure how bad is it.
974 if (bufReqs.size() > mOutputStreams.size()) {
975 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
976 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
977 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
978 return hardware::Void();
979 }
980
981 bufRets.resize(bufReqs.size());
982
983 bool allReqsSucceeds = true;
984 bool oneReqSucceeds = false;
985 for (size_t i = 0; i < bufReqs.size(); i++) {
986 const auto& bufReq = bufReqs[i];
987 auto& bufRet = bufRets[i];
988 int32_t streamId = bufReq.streamId;
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
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001622status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001623 uint32_t width, uint32_t height, int format,
1624 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001625 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001626 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001627 ATRACE_CALL();
1628
1629 if (consumer == nullptr) {
1630 ALOGE("%s: consumer must not be null", __FUNCTION__);
1631 return BAD_VALUE;
1632 }
1633
1634 std::vector<sp<Surface>> consumers;
1635 consumers.push_back(consumer);
1636
1637 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001638 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1639 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001640}
1641
1642status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1643 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1644 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001645 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001646 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001647 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001648
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001649 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001650 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001651 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001652 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001653 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1654 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1655 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001656
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001657 status_t res;
1658 bool wasActive = false;
1659
1660 switch (mStatus) {
1661 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001662 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001663 return INVALID_OPERATION;
1664 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001665 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001666 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001667 case STATUS_UNCONFIGURED:
1668 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001669 // OK
1670 break;
1671 case STATUS_ACTIVE:
1672 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001673 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001674 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001675 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001676 return res;
1677 }
1678 wasActive = true;
1679 break;
1680 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001681 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001682 return INVALID_OPERATION;
1683 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001684 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001685
1686 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001687
Shuzhen Wang0129d522016-10-30 22:43:41 -07001688 if (consumers.size() == 0 && !hasDeferredConsumer) {
1689 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1690 return BAD_VALUE;
1691 }
Zhijun He5d677d12016-05-29 16:52:39 -07001692
Shuzhen Wang0129d522016-10-30 22:43:41 -07001693 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001694 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1695 return BAD_VALUE;
1696 }
1697
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001698 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001699 ssize_t blobBufferSize;
1700 if (dataSpace != HAL_DATASPACE_DEPTH) {
1701 blobBufferSize = getJpegBufferSize(width, height);
1702 if (blobBufferSize <= 0) {
1703 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1704 return BAD_VALUE;
1705 }
1706 } else {
1707 blobBufferSize = getPointCloudBufferSize();
1708 if (blobBufferSize <= 0) {
1709 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1710 return BAD_VALUE;
1711 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001712 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001713 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001714 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001715 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001716 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1717 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1718 if (rawOpaqueBufferSize <= 0) {
1719 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1720 return BAD_VALUE;
1721 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001722 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001723 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001724 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001725 } else if (isShared) {
1726 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1727 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001728 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001729 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001730 newStream = new Camera3OutputStream(mNextStreamId,
1731 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001732 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001733 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001734 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001735 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001736 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001737 }
Emilian Peev40ead602017-09-26 15:46:36 +01001738
1739 size_t consumerCount = consumers.size();
1740 for (size_t i = 0; i < consumerCount; i++) {
1741 int id = newStream->getSurfaceId(consumers[i]);
1742 if (id < 0) {
1743 SET_ERR_L("Invalid surface id");
1744 return BAD_VALUE;
1745 }
1746 if (surfaceIds != nullptr) {
1747 surfaceIds->push_back(id);
1748 }
1749 }
1750
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001751 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001752
Emilian Peev08dd2452017-04-06 16:55:14 +01001753 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001754
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001755 res = mOutputStreams.add(mNextStreamId, newStream);
1756 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001757 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001758 return res;
1759 }
1760
1761 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001762 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001763
1764 // Continue captures if active at start
1765 if (wasActive) {
1766 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001767 // Reuse current operating mode and session parameters for new stream config
1768 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001769 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001770 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1771 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001772 return res;
1773 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001774 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001775 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001776 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001777 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001778}
1779
Emilian Peev710c1422017-08-30 11:19:38 +01001780status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001781 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001782 if (nullptr == streamInfo) {
1783 return BAD_VALUE;
1784 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001785 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001786 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001787
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001788 switch (mStatus) {
1789 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001790 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001791 return INVALID_OPERATION;
1792 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001793 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001794 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001795 case STATUS_UNCONFIGURED:
1796 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001797 case STATUS_ACTIVE:
1798 // OK
1799 break;
1800 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001801 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001802 return INVALID_OPERATION;
1803 }
1804
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001805 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1806 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001807 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001808 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001809 }
1810
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001811 streamInfo->width = stream->getWidth();
1812 streamInfo->height = stream->getHeight();
1813 streamInfo->format = stream->getFormat();
1814 streamInfo->dataSpace = stream->getDataSpace();
1815 streamInfo->formatOverridden = stream->isFormatOverridden();
1816 streamInfo->originalFormat = stream->getOriginalFormat();
1817 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1818 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001819 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001820}
1821
1822status_t Camera3Device::setStreamTransform(int id,
1823 int transform) {
1824 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001825 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001826 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001827
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001828 switch (mStatus) {
1829 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001830 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001831 return INVALID_OPERATION;
1832 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001833 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001834 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001835 case STATUS_UNCONFIGURED:
1836 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001837 case STATUS_ACTIVE:
1838 // OK
1839 break;
1840 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001841 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001842 return INVALID_OPERATION;
1843 }
1844
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001845 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1846 if (stream == nullptr) {
1847 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001848 return BAD_VALUE;
1849 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001850 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001851}
1852
1853status_t Camera3Device::deleteStream(int id) {
1854 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001855 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001856 Mutex::Autolock l(mLock);
1857 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001858
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001859 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001860
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001861 // CameraDevice semantics require device to already be idle before
1862 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001863 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001864 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001865 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001866 }
1867
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001868 if (mStatus == STATUS_ERROR) {
1869 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1870 __FUNCTION__, mId.string());
1871 return -EBUSY;
1872 }
1873
Igor Murashkin2fba5842013-04-22 14:03:54 -07001874 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001875 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001876 if (mInputStream != NULL && id == mInputStream->getId()) {
1877 deletedStream = mInputStream;
1878 mInputStream.clear();
1879 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001880 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001881 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001882 return BAD_VALUE;
1883 }
Zhijun He5f446352014-01-22 09:49:33 -08001884 }
1885
1886 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001887 if (stream != nullptr) {
1888 deletedStream = stream;
1889 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001890 }
1891
1892 // Free up the stream endpoint so that it can be used by some other stream
1893 res = deletedStream->disconnect();
1894 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001895 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001896 // fall through since we want to still list the stream as deleted.
1897 }
1898 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001899 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001900
1901 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001902}
1903
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001904status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001905 ATRACE_CALL();
1906 ALOGV("%s: E", __FUNCTION__);
1907
1908 Mutex::Autolock il(mInterfaceLock);
1909 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001910
Emilian Peev811d2952018-05-25 11:08:40 +01001911 // In case the client doesn't include any session parameter, try a
1912 // speculative configuration using the values from the last cached
1913 // default request.
1914 if (sessionParams.isEmpty() &&
1915 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1916 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1917 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1918 mLastTemplateId);
1919 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1920 operatingMode);
1921 }
1922
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001923 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1924}
1925
1926status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1927 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001928 //Filter out any incoming session parameters
1929 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001930 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1931 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001932 CameraMetadata filteredParams(availableSessionKeys.count);
1933 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1934 filteredParams.getAndLock());
1935 set_camera_metadata_vendor_id(meta, mVendorTagId);
1936 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001937 if (availableSessionKeys.count > 0) {
1938 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1939 camera_metadata_ro_entry entry = params.find(
1940 availableSessionKeys.data.i32[i]);
1941 if (entry.count > 0) {
1942 filteredParams.update(entry);
1943 }
1944 }
1945 }
1946
1947 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001948}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001949
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001950status_t Camera3Device::getInputBufferProducer(
1951 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001952 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001953 Mutex::Autolock il(mInterfaceLock);
1954 Mutex::Autolock l(mLock);
1955
1956 if (producer == NULL) {
1957 return BAD_VALUE;
1958 } else if (mInputStream == NULL) {
1959 return INVALID_OPERATION;
1960 }
1961
1962 return mInputStream->getInputBufferProducer(producer);
1963}
1964
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001965status_t Camera3Device::createDefaultRequest(int templateId,
1966 CameraMetadata *request) {
1967 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001968 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001969
1970 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1971 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001972 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001973 return BAD_VALUE;
1974 }
1975
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001976 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001977
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001978 {
1979 Mutex::Autolock l(mLock);
1980 switch (mStatus) {
1981 case STATUS_ERROR:
1982 CLOGE("Device has encountered a serious error");
1983 return INVALID_OPERATION;
1984 case STATUS_UNINITIALIZED:
1985 CLOGE("Device is not initialized!");
1986 return INVALID_OPERATION;
1987 case STATUS_UNCONFIGURED:
1988 case STATUS_CONFIGURED:
1989 case STATUS_ACTIVE:
1990 // OK
1991 break;
1992 default:
1993 SET_ERR_L("Unexpected status: %d", mStatus);
1994 return INVALID_OPERATION;
1995 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001996
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001997 if (!mRequestTemplateCache[templateId].isEmpty()) {
1998 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001999 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002000 return OK;
2001 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002002 }
2003
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002004 camera_metadata_t *rawRequest;
2005 status_t res = mInterface->constructDefaultRequestSettings(
2006 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002007
2008 {
2009 Mutex::Autolock l(mLock);
2010 if (res == BAD_VALUE) {
2011 ALOGI("%s: template %d is not supported on this camera device",
2012 __FUNCTION__, templateId);
2013 return res;
2014 } else if (res != OK) {
2015 CLOGE("Unable to construct request template %d: %s (%d)",
2016 templateId, strerror(-res), res);
2017 return res;
2018 }
2019
2020 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2021 mRequestTemplateCache[templateId].acquire(rawRequest);
2022
2023 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002024 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002025 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002026 return OK;
2027}
2028
2029status_t Camera3Device::waitUntilDrained() {
2030 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002031 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002032 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002033 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002034
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002035 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002036}
2037
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002038status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002039 switch (mStatus) {
2040 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002041 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002042 ALOGV("%s: Already idle", __FUNCTION__);
2043 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002044 case STATUS_CONFIGURED:
2045 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002046 case STATUS_ERROR:
2047 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002048 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002049 break;
2050 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002051 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002052 return INVALID_OPERATION;
2053 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002054 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2055 maxExpectedDuration);
2056 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002057 if (res != OK) {
2058 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2059 res);
2060 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002061 return res;
2062}
2063
Ruben Brunk183f0562015-08-12 12:55:02 -07002064
2065void Camera3Device::internalUpdateStatusLocked(Status status) {
2066 mStatus = status;
2067 mRecentStatusUpdates.add(mStatus);
2068 mStatusChanged.broadcast();
2069}
2070
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002071void Camera3Device::pauseStateNotify(bool enable) {
2072 Mutex::Autolock il(mInterfaceLock);
2073 Mutex::Autolock l(mLock);
2074
2075 mPauseStateNotify = enable;
2076}
2077
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002078// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002079status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002080 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002081
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002082 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2083 maxExpectedDuration);
2084 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002085 if (res != OK) {
2086 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002087 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002088 }
2089
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002090 return res;
2091}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002092
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002093// Resume after internalPauseAndWaitLocked
2094status_t Camera3Device::internalResumeLocked() {
2095 status_t res;
2096
2097 mRequestThread->setPaused(false);
2098
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002099 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2100 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002101 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2102 if (res != OK) {
2103 SET_ERR_L("Can't transition to active in %f seconds!",
2104 kActiveTimeout/1e9);
2105 }
2106 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002107 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002108}
2109
Ruben Brunk183f0562015-08-12 12:55:02 -07002110status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002111 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002112
2113 size_t startIndex = 0;
2114 if (mStatusWaiters == 0) {
2115 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2116 // this status list
2117 mRecentStatusUpdates.clear();
2118 } else {
2119 // If other threads are waiting on updates to this status list, set the position of the
2120 // first element that this list will check rather than clearing the list.
2121 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002122 }
2123
Ruben Brunk183f0562015-08-12 12:55:02 -07002124 mStatusWaiters++;
2125
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002126 bool stateSeen = false;
2127 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002128 if (active == (mStatus == STATUS_ACTIVE)) {
2129 // Desired state is current
2130 break;
2131 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002132
2133 res = mStatusChanged.waitRelative(mLock, timeout);
2134 if (res != OK) break;
2135
Ruben Brunk183f0562015-08-12 12:55:02 -07002136 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2137 // transitions.
2138 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2139 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2140 __FUNCTION__);
2141
2142 // Encountered desired state since we began waiting
2143 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002144 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2145 stateSeen = true;
2146 break;
2147 }
2148 }
2149 } while (!stateSeen);
2150
Ruben Brunk183f0562015-08-12 12:55:02 -07002151 mStatusWaiters--;
2152
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002153 return res;
2154}
2155
2156
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002157status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002158 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002159 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002160
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002161 if (listener != NULL && mListener != NULL) {
2162 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2163 }
2164 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002165 mRequestThread->setNotificationListener(listener);
2166 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002167
2168 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002169}
2170
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002171bool Camera3Device::willNotify3A() {
2172 return false;
2173}
2174
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002175status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002176 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002177 status_t res;
2178 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002179
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002180 while (mResultQueue.empty()) {
2181 res = mResultSignal.waitRelative(mOutputLock, timeout);
2182 if (res == TIMED_OUT) {
2183 return res;
2184 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002185 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2186 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002187 return res;
2188 }
2189 }
2190 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002191}
2192
Jianing Weicb0652e2014-03-12 18:29:36 -07002193status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002194 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002195 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002196
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002197 if (mResultQueue.empty()) {
2198 return NOT_ENOUGH_DATA;
2199 }
2200
Jianing Weicb0652e2014-03-12 18:29:36 -07002201 if (frame == NULL) {
2202 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2203 return BAD_VALUE;
2204 }
2205
2206 CaptureResult &result = *(mResultQueue.begin());
2207 frame->mResultExtras = result.mResultExtras;
2208 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002209 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002210 mResultQueue.erase(mResultQueue.begin());
2211
2212 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002213}
2214
2215status_t Camera3Device::triggerAutofocus(uint32_t id) {
2216 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002217 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002218
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002219 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2220 // Mix-in this trigger into the next request and only the next request.
2221 RequestTrigger trigger[] = {
2222 {
2223 ANDROID_CONTROL_AF_TRIGGER,
2224 ANDROID_CONTROL_AF_TRIGGER_START
2225 },
2226 {
2227 ANDROID_CONTROL_AF_TRIGGER_ID,
2228 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002229 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002230 };
2231
2232 return mRequestThread->queueTrigger(trigger,
2233 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002234}
2235
2236status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2237 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002238 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002239
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002240 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2241 // Mix-in this trigger into the next request and only the next request.
2242 RequestTrigger trigger[] = {
2243 {
2244 ANDROID_CONTROL_AF_TRIGGER,
2245 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2246 },
2247 {
2248 ANDROID_CONTROL_AF_TRIGGER_ID,
2249 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002250 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002251 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002252
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002253 return mRequestThread->queueTrigger(trigger,
2254 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002255}
2256
2257status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2258 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002259 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002260
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002261 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2262 // Mix-in this trigger into the next request and only the next request.
2263 RequestTrigger trigger[] = {
2264 {
2265 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2266 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2267 },
2268 {
2269 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2270 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002271 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002272 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002273
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002274 return mRequestThread->queueTrigger(trigger,
2275 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002276}
2277
Jianing Weicb0652e2014-03-12 18:29:36 -07002278status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002279 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002280 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002281 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002282
Zhijun He7ef20392014-04-21 16:04:17 -07002283 {
2284 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002285
2286 // b/116514106 "disconnect()" can get called twice for the same device. The
2287 // camera device will not be initialized during the second run.
2288 if (mStatus == STATUS_UNINITIALIZED) {
2289 return OK;
2290 }
2291
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002292 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002293 }
2294
Emilian Peev08dd2452017-04-06 16:55:14 +01002295 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002296}
2297
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002298status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002299 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2300}
2301
2302status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002303 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002304 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002305 Mutex::Autolock il(mInterfaceLock);
2306 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002307
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002308 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2309 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002310 CLOGE("Stream %d does not exist", streamId);
2311 return BAD_VALUE;
2312 }
2313
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002314 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002315 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002316 return BAD_VALUE;
2317 }
2318
2319 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002320 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002321 return BAD_VALUE;
2322 }
2323
Ruben Brunkc78ac262015-08-13 17:58:46 -07002324 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002325}
2326
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002327status_t Camera3Device::tearDown(int streamId) {
2328 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002329 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002330 Mutex::Autolock il(mInterfaceLock);
2331 Mutex::Autolock l(mLock);
2332
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002333 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2334 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002335 CLOGE("Stream %d does not exist", streamId);
2336 return BAD_VALUE;
2337 }
2338
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002339 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2340 CLOGE("Stream %d is a target of a in-progress request", streamId);
2341 return BAD_VALUE;
2342 }
2343
2344 return stream->tearDown();
2345}
2346
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002347status_t Camera3Device::addBufferListenerForStream(int streamId,
2348 wp<Camera3StreamBufferListener> listener) {
2349 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002350 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002351 Mutex::Autolock il(mInterfaceLock);
2352 Mutex::Autolock l(mLock);
2353
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002354 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2355 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002356 CLOGE("Stream %d does not exist", streamId);
2357 return BAD_VALUE;
2358 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002359 stream->addBufferListener(listener);
2360
2361 return OK;
2362}
2363
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002364/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002365 * Methods called by subclasses
2366 */
2367
2368void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002369 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002370 {
2371 // Need mLock to safely update state and synchronize to current
2372 // state of methods in flight.
2373 Mutex::Autolock l(mLock);
2374 // We can get various system-idle notices from the status tracker
2375 // while starting up. Only care about them if we've actually sent
2376 // in some requests recently.
2377 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2378 return;
2379 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002380 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2381 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002382 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002383
2384 // Skip notifying listener if we're doing some user-transparent
2385 // state changes
2386 if (mPauseStateNotify) return;
2387 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002388
2389 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002390 {
2391 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002392 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002393 }
2394 if (idle && listener != NULL) {
2395 listener->notifyIdle();
2396 }
2397}
2398
Shuzhen Wang758c2152017-01-10 18:26:18 -08002399status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002400 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002401 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002402 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2403 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002404
2405 if (surfaceIds == nullptr) {
2406 return BAD_VALUE;
2407 }
2408
Zhijun He5d677d12016-05-29 16:52:39 -07002409 Mutex::Autolock il(mInterfaceLock);
2410 Mutex::Autolock l(mLock);
2411
Shuzhen Wang758c2152017-01-10 18:26:18 -08002412 if (consumers.size() == 0) {
2413 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002414 return BAD_VALUE;
2415 }
2416
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002417 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2418 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002419 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002420 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002421 }
Shuzhen Wang758c2152017-01-10 18:26:18 -08002422 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002423 if (res != OK) {
2424 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2425 return res;
2426 }
2427
Emilian Peev40ead602017-09-26 15:46:36 +01002428 for (auto &consumer : consumers) {
2429 int id = stream->getSurfaceId(consumer);
2430 if (id < 0) {
2431 CLOGE("Invalid surface id!");
2432 return BAD_VALUE;
2433 }
2434 surfaceIds->push_back(id);
2435 }
2436
Shuzhen Wang0129d522016-10-30 22:43:41 -07002437 if (stream->isConsumerConfigurationDeferred()) {
2438 if (!stream->isConfiguring()) {
2439 CLOGE("Stream %d was already fully configured.", streamId);
2440 return INVALID_OPERATION;
2441 }
Zhijun He5d677d12016-05-29 16:52:39 -07002442
Shuzhen Wang0129d522016-10-30 22:43:41 -07002443 res = stream->finishConfiguration();
2444 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002445 // If finishConfiguration fails due to abandoned surface, do not set
2446 // device to error state.
2447 bool isSurfaceAbandoned =
2448 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2449 if (!isSurfaceAbandoned) {
2450 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2451 stream->getId(), strerror(-res), res);
2452 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002453 return res;
2454 }
Zhijun He5d677d12016-05-29 16:52:39 -07002455 }
2456
2457 return OK;
2458}
2459
Emilian Peev40ead602017-09-26 15:46:36 +01002460status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2461 const std::vector<OutputStreamInfo> &outputInfo,
2462 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2463 Mutex::Autolock il(mInterfaceLock);
2464 Mutex::Autolock l(mLock);
2465
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002466 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2467 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002468 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002469 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002470 }
2471
2472 for (const auto &it : removedSurfaceIds) {
2473 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2474 CLOGE("Shared surface still part of a pending request!");
2475 return -EBUSY;
2476 }
2477 }
2478
Emilian Peev40ead602017-09-26 15:46:36 +01002479 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2480 if (res != OK) {
2481 CLOGE("Stream %d failed to update stream (error %d %s) ",
2482 streamId, res, strerror(-res));
2483 if (res == UNKNOWN_ERROR) {
2484 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2485 __FUNCTION__);
2486 }
2487 return res;
2488 }
2489
2490 return res;
2491}
2492
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002493status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2494 Mutex::Autolock il(mInterfaceLock);
2495 Mutex::Autolock l(mLock);
2496
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002497 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2498 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002499 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2500 return BAD_VALUE;
2501 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002502 return stream->dropBuffers(dropping);
2503}
2504
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002505/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002506 * Camera3Device private methods
2507 */
2508
2509sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002510 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002511 ATRACE_CALL();
2512 status_t res;
2513
2514 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002515 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002516
2517 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002518 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002519 if (inputStreams.count > 0) {
2520 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002521 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002522 CLOGE("Request references unknown input stream %d",
2523 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002524 return NULL;
2525 }
2526 // Lazy completion of stream configuration (allocation/registration)
2527 // on first use
2528 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002529 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002530 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002531 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002532 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002533 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002534 return NULL;
2535 }
2536 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002537 // Check if stream prepare is blocking requests.
2538 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002539 CLOGE("Request references an input stream that's being prepared!");
2540 return NULL;
2541 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002542
2543 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002544 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002545 }
2546
2547 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002548 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002549 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002550 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002551 return NULL;
2552 }
2553
2554 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002555 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2556 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002557 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002558 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002559 return NULL;
2560 }
Zhijun He5d677d12016-05-29 16:52:39 -07002561 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002562 auto iter = surfaceMap.find(streams.data.i32[i]);
2563 if (iter != surfaceMap.end()) {
2564 const std::vector<size_t>& surfaces = iter->second;
2565 for (const auto& surface : surfaces) {
2566 if (stream->isConsumerConfigurationDeferred(surface)) {
2567 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2568 "due to deferred consumer", stream->getId(), surface);
2569 return NULL;
2570 }
2571 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002572 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002573 }
2574
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002575 // Lazy completion of stream configuration (allocation/registration)
2576 // on first use
2577 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002578 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002579 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002580 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2581 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002582 return NULL;
2583 }
2584 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002585 // Check if stream prepare is blocking requests.
2586 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002587 CLOGE("Request references an output stream that's being prepared!");
2588 return NULL;
2589 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002590
2591 newRequest->mOutputStreams.push(stream);
2592 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002593 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002594 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002595
2596 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002597}
2598
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002599bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2600 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2601 Size size = mSupportedOpaqueInputSizes[i];
2602 if (size.width == width && size.height == height) {
2603 return true;
2604 }
2605 }
2606
2607 return false;
2608}
2609
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002610void Camera3Device::cancelStreamsConfigurationLocked() {
2611 int res = OK;
2612 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2613 res = mInputStream->cancelConfiguration();
2614 if (res != OK) {
2615 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2616 mInputStream->getId(), strerror(-res), res);
2617 }
2618 }
2619
2620 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002621 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002622 if (outputStream->isConfiguring()) {
2623 res = outputStream->cancelConfiguration();
2624 if (res != OK) {
2625 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2626 outputStream->getId(), strerror(-res), res);
2627 }
2628 }
2629 }
2630
2631 // Return state to that at start of call, so that future configures
2632 // properly clean things up
2633 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2634 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002635
2636 res = mPreparerThread->resume();
2637 if (res != OK) {
2638 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2639 }
2640}
2641
2642bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2643 ATRACE_CALL();
2644 bool ret = false;
2645
2646 Mutex::Autolock il(mInterfaceLock);
2647 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2648
2649 Mutex::Autolock l(mLock);
2650 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2651 if (rc == NO_ERROR) {
2652 mNeedConfig = true;
2653 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2654 if (rc == NO_ERROR) {
2655 ret = true;
2656 mPauseStateNotify = false;
2657 //Moving to active state while holding 'mLock' is important.
2658 //There could be pending calls to 'create-/deleteStream' which
2659 //will trigger another stream configuration while the already
2660 //present streams end up with outstanding buffers that will
2661 //not get drained.
2662 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002663 } else if (rc == DEAD_OBJECT) {
2664 // DEAD_OBJECT can be returned if either the consumer surface is
2665 // abandoned, or the HAL has died.
2666 // - If the HAL has died, configureStreamsLocked call will set
2667 // device to error state,
2668 // - If surface is abandoned, we should not set device to error
2669 // state.
2670 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002671 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002672 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002673 }
2674 } else {
2675 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2676 }
2677
2678 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002679}
2680
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002681status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002682 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002683 ATRACE_CALL();
2684 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002685
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002686 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002687 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002688 return INVALID_OPERATION;
2689 }
2690
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002691 if (operatingMode < 0) {
2692 CLOGE("Invalid operating mode: %d", operatingMode);
2693 return BAD_VALUE;
2694 }
2695
2696 bool isConstrainedHighSpeed =
2697 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2698 operatingMode;
2699
2700 if (mOperatingMode != operatingMode) {
2701 mNeedConfig = true;
2702 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2703 mOperatingMode = operatingMode;
2704 }
2705
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002706 if (!mNeedConfig) {
2707 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2708 return OK;
2709 }
2710
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002711 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2712 // adding a dummy stream instead.
2713 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2714 if (mOutputStreams.size() == 0) {
2715 addDummyStreamLocked();
2716 } else {
2717 tryRemoveDummyStreamLocked();
2718 }
2719
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002720 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002721 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002722
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002723 mPreparerThread->pause();
2724
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002725 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002726 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002727 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2728
2729 Vector<camera3_stream_t*> streams;
2730 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002731 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002732
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002733
2734 if (mInputStream != NULL) {
2735 camera3_stream_t *inputStream;
2736 inputStream = mInputStream->startConfiguration();
2737 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002738 CLOGE("Can't start input stream configuration");
2739 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002740 return INVALID_OPERATION;
2741 }
2742 streams.add(inputStream);
2743 }
2744
2745 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002746
2747 // Don't configure bidi streams twice, nor add them twice to the list
2748 if (mOutputStreams[i].get() ==
2749 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2750
2751 config.num_streams--;
2752 continue;
2753 }
2754
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002755 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002756 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002757 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002758 CLOGE("Can't start output stream configuration");
2759 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002760 return INVALID_OPERATION;
2761 }
2762 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002763
2764 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2765 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002766 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2767 // always occupy the initial entry.
2768 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002769 getJpegBufferSize(outputStream->width, outputStream->height));
2770 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002771 }
2772
2773 config.streams = streams.editArray();
2774
2775 // Do the HAL configuration; will potentially touch stream
2776 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002777
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002778 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002779 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002780 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002781
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002782 if (res == BAD_VALUE) {
2783 // HAL rejected this set of streams as unsupported, clean up config
2784 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002785 CLOGE("Set of requested inputs/outputs not supported by HAL");
2786 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002787 return BAD_VALUE;
2788 } else if (res != OK) {
2789 // Some other kind of error from configure_streams - this is not
2790 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002791 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2792 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002793 return res;
2794 }
2795
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002796 // Finish all stream configuration immediately.
2797 // TODO: Try to relax this later back to lazy completion, which should be
2798 // faster
2799
Igor Murashkin073f8572013-05-02 14:59:28 -07002800 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002801 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002802 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002803 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002804 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002805 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002806 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2807 return DEAD_OBJECT;
2808 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002809 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002810 }
2811 }
2812
2813 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002814 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002815 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002816 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002817 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002818 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002819 outputStream->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) && outputStream->isAbandoned()) {
2822 return DEAD_OBJECT;
2823 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002824 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002825 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002826 }
2827 }
2828
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002829 // Request thread needs to know to avoid using repeat-last-settings protocol
2830 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002831 if (notifyRequestThread) {
2832 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2833 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002834
Zhijun He90f7c372016-08-16 16:19:43 -07002835 char value[PROPERTY_VALUE_MAX];
2836 property_get("camera.fifo.disable", value, "0");
2837 int32_t disableFifo = atoi(value);
2838 if (disableFifo != 1) {
2839 // Boost priority of request thread to SCHED_FIFO.
2840 pid_t requestThreadTid = mRequestThread->getTid();
2841 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002842 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002843 if (res != OK) {
2844 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2845 strerror(-res), res);
2846 } else {
2847 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2848 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002849 }
2850
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002851 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002852 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2853 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2854 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2855 sessionParams.unlock(newSessionParams);
2856 mSessionParams.unlock(currentSessionParams);
2857 if (updateSessionParams) {
2858 mSessionParams = sessionParams;
2859 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002860
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002861 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002862
Ruben Brunk183f0562015-08-12 12:55:02 -07002863 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2864 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002865
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002866 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002867
Zhijun He0a210512014-07-24 13:45:15 -07002868 // tear down the deleted streams after configure streams.
2869 mDeletedStreams.clear();
2870
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002871 auto rc = mPreparerThread->resume();
2872 if (rc != OK) {
2873 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2874 return rc;
2875 }
2876
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002877 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002878}
2879
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002880status_t Camera3Device::addDummyStreamLocked() {
2881 ATRACE_CALL();
2882 status_t res;
2883
2884 if (mDummyStreamId != NO_STREAM) {
2885 // Should never be adding a second dummy stream when one is already
2886 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002887 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2888 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002889 return INVALID_OPERATION;
2890 }
2891
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002892 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002893
2894 sp<Camera3OutputStreamInterface> dummyStream =
2895 new Camera3DummyStream(mNextStreamId);
2896
2897 res = mOutputStreams.add(mNextStreamId, dummyStream);
2898 if (res < 0) {
2899 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2900 return res;
2901 }
2902
2903 mDummyStreamId = mNextStreamId;
2904 mNextStreamId++;
2905
2906 return OK;
2907}
2908
2909status_t Camera3Device::tryRemoveDummyStreamLocked() {
2910 ATRACE_CALL();
2911 status_t res;
2912
2913 if (mDummyStreamId == NO_STREAM) return OK;
2914 if (mOutputStreams.size() == 1) return OK;
2915
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002916 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002917
2918 // Ok, have a dummy stream and there's at least one other output stream,
2919 // so remove the dummy
2920
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002921 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2922 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002923 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2924 return INVALID_OPERATION;
2925 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002926 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002927
2928 // Free up the stream endpoint so that it can be used by some other stream
2929 res = deletedStream->disconnect();
2930 if (res != OK) {
2931 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2932 // fall through since we want to still list the stream as deleted.
2933 }
2934 mDeletedStreams.add(deletedStream);
2935 mDummyStreamId = NO_STREAM;
2936
2937 return res;
2938}
2939
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002940void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002941 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002942 Mutex::Autolock l(mLock);
2943 va_list args;
2944 va_start(args, fmt);
2945
2946 setErrorStateLockedV(fmt, args);
2947
2948 va_end(args);
2949}
2950
2951void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002952 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002953 Mutex::Autolock l(mLock);
2954 setErrorStateLockedV(fmt, args);
2955}
2956
2957void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2958 va_list args;
2959 va_start(args, fmt);
2960
2961 setErrorStateLockedV(fmt, args);
2962
2963 va_end(args);
2964}
2965
2966void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002967 // Print out all error messages to log
2968 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002969 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002970
2971 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002972 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002973
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002974 mErrorCause = errorCause;
2975
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002976 if (mRequestThread != nullptr) {
2977 mRequestThread->setPaused(true);
2978 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002979 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002980
2981 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002982 sp<NotificationListener> listener = mListener.promote();
2983 if (listener != NULL) {
2984 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002985 CaptureResultExtras());
2986 }
2987
2988 // Save stack trace. View by dumping it later.
2989 CameraTraces::saveTrace();
2990 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002991}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002992
2993/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002994 * In-flight request management
2995 */
2996
Jianing Weicb0652e2014-03-12 18:29:36 -07002997status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002998 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002999 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003000 std::set<String8>& physicalCameraIds, bool isStillCapture,
3001 bool isZslCapture) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003002 ATRACE_CALL();
3003 Mutex::Autolock l(mInFlightLock);
3004
3005 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003006 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003007 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003008 if (res < 0) return res;
3009
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003010 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003011 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3012 // avoid a deadlock during reprocess requests.
3013 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003014 if (mStatusTracker != nullptr) {
3015 mStatusTracker->markComponentActive(mInFlightStatusId);
3016 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003017 }
3018
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003019 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003020 return OK;
3021}
3022
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003023void Camera3Device::returnOutputBuffers(
3024 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003025 nsecs_t timestamp, bool timestampIncreasing) {
3026
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003027 for (size_t i = 0; i < numBuffers; i++)
3028 {
3029 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003030 status_t res = stream->returnBuffer(outputBuffers[i], timestamp, timestampIncreasing);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003031 // Note: stream may be deallocated at this point, if this buffer was
3032 // the last reference to it.
3033 if (res != OK) {
3034 ALOGE("Can't return buffer to its stream: %s (%d)",
3035 strerror(-res), res);
3036 }
3037 }
3038}
3039
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003040void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003041 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003042 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003043 mInFlightMap.removeItemsAt(idx, 1);
3044
3045 // Indicate idle inFlightMap to the status tracker
3046 if (mInFlightMap.size() == 0) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003047 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3048 // avoid a deadlock during reprocess requests.
3049 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003050 if (mStatusTracker != nullptr) {
3051 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3052 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003053 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003054 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003055}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003056
3057void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3058
3059 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3060 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3061
3062 nsecs_t sensorTimestamp = request.sensorTimestamp;
3063 nsecs_t shutterTimestamp = request.shutterTimestamp;
3064
3065 // Check if it's okay to remove the request from InFlightMap:
3066 // In the case of a successful request:
3067 // all input and output buffers, all result metadata, shutter callback
3068 // arrived.
3069 // In the case of a unsuccessful request:
3070 // all input and output buffers arrived.
3071 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003072 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003073 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003074 if (request.stillCapture) {
3075 ATRACE_ASYNC_END("still capture", frameNumber);
3076 }
3077
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003078 ATRACE_ASYNC_END("frame capture", frameNumber);
3079
Shuzhen Wang403044a2017-02-26 23:29:04 -08003080 // Sanity check - if sensor timestamp matches shutter timestamp in the
3081 // case of request having callback.
3082 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003083 sensorTimestamp != shutterTimestamp) {
3084 SET_ERR("sensor timestamp (%" PRId64
3085 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3086 sensorTimestamp, frameNumber, shutterTimestamp);
3087 }
3088
3089 // for an unsuccessful request, it may have pending output buffers to
3090 // return.
3091 assert(request.requestStatus != OK ||
3092 request.pendingOutputBuffers.size() == 0);
3093 returnOutputBuffers(request.pendingOutputBuffers.array(),
3094 request.pendingOutputBuffers.size(), 0);
3095
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003096 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003097 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3098 }
3099
3100 // Sanity check - if we have too many in-flight frames, something has
3101 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003102 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003103 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003104 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3105 kInFlightWarnLimitHighSpeed) {
3106 CLOGE("In-flight list too large for high speed configuration: %zu",
3107 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003108 }
3109}
3110
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003111void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003112 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003113 { // First return buffers cached in mInFlightMap
3114 Mutex::Autolock l(mInFlightLock);
3115 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3116 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3117 returnOutputBuffers(request.pendingOutputBuffers.array(),
3118 request.pendingOutputBuffers.size(), 0);
3119 }
3120 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003121 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003122 }
3123
3124 // Then return all inflight buffers not returned by HAL
3125 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3126 mInterface->getInflightBufferKeys(&inflightKeys);
3127
3128 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3129 for (auto& pair : inflightKeys) {
3130 int32_t frameNumber = pair.first;
3131 int32_t streamId = pair.second;
3132 buffer_handle_t* buffer;
3133 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3134 if (res != OK) {
3135 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3136 __FUNCTION__, frameNumber, streamId);
3137 continue;
3138 }
3139
3140 camera3_stream_buffer_t streamBuffer;
3141 streamBuffer.buffer = buffer;
3142 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3143 streamBuffer.acquire_fence = -1;
3144 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003145
3146 // First check if the buffer belongs to deleted stream
3147 bool streamDeleted = false;
3148 for (auto& stream : mDeletedStreams) {
3149 if (streamId == stream->getId()) {
3150 streamDeleted = true;
3151 // Return buffer to deleted stream
3152 camera3_stream* halStream = stream->asHalStream();
3153 streamBuffer.stream = halStream;
3154 switch (halStream->stream_type) {
3155 case CAMERA3_STREAM_OUTPUT:
3156 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
3157 if (res != OK) {
3158 ALOGE("%s: Can't return output buffer for frame %d to"
3159 " stream %d: %s (%d)", __FUNCTION__,
3160 frameNumber, streamId, strerror(-res), res);
3161 }
3162 break;
3163 case CAMERA3_STREAM_INPUT:
3164 res = stream->returnInputBuffer(streamBuffer);
3165 if (res != OK) {
3166 ALOGE("%s: Can't return input buffer for frame %d to"
3167 " stream %d: %s (%d)", __FUNCTION__,
3168 frameNumber, streamId, strerror(-res), res);
3169 }
3170 break;
3171 default: // Bi-direcitonal stream is deprecated
3172 ALOGE("%s: stream %d has unknown stream type %d",
3173 __FUNCTION__, streamId, halStream->stream_type);
3174 break;
3175 }
3176 break;
3177 }
3178 }
3179 if (streamDeleted) {
3180 continue;
3181 }
3182
3183 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003184 if (streamId == inputStreamId) {
3185 streamBuffer.stream = mInputStream->asHalStream();
3186 res = mInputStream->returnInputBuffer(streamBuffer);
3187 if (res != OK) {
3188 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003189 " stream %d: %s (%d)", __FUNCTION__,
3190 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003191 }
3192 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003193 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3194 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003195 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3196 continue;
3197 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003198 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003199 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3200 }
3201 }
3202}
3203
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003204void Camera3Device::insertResultLocked(CaptureResult *result,
3205 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003206 if (result == nullptr) return;
3207
Emilian Peev71c73a22017-03-21 16:35:51 +00003208 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3209 result->mMetadata.getAndLock());
3210 set_camera_metadata_vendor_id(meta, mVendorTagId);
3211 result->mMetadata.unlock(meta);
3212
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003213 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3214 (int32_t*)&frameNumber, 1) != OK) {
3215 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3216 return;
3217 }
3218
3219 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3220 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3221 return;
3222 }
3223
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003224 // Valid result, insert into queue
3225 List<CaptureResult>::iterator queuedResult =
3226 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3227 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3228 ", burstId = %" PRId32, __FUNCTION__,
3229 queuedResult->mResultExtras.requestId,
3230 queuedResult->mResultExtras.frameNumber,
3231 queuedResult->mResultExtras.burstId);
3232
3233 mResultSignal.signal();
3234}
3235
3236
3237void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003238 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003239 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003240 Mutex::Autolock l(mOutputLock);
3241
3242 CaptureResult captureResult;
3243 captureResult.mResultExtras = resultExtras;
3244 captureResult.mMetadata = partialResult;
3245
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003246 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003247}
3248
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003249
3250void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3251 CaptureResultExtras &resultExtras,
3252 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003253 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003254 bool reprocess,
3255 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003256 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003257 if (pendingMetadata.isEmpty())
3258 return;
3259
3260 Mutex::Autolock l(mOutputLock);
3261
3262 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003263 if (reprocess) {
3264 if (frameNumber < mNextReprocessResultFrameNumber) {
3265 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003266 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003267 frameNumber, mNextReprocessResultFrameNumber);
3268 return;
3269 }
3270 mNextReprocessResultFrameNumber = frameNumber + 1;
3271 } else {
3272 if (frameNumber < mNextResultFrameNumber) {
3273 SET_ERR("Out-of-order capture result metadata submitted! "
3274 "(got frame number %d, expecting %d)",
3275 frameNumber, mNextResultFrameNumber);
3276 return;
3277 }
3278 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003279 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003280
3281 CaptureResult captureResult;
3282 captureResult.mResultExtras = resultExtras;
3283 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003284 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003285
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003286 // Append any previous partials to form a complete result
3287 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3288 captureResult.mMetadata.append(collectedPartialResult);
3289 }
3290
3291 captureResult.mMetadata.sort();
3292
3293 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003294 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3295 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003296 SET_ERR("No timestamp provided by HAL for frame %d!",
3297 frameNumber);
3298 return;
3299 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003300 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3301 camera_metadata_entry timestamp =
3302 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3303 if (timestamp.count == 0) {
3304 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3305 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3306 return;
3307 }
3308 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003309
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003310 // Fix up some result metadata to account for HAL-level distortion correction
3311 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3312 if (res != OK) {
3313 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3314 frameNumber, strerror(res), res);
3315 return;
3316 }
3317
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003318 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3319 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3320
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003321 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003322}
3323
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003324/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003325 * Camera HAL device callback methods
3326 */
3327
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003328void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003329 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003330
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003331 status_t res;
3332
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003333 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003334 if (result->result == NULL && result->num_output_buffers == 0 &&
3335 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003336 SET_ERR("No result data provided by HAL for frame %d",
3337 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003338 return;
3339 }
Zhijun He204e3292014-07-14 17:09:23 -07003340
Zhijun He204e3292014-07-14 17:09:23 -07003341 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003342 result->result != NULL &&
3343 result->partial_result != 1) {
3344 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3345 " if partial result is not supported",
3346 frameNumber, result->partial_result);
3347 return;
3348 }
3349
3350 bool isPartialResult = false;
3351 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003352 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003353
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003354 // Get shutter timestamp and resultExtras from list of in-flight requests,
3355 // where it was added by the shutter notification for this frame. If the
3356 // shutter timestamp isn't received yet, append the output buffers to the
3357 // in-flight request and they will be returned when the shutter timestamp
3358 // arrives. Update the in-flight status and remove the in-flight entry if
3359 // all result data and shutter timestamp have been received.
3360 nsecs_t shutterTimestamp = 0;
3361
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003362 {
3363 Mutex::Autolock l(mInFlightLock);
3364 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3365 if (idx == NAME_NOT_FOUND) {
3366 SET_ERR("Unknown frame number for capture result: %d",
3367 frameNumber);
3368 return;
3369 }
3370 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003371 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3372 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003373 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003374 __FUNCTION__, request.resultExtras.requestId,
3375 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003376 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003377 // Always update the partial count to the latest one if it's not 0
3378 // (buffers only). When framework aggregates adjacent partial results
3379 // into one, the latest partial count will be used.
3380 if (result->partial_result != 0)
3381 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003382
3383 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003384 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003385 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3386 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3387 " the range of [1, %d] when metadata is included in the result",
3388 frameNumber, result->partial_result, mNumPartialResults);
3389 return;
3390 }
3391 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003392 if (isPartialResult && result->num_physcam_metadata) {
3393 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3394 " physical camera result", frameNumber);
3395 return;
3396 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003397 if (isPartialResult) {
3398 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003399 }
3400
Shuzhen Wang4a472662017-02-26 23:29:04 -08003401 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003402 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003403 sendPartialCaptureResult(result->result, request.resultExtras,
3404 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003405 }
3406 }
3407
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003408 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003409 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003410
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003411 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003412 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003413 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3414 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3415 request.physicalCameraIds.size(), result->num_physcam_metadata);
3416 return;
3417 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003418 if (request.haveResultMetadata) {
3419 SET_ERR("Called multiple times with metadata for frame %d",
3420 frameNumber);
3421 return;
3422 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003423 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3424 String8 physicalId(result->physcam_ids[i]);
3425 std::set<String8>::iterator cameraIdIter =
3426 request.physicalCameraIds.find(physicalId);
3427 if (cameraIdIter != request.physicalCameraIds.end()) {
3428 request.physicalCameraIds.erase(cameraIdIter);
3429 } else {
3430 SET_ERR("Total result for frame %d has already returned for camera %s",
3431 frameNumber, physicalId.c_str());
3432 return;
3433 }
3434 }
Zhijun He204e3292014-07-14 17:09:23 -07003435 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003436 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003437 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003438 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003439 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003440 request.haveResultMetadata = true;
3441 }
3442
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003443 uint32_t numBuffersReturned = result->num_output_buffers;
3444 if (result->input_buffer != NULL) {
3445 if (hasInputBufferInRequest) {
3446 numBuffersReturned += 1;
3447 } else {
3448 ALOGW("%s: Input buffer should be NULL if there is no input"
3449 " buffer sent in the request",
3450 __FUNCTION__);
3451 }
3452 }
3453 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003454 if (request.numBuffersLeft < 0) {
3455 SET_ERR("Too many buffers returned for frame %d",
3456 frameNumber);
3457 return;
3458 }
3459
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003460 camera_metadata_ro_entry_t entry;
3461 res = find_camera_metadata_ro_entry(result->result,
3462 ANDROID_SENSOR_TIMESTAMP, &entry);
3463 if (res == OK && entry.count == 1) {
3464 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003465 }
3466
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003467 // If shutter event isn't received yet, append the output buffers to
3468 // the in-flight request. Otherwise, return the output buffers to
3469 // streams.
3470 if (shutterTimestamp == 0) {
3471 request.pendingOutputBuffers.appendArray(result->output_buffers,
3472 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003473 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003474 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003475 returnOutputBuffers(result->output_buffers,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003476 result->num_output_buffers, shutterTimestamp, timestampIncreasing);
Igor Murashkind2c90692013-04-02 12:32:32 -07003477 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003478
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003479 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003480 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3481 CameraMetadata physicalMetadata;
3482 physicalMetadata.append(result->physcam_metadata[i]);
3483 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3484 physicalMetadata});
3485 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003486 if (shutterTimestamp == 0) {
3487 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003488 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003489 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003490 CameraMetadata metadata;
3491 metadata = result->result;
3492 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003493 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003494 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003495 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003496 }
3497
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003498 removeInFlightRequestIfReadyLocked(idx);
3499 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003500
Zhijun Hef0d962a2014-06-30 10:24:11 -07003501 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003502 if (hasInputBufferInRequest) {
3503 Camera3Stream *stream =
3504 Camera3Stream::cast(result->input_buffer->stream);
3505 res = stream->returnInputBuffer(*(result->input_buffer));
3506 // Note: stream may be deallocated at this point, if this buffer was the
3507 // last reference to it.
3508 if (res != OK) {
3509 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3510 " its stream:%s (%d)", __FUNCTION__,
3511 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003512 }
3513 } else {
3514 ALOGW("%s: Input buffer should be NULL if there is no input"
3515 " buffer sent in the request, skipping input buffer return.",
3516 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003517 }
3518 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003519}
3520
3521void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003522 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003523 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003524 {
3525 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003526 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003527 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003528
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003529 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003530 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003531 return;
3532 }
3533
3534 switch (msg->type) {
3535 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003536 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003537 break;
3538 }
3539 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003540 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003541 break;
3542 }
3543 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003544 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003545 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003546 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003547}
3548
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003549void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003550 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003551 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003552 // Map camera HAL error codes to ICameraDeviceCallback error codes
3553 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003554 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003555 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003556 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003557 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003558 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003559 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003560 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003561 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003562 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003563 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003564 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003565 };
3566
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003567 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003568 ((msg.error_code >= 0) &&
3569 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3570 halErrorMap[msg.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
3573 int streamId = 0;
3574 if (msg.error_stream != NULL) {
3575 Camera3Stream *stream =
3576 Camera3Stream::cast(msg.error_stream);
3577 streamId = stream->getId();
3578 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003579 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3580 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003581 streamId, msg.error_code);
3582
3583 CaptureResultExtras resultExtras;
3584 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003585 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003586 // SET_ERR calls notifyError
3587 SET_ERR("Camera HAL reported serious device error");
3588 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003589 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3590 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3591 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003592 {
3593 Mutex::Autolock l(mInFlightLock);
3594 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3595 if (idx >= 0) {
3596 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3597 r.requestStatus = msg.error_code;
3598 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003599 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3600 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3601 errorCode) {
3602 r.skipResultMetadata = true;
3603 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003604 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3605 errorCode) {
3606 // In case of missing result check whether the buffers
3607 // returned. If they returned, then remove inflight
3608 // request.
3609 removeInFlightRequestIfReadyLocked(idx);
3610 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003611 } else {
3612 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003613 ALOGE("Camera %s: %s: cannot find in-flight request on "
3614 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003615 resultExtras.frameNumber);
3616 }
3617 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003618 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003619 if (listener != NULL) {
3620 listener->notifyError(errorCode, resultExtras);
3621 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003622 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003623 }
3624 break;
3625 default:
3626 // SET_ERR calls notifyError
3627 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3628 break;
3629 }
3630}
3631
3632void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003633 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003634 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003635 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003636
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003637 // Set timestamp for the request in the in-flight tracking
3638 // and get the request ID to send upstream
3639 {
3640 Mutex::Autolock l(mInFlightLock);
3641 idx = mInFlightMap.indexOfKey(msg.frame_number);
3642 if (idx >= 0) {
3643 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003644
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003645 // Verify ordering of shutter notifications
3646 {
3647 Mutex::Autolock l(mOutputLock);
3648 // TODO: need to track errors for tighter bounds on expected frame number.
3649 if (r.hasInputBuffer) {
3650 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3651 SET_ERR("Shutter notification out-of-order. Expected "
3652 "notification for frame %d, got frame %d",
3653 mNextReprocessShutterFrameNumber, msg.frame_number);
3654 return;
3655 }
3656 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3657 } else {
3658 if (msg.frame_number < mNextShutterFrameNumber) {
3659 SET_ERR("Shutter notification out-of-order. Expected "
3660 "notification for frame %d, got frame %d",
3661 mNextShutterFrameNumber, msg.frame_number);
3662 return;
3663 }
3664 mNextShutterFrameNumber = msg.frame_number + 1;
3665 }
3666 }
3667
Shuzhen Wang4a472662017-02-26 23:29:04 -08003668 r.shutterTimestamp = msg.timestamp;
3669 if (r.hasCallback) {
3670 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003671 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003672 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003673 // Call listener, if any
3674 if (listener != NULL) {
3675 listener->notifyShutter(r.resultExtras, msg.timestamp);
3676 }
3677 // send pending result and buffers
3678 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3679 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003680 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003681 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003682 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003683 returnOutputBuffers(r.pendingOutputBuffers.array(),
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003684 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003685 r.pendingOutputBuffers.clear();
3686
3687 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003688 }
3689 }
3690 if (idx < 0) {
3691 SET_ERR("Shutter notification for non-existent frame number %d",
3692 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003693 }
3694}
3695
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003696CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003697 ALOGV("%s", __FUNCTION__);
3698
Igor Murashkin1e479c02013-09-06 16:55:14 -07003699 CameraMetadata retVal;
3700
3701 if (mRequestThread != NULL) {
3702 retVal = mRequestThread->getLatestRequest();
3703 }
3704
Igor Murashkin1e479c02013-09-06 16:55:14 -07003705 return retVal;
3706}
3707
Jianing Weicb0652e2014-03-12 18:29:36 -07003708
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003709void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3710 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3711 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3712}
3713
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003714/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003715 * HalInterface inner class methods
3716 */
3717
Yifan Hongf79b5542017-04-11 14:44:25 -07003718Camera3Device::HalInterface::HalInterface(
3719 sp<ICameraDeviceSession> &session,
3720 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003721 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003722 mRequestMetadataQueue(queue) {
3723 // Check with hardware service manager if we can downcast these interfaces
3724 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003725 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3726 if (castResult_3_5.isOk()) {
3727 mHidlSession_3_5 = castResult_3_5;
3728 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003729 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3730 if (castResult_3_4.isOk()) {
3731 mHidlSession_3_4 = castResult_3_4;
3732 }
3733 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3734 if (castResult_3_3.isOk()) {
3735 mHidlSession_3_3 = castResult_3_3;
3736 }
3737}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003738
Emilian Peev31abd0a2017-05-11 18:37:46 +01003739Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003740
3741Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003742 mHidlSession(other.mHidlSession),
3743 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003744
3745bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003746 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003747}
3748
3749void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003750 mHidlSession_3_4.clear();
3751 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003752 mHidlSession.clear();
3753}
3754
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003755bool Camera3Device::HalInterface::supportBatchRequest() {
3756 return mHidlSession != nullptr;
3757}
3758
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003759status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3760 camera3_request_template_t templateId,
3761 /*out*/ camera_metadata_t **requestTemplate) {
3762 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3763 if (!valid()) return INVALID_OPERATION;
3764 status_t res = OK;
3765
Emilian Peev31abd0a2017-05-11 18:37:46 +01003766 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003767
3768 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003769 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003770 status = s;
3771 if (status == common::V1_0::Status::OK) {
3772 const camera_metadata *r =
3773 reinterpret_cast<const camera_metadata_t*>(request.data());
3774 size_t expectedSize = request.size();
3775 int ret = validate_camera_metadata_structure(r, &expectedSize);
3776 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3777 *requestTemplate = clone_camera_metadata(r);
3778 if (*requestTemplate == nullptr) {
3779 ALOGE("%s: Unable to clone camera metadata received from HAL",
3780 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003781 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003782 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003783 } else {
3784 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3785 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003786 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003787 }
3788 };
3789 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003790 RequestTemplate id;
3791 switch (templateId) {
3792 case CAMERA3_TEMPLATE_PREVIEW:
3793 id = RequestTemplate::PREVIEW;
3794 break;
3795 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3796 id = RequestTemplate::STILL_CAPTURE;
3797 break;
3798 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3799 id = RequestTemplate::VIDEO_RECORD;
3800 break;
3801 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3802 id = RequestTemplate::VIDEO_SNAPSHOT;
3803 break;
3804 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3805 id = RequestTemplate::ZERO_SHUTTER_LAG;
3806 break;
3807 case CAMERA3_TEMPLATE_MANUAL:
3808 id = RequestTemplate::MANUAL;
3809 break;
3810 default:
3811 // Unknown template ID, or this HAL is too old to support it
3812 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003813 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003814 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003815
Emilian Peev31abd0a2017-05-11 18:37:46 +01003816 if (!err.isOk()) {
3817 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3818 res = DEAD_OBJECT;
3819 } else {
3820 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003821 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003822
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003823 return res;
3824}
3825
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003826status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003827 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003828 ATRACE_NAME("CameraHal::configureStreams");
3829 if (!valid()) return INVALID_OPERATION;
3830 status_t res = OK;
3831
Emilian Peev31abd0a2017-05-11 18:37:46 +01003832 // Convert stream config to HIDL
3833 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003834 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3835 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3836 requestedConfiguration3_2.streams.resize(config->num_streams);
3837 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003838 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003839 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3840 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003841 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003842
Emilian Peev31abd0a2017-05-11 18:37:46 +01003843 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3844 cam3stream->setBufferFreedListener(this);
3845 int streamId = cam3stream->getId();
3846 StreamType streamType;
3847 switch (src->stream_type) {
3848 case CAMERA3_STREAM_OUTPUT:
3849 streamType = StreamType::OUTPUT;
3850 break;
3851 case CAMERA3_STREAM_INPUT:
3852 streamType = StreamType::INPUT;
3853 break;
3854 default:
3855 ALOGE("%s: Stream %d: Unsupported stream type %d",
3856 __FUNCTION__, streamId, config->streams[i]->stream_type);
3857 return BAD_VALUE;
3858 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003859 dst3_2.id = streamId;
3860 dst3_2.streamType = streamType;
3861 dst3_2.width = src->width;
3862 dst3_2.height = src->height;
3863 dst3_2.format = mapToPixelFormat(src->format);
3864 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3865 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3866 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3867 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003868 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003869 if (src->physical_camera_id != nullptr) {
3870 dst3_4.physicalCameraId = src->physical_camera_id;
3871 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003872
3873 activeStreams.insert(streamId);
3874 // Create Buffer ID map if necessary
3875 if (mBufferIdMaps.count(streamId) == 0) {
3876 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3877 }
3878 }
3879 // remove BufferIdMap for deleted streams
3880 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3881 int streamId = it->first;
3882 bool active = activeStreams.count(streamId) > 0;
3883 if (!active) {
3884 it = mBufferIdMaps.erase(it);
3885 } else {
3886 ++it;
3887 }
3888 }
3889
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003890 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003891 res = mapToStreamConfigurationMode(
3892 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003893 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003894 if (res != OK) {
3895 return res;
3896 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003897 requestedConfiguration3_2.operationMode = operationMode;
3898 requestedConfiguration3_4.operationMode = operationMode;
3899 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003900 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3901 get_camera_metadata_size(sessionParams));
3902
Emilian Peev31abd0a2017-05-11 18:37:46 +01003903 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003904 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003905 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003906
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003907 // See if we have v3.4 or v3.3 HAL
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003908 if (mHidlSession_3_4 != nullptr) {
3909 // We do; use v3.4 for the call
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003910 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003911 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003912 auto err = mHidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003913 [&status, &finalConfiguration3_4]
3914 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3915 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003916 status = s;
3917 });
3918 if (!err.isOk()) {
3919 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3920 return DEAD_OBJECT;
3921 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003922 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3923 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3924 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3925 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003926 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003927 // We do; use v3.3 for the call
3928 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003929 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003930 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003931 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003932 finalConfiguration = halConfiguration;
3933 status = s;
3934 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003935 if (!err.isOk()) {
3936 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3937 return DEAD_OBJECT;
3938 }
3939 } else {
3940 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3941 ALOGV("%s: v3.2 device found", __FUNCTION__);
3942 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003943 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003944 [&status, &finalConfiguration_3_2]
3945 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3946 finalConfiguration_3_2 = halConfiguration;
3947 status = s;
3948 });
3949 if (!err.isOk()) {
3950 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3951 return DEAD_OBJECT;
3952 }
3953 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3954 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3955 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3956 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003957 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003958 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003959 }
3960
3961 if (status != common::V1_0::Status::OK ) {
3962 return CameraProviderManager::mapToStatusT(status);
3963 }
3964
3965 // And convert output stream configuration from HIDL
3966
3967 for (size_t i = 0; i < config->num_streams; i++) {
3968 camera3_stream_t *dst = config->streams[i];
3969 int streamId = Camera3Stream::cast(dst)->getId();
3970
3971 // Start scan at i, with the assumption that the stream order matches
3972 size_t realIdx = i;
3973 bool found = false;
3974 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003975 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003976 found = true;
3977 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003978 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003979 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3980 }
3981 if (!found) {
3982 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3983 __FUNCTION__, streamId);
3984 return INVALID_OPERATION;
3985 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003986 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003987
Emilian Peev710c1422017-08-30 11:19:38 +01003988 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3989 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003990 dstStream->setDataSpaceOverride(false);
3991 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3992 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3993
Emilian Peev31abd0a2017-05-11 18:37:46 +01003994 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3995 if (dst->format != overrideFormat) {
3996 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3997 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003998 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003999 if (dst->data_space != overrideDataSpace) {
4000 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4001 streamId, dst->format);
4002 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004003 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004004 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004005 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4006
Emilian Peev31abd0a2017-05-11 18:37:46 +01004007 // Override allowed with IMPLEMENTATION_DEFINED
4008 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004009 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004010 }
4011
Emilian Peev31abd0a2017-05-11 18:37:46 +01004012 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004013 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004014 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004015 __FUNCTION__, streamId);
4016 return INVALID_OPERATION;
4017 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004018 dstStream->setUsage(
4019 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004020 } else {
4021 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004022 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004023 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4024 __FUNCTION__, streamId);
4025 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004026 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004027 dstStream->setUsage(
4028 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004029 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004030 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004031 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004032
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004033 return res;
4034}
4035
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004036void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
4037 /*out*/device::V3_2::CaptureRequest* captureRequest,
4038 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004039 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004040 if (captureRequest == nullptr || handlesCreated == nullptr) {
4041 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4042 __FUNCTION__, captureRequest, handlesCreated);
4043 return;
4044 }
4045
4046 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004047
4048 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004049
4050 {
4051 std::lock_guard<std::mutex> lock(mInflightLock);
4052 if (request->input_buffer != nullptr) {
4053 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4054 buffer_handle_t buf = *(request->input_buffer->buffer);
4055 auto pair = getBufferId(buf, streamId);
4056 bool isNewBuffer = pair.first;
4057 uint64_t bufferId = pair.second;
4058 captureRequest->inputBuffer.streamId = streamId;
4059 captureRequest->inputBuffer.bufferId = bufferId;
4060 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4061 captureRequest->inputBuffer.status = BufferStatus::OK;
4062 native_handle_t *acquireFence = nullptr;
4063 if (request->input_buffer->acquire_fence != -1) {
4064 acquireFence = native_handle_create(1,0);
4065 acquireFence->data[0] = request->input_buffer->acquire_fence;
4066 handlesCreated->push_back(acquireFence);
4067 }
4068 captureRequest->inputBuffer.acquireFence = acquireFence;
4069 captureRequest->inputBuffer.releaseFence = nullptr;
4070
4071 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4072 request->input_buffer->buffer,
4073 request->input_buffer->acquire_fence);
4074 } else {
4075 captureRequest->inputBuffer.streamId = -1;
4076 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4077 }
4078
4079 captureRequest->outputBuffers.resize(request->num_output_buffers);
4080 for (size_t i = 0; i < request->num_output_buffers; i++) {
4081 const camera3_stream_buffer_t *src = request->output_buffers + i;
4082 StreamBuffer &dst = captureRequest->outputBuffers[i];
4083 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
4084 buffer_handle_t buf = *(src->buffer);
4085 auto pair = getBufferId(buf, streamId);
4086 bool isNewBuffer = pair.first;
4087 dst.streamId = streamId;
4088 dst.bufferId = pair.second;
4089 dst.buffer = isNewBuffer ? buf : nullptr;
4090 dst.status = BufferStatus::OK;
4091 native_handle_t *acquireFence = nullptr;
4092 if (src->acquire_fence != -1) {
4093 acquireFence = native_handle_create(1,0);
4094 acquireFence->data[0] = src->acquire_fence;
4095 handlesCreated->push_back(acquireFence);
4096 }
4097 dst.acquireFence = acquireFence;
4098 dst.releaseFence = nullptr;
4099
4100 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4101 src->buffer, src->acquire_fence);
4102 }
4103 }
4104}
4105
4106status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4107 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4108 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4109 if (!valid()) return INVALID_OPERATION;
4110
Emilian Peevaebbe412018-01-15 13:53:24 +00004111 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4112 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4113 if (castResult_3_4.isOk()) {
4114 hidlSession_3_4 = castResult_3_4;
4115 }
4116
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004117 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004118 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004119 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004120 if (hidlSession_3_4 != nullptr) {
4121 captureRequests_3_4.resize(batchSize);
4122 } else {
4123 captureRequests.resize(batchSize);
4124 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004125 std::vector<native_handle_t*> handlesCreated;
4126
4127 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004128 if (hidlSession_3_4 != nullptr) {
4129 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
4130 /*out*/&handlesCreated);
4131 } else {
4132 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
4133 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004134 }
4135
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004136 std::vector<device::V3_2::BufferCache> cachesToRemove;
4137 {
4138 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4139 for (auto& pair : mFreedBuffers) {
4140 // The stream might have been removed since onBufferFreed
4141 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4142 cachesToRemove.push_back({pair.first, pair.second});
4143 }
4144 }
4145 mFreedBuffers.clear();
4146 }
4147
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004148 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4149 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004150
4151 // Write metadata to FMQ.
4152 for (size_t i = 0; i < batchSize; i++) {
4153 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004154 device::V3_2::CaptureRequest* captureRequest;
4155 if (hidlSession_3_4 != nullptr) {
4156 captureRequest = &captureRequests_3_4[i].v3_2;
4157 } else {
4158 captureRequest = &captureRequests[i];
4159 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004160
4161 if (request->settings != nullptr) {
4162 size_t settingsSize = get_camera_metadata_size(request->settings);
4163 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4164 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4165 captureRequest->settings.resize(0);
4166 captureRequest->fmqSettingsSize = settingsSize;
4167 } else {
4168 if (mRequestMetadataQueue != nullptr) {
4169 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4170 }
4171 captureRequest->settings.setToExternal(
4172 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4173 get_camera_metadata_size(request->settings));
4174 captureRequest->fmqSettingsSize = 0u;
4175 }
4176 } else {
4177 // A null request settings maps to a size-0 CameraMetadata
4178 captureRequest->settings.resize(0);
4179 captureRequest->fmqSettingsSize = 0u;
4180 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004181
4182 if (hidlSession_3_4 != nullptr) {
4183 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4184 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004185 if (request->physcam_settings != nullptr) {
4186 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4187 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4188 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4189 settingsSize)) {
4190 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4191 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4192 settingsSize;
4193 } else {
4194 if (mRequestMetadataQueue != nullptr) {
4195 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4196 }
4197 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4198 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4199 request->physcam_settings[j])),
4200 get_camera_metadata_size(request->physcam_settings[j]));
4201 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004202 }
Emilian Peev00420d22018-02-05 21:33:13 +00004203 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004204 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004205 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004206 }
4207 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4208 request->physcam_id[j];
4209 }
4210 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004211 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004212
4213 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004214 auto resultCallback =
4215 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4216 status = s;
4217 *numRequestProcessed = n;
4218 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004219 if (hidlSession_3_4 != nullptr) {
4220 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004221 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004222 } else {
4223 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004224 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004225 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004226 if (!err.isOk()) {
4227 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4228 return DEAD_OBJECT;
4229 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004230 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4231 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4232 __FUNCTION__, *numRequestProcessed, batchSize);
4233 status = common::V1_0::Status::INTERNAL_ERROR;
4234 }
4235
4236 for (auto& handle : handlesCreated) {
4237 native_handle_delete(handle);
4238 }
4239 return CameraProviderManager::mapToStatusT(status);
4240}
4241
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004242status_t Camera3Device::HalInterface::processCaptureRequest(
4243 camera3_capture_request_t *request) {
4244 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004245 if (!valid()) return INVALID_OPERATION;
4246 status_t res = OK;
4247
Emilian Peev31abd0a2017-05-11 18:37:46 +01004248 uint32_t numRequestProcessed = 0;
4249 std::vector<camera3_capture_request_t*> requests(1);
4250 requests[0] = request;
4251 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4252
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004253 return res;
4254}
4255
4256status_t Camera3Device::HalInterface::flush() {
4257 ATRACE_NAME("CameraHal::flush");
4258 if (!valid()) return INVALID_OPERATION;
4259 status_t res = OK;
4260
Emilian Peev31abd0a2017-05-11 18:37:46 +01004261 auto err = mHidlSession->flush();
4262 if (!err.isOk()) {
4263 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4264 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004265 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004266 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004267 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004268
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004269 return res;
4270}
4271
Emilian Peev31abd0a2017-05-11 18:37:46 +01004272status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004273 ATRACE_NAME("CameraHal::dump");
4274 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004275
Emilian Peev31abd0a2017-05-11 18:37:46 +01004276 // Handled by CameraProviderManager::dump
4277
4278 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004279}
4280
4281status_t Camera3Device::HalInterface::close() {
4282 ATRACE_NAME("CameraHal::close()");
4283 if (!valid()) return INVALID_OPERATION;
4284 status_t res = OK;
4285
Emilian Peev31abd0a2017-05-11 18:37:46 +01004286 auto err = mHidlSession->close();
4287 // Interface will be dead shortly anyway, so don't log errors
4288 if (!err.isOk()) {
4289 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004290 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004291
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004292 return res;
4293}
4294
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004295void Camera3Device::HalInterface::getInflightBufferKeys(
4296 std::vector<std::pair<int32_t, int32_t>>* out) {
4297 std::lock_guard<std::mutex> lock(mInflightLock);
4298 out->clear();
4299 out->reserve(mInflightBufferMap.size());
4300 for (auto& pair : mInflightBufferMap) {
4301 uint64_t key = pair.first;
4302 int32_t streamId = key & 0xFFFFFFFF;
4303 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4304 out->push_back(std::make_pair(frameNumber, streamId));
4305 }
4306 return;
4307}
4308
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004309status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004310 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004311 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004312 auto pair = std::make_pair(buffer, acquireFence);
4313 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004314 return OK;
4315}
4316
4317status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004318 int32_t frameNumber, int32_t streamId,
4319 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004320 std::lock_guard<std::mutex> lock(mInflightLock);
4321
4322 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4323 auto it = mInflightBufferMap.find(key);
4324 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004325 auto pair = it->second;
4326 *buffer = pair.first;
4327 int acquireFence = pair.second;
4328 if (acquireFence > 0) {
4329 ::close(acquireFence);
4330 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004331 mInflightBufferMap.erase(it);
4332 return OK;
4333}
4334
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004335status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4336 uint64_t bufferId, buffer_handle_t* buf) {
4337 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4338 auto pair = mRequestedBuffers.insert({bufferId, buf});
4339 if (!pair.second) {
4340 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4341 __FUNCTION__, bufferId);
4342 return BAD_VALUE;
4343 }
4344 return OK;
4345}
4346
4347// Find and pop a buffer_handle_t based on bufferId
4348status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4349 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4350 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4351 auto it = mRequestedBuffers.find(bufferId);
4352 if (it == mRequestedBuffers.end()) {
4353 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4354 __FUNCTION__, bufferId);
4355 return BAD_VALUE;
4356 }
4357 *buffer = it->second;
4358 mRequestedBuffers.erase(it);
4359 return OK;
4360}
4361
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004362std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4363 const buffer_handle_t& buf, int streamId) {
4364 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4365
4366 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4367 auto it = bIdMap.find(buf);
4368 if (it == bIdMap.end()) {
4369 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004370 ALOGV("stream %d now have %zu buffer caches, buf %p",
4371 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004372 return std::make_pair(true, mNextBufferId - 1);
4373 } else {
4374 return std::make_pair(false, it->second);
4375 }
4376}
4377
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004378void Camera3Device::HalInterface::onBufferFreed(
4379 int streamId, const native_handle_t* handle) {
4380 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4381 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4382 auto mapIt = mBufferIdMaps.find(streamId);
4383 if (mapIt == mBufferIdMaps.end()) {
4384 // streamId might be from a deleted stream here
4385 ALOGI("%s: stream %d has been removed",
4386 __FUNCTION__, streamId);
4387 return;
4388 }
4389 BufferIdMap& bIdMap = mapIt->second;
4390 auto it = bIdMap.find(handle);
4391 if (it == bIdMap.end()) {
4392 ALOGW("%s: cannot find buffer %p in stream %d",
4393 __FUNCTION__, handle, streamId);
4394 return;
4395 } else {
4396 bufferId = it->second;
4397 bIdMap.erase(it);
4398 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4399 __FUNCTION__, streamId, bIdMap.size(), handle);
4400 }
4401 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4402}
4403
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004404/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004405 * RequestThread inner class methods
4406 */
4407
4408Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004409 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004410 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4411 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004412 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004413 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004414 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004415 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004416 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004417 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004418 mReconfigured(false),
4419 mDoPause(false),
4420 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004421 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004422 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004423 mCurrentAfTriggerId(0),
4424 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004425 mRepeatingLastFrameNumber(
4426 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004427 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004428 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004429 mRequestLatency(kRequestLatencyBinSize),
4430 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004431 mLatestSessionParams(sessionParamKeys.size()),
4432 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004433 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004434}
4435
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004436Camera3Device::RequestThread::~RequestThread() {}
4437
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004438void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004439 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004440 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004441 Mutex::Autolock l(mRequestLock);
4442 mListener = listener;
4443}
4444
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004445void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4446 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004447 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004448 Mutex::Autolock l(mRequestLock);
4449 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004450 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004451 // Prepare video stream for high speed recording.
4452 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004453 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004454}
4455
Jianing Wei90e59c92014-03-12 18:29:36 -07004456status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004457 List<sp<CaptureRequest> > &requests,
4458 /*out*/
4459 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004460 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004461 Mutex::Autolock l(mRequestLock);
4462 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4463 ++it) {
4464 mRequestQueue.push_back(*it);
4465 }
4466
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004467 if (lastFrameNumber != NULL) {
4468 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4469 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4470 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4471 *lastFrameNumber);
4472 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004473
Jianing Wei90e59c92014-03-12 18:29:36 -07004474 unpauseForNewRequests();
4475
4476 return OK;
4477}
4478
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004479
4480status_t Camera3Device::RequestThread::queueTrigger(
4481 RequestTrigger trigger[],
4482 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004483 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004484 Mutex::Autolock l(mTriggerMutex);
4485 status_t ret;
4486
4487 for (size_t i = 0; i < count; ++i) {
4488 ret = queueTriggerLocked(trigger[i]);
4489
4490 if (ret != OK) {
4491 return ret;
4492 }
4493 }
4494
4495 return OK;
4496}
4497
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004498const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4499 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004500 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004501 if (d != nullptr) return d->mId;
4502 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004503}
4504
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004505status_t Camera3Device::RequestThread::queueTriggerLocked(
4506 RequestTrigger trigger) {
4507
4508 uint32_t tag = trigger.metadataTag;
4509 ssize_t index = mTriggerMap.indexOfKey(tag);
4510
4511 switch (trigger.getTagType()) {
4512 case TYPE_BYTE:
4513 // fall-through
4514 case TYPE_INT32:
4515 break;
4516 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004517 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4518 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004519 return INVALID_OPERATION;
4520 }
4521
4522 /**
4523 * Collect only the latest trigger, since we only have 1 field
4524 * in the request settings per trigger tag, and can't send more than 1
4525 * trigger per request.
4526 */
4527 if (index != NAME_NOT_FOUND) {
4528 mTriggerMap.editValueAt(index) = trigger;
4529 } else {
4530 mTriggerMap.add(tag, trigger);
4531 }
4532
4533 return OK;
4534}
4535
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004536status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004537 const RequestList &requests,
4538 /*out*/
4539 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004540 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004541 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004542 if (lastFrameNumber != NULL) {
4543 *lastFrameNumber = mRepeatingLastFrameNumber;
4544 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004545 mRepeatingRequests.clear();
4546 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4547 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004548
4549 unpauseForNewRequests();
4550
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004551 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004552 return OK;
4553}
4554
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004555bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004556 if (mRepeatingRequests.empty()) {
4557 return false;
4558 }
4559 int32_t requestId = requestIn->mResultExtras.requestId;
4560 const RequestList &repeatRequests = mRepeatingRequests;
4561 // All repeating requests are guaranteed to have same id so only check first quest
4562 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4563 return (firstRequest->mResultExtras.requestId == requestId);
4564}
4565
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004566status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004567 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004568 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004569 return clearRepeatingRequestsLocked(lastFrameNumber);
4570
4571}
4572
4573status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004574 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004575 if (lastFrameNumber != NULL) {
4576 *lastFrameNumber = mRepeatingLastFrameNumber;
4577 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004578 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004579 return OK;
4580}
4581
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004582status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004583 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004584 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004585 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004586 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004587
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004588 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004589
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004590 // Send errors for all requests pending in the request queue, including
4591 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004592 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004593 if (listener != NULL) {
4594 for (RequestList::iterator it = mRequestQueue.begin();
4595 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004596 // Abort the input buffers for reprocess requests.
4597 if ((*it)->mInputStream != NULL) {
4598 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004599 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4600 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004601 if (res != OK) {
4602 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4603 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4604 } else {
4605 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4606 if (res != OK) {
4607 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4608 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4609 }
4610 }
4611 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004612 // Set the frame number this request would have had, if it
4613 // had been submitted; this frame number will not be reused.
4614 // The requestId and burstId fields were set when the request was
4615 // submitted originally (in convertMetadataListToRequestListLocked)
4616 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004617 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004618 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004619 }
4620 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004621 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004622
4623 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004624 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004625 if (lastFrameNumber != NULL) {
4626 *lastFrameNumber = mRepeatingLastFrameNumber;
4627 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004628 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004629 return OK;
4630}
4631
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004632status_t Camera3Device::RequestThread::flush() {
4633 ATRACE_CALL();
4634 Mutex::Autolock l(mFlushLock);
4635
Emilian Peev08dd2452017-04-06 16:55:14 +01004636 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004637}
4638
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004639void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004640 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004641 Mutex::Autolock l(mPauseLock);
4642 mDoPause = paused;
4643 mDoPauseSignal.signal();
4644}
4645
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004646status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4647 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004648 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004649 Mutex::Autolock l(mLatestRequestMutex);
4650 status_t res;
4651 while (mLatestRequestId != requestId) {
4652 nsecs_t startTime = systemTime();
4653
4654 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4655 if (res != OK) return res;
4656
4657 timeout -= (systemTime() - startTime);
4658 }
4659
4660 return OK;
4661}
4662
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004663void Camera3Device::RequestThread::requestExit() {
4664 // Call parent to set up shutdown
4665 Thread::requestExit();
4666 // The exit from any possible waits
4667 mDoPauseSignal.signal();
4668 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004669
4670 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4671 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004672}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004673
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004674void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004675 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004676 bool surfaceAbandoned = false;
4677 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004678 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004679 {
4680 Mutex::Autolock l(mRequestLock);
4681 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4682 // repeating requests.
4683 for (const auto& request : mRepeatingRequests) {
4684 for (const auto& s : request->mOutputStreams) {
4685 if (s->isAbandoned()) {
4686 surfaceAbandoned = true;
4687 clearRepeatingRequestsLocked(&lastFrameNumber);
4688 break;
4689 }
4690 }
4691 if (surfaceAbandoned) {
4692 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004693 }
4694 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004695 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004696 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004697
4698 if (listener != NULL && surfaceAbandoned) {
4699 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004700 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004701}
4702
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004703bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004704 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004705 status_t res;
4706 size_t batchSize = mNextRequests.size();
4707 std::vector<camera3_capture_request_t*> requests(batchSize);
4708 uint32_t numRequestProcessed = 0;
4709 for (size_t i = 0; i < batchSize; i++) {
4710 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004711 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004712 }
4713
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004714 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4715
4716 bool triggerRemoveFailed = false;
4717 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4718 for (size_t i = 0; i < numRequestProcessed; i++) {
4719 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4720 nextRequest.submitted = true;
4721
4722
4723 // Update the latest request sent to HAL
4724 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4725 Mutex::Autolock al(mLatestRequestMutex);
4726
4727 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4728 mLatestRequest.acquire(cloned);
4729
4730 sp<Camera3Device> parent = mParent.promote();
4731 if (parent != NULL) {
4732 parent->monitorMetadata(TagMonitor::REQUEST,
4733 nextRequest.halRequest.frame_number,
4734 0, mLatestRequest);
4735 }
4736 }
4737
4738 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004739 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4740 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004741 }
4742
Emilian Peevaebbe412018-01-15 13:53:24 +00004743 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4744
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004745 if (!triggerRemoveFailed) {
4746 // Remove any previously queued triggers (after unlock)
4747 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4748 if (removeTriggerRes != OK) {
4749 triggerRemoveFailed = true;
4750 triggerFailedRequest = nextRequest;
4751 }
4752 }
4753 }
4754
4755 if (triggerRemoveFailed) {
4756 SET_ERR("RequestThread: Unable to remove triggers "
4757 "(capture request %d, HAL device: %s (%d)",
4758 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4759 cleanUpFailedRequests(/*sendRequestError*/ false);
4760 return false;
4761 }
4762
4763 if (res != OK) {
4764 // Should only get a failure here for malformed requests or device-level
4765 // errors, so consider all errors fatal. Bad metadata failures should
4766 // come through notify.
4767 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4768 mNextRequests[numRequestProcessed].halRequest.frame_number,
4769 strerror(-res), res);
4770 cleanUpFailedRequests(/*sendRequestError*/ false);
4771 return false;
4772 }
4773 return true;
4774}
4775
4776bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4777 status_t res;
4778
4779 for (auto& nextRequest : mNextRequests) {
4780 // Submit request and block until ready for next one
4781 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4782 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4783
4784 if (res != OK) {
4785 // Should only get a failure here for malformed requests or device-level
4786 // errors, so consider all errors fatal. Bad metadata failures should
4787 // come through notify.
4788 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4789 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4790 res);
4791 cleanUpFailedRequests(/*sendRequestError*/ false);
4792 return false;
4793 }
4794
4795 // Mark that the request has be submitted successfully.
4796 nextRequest.submitted = true;
4797
4798 // Update the latest request sent to HAL
4799 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4800 Mutex::Autolock al(mLatestRequestMutex);
4801
4802 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4803 mLatestRequest.acquire(cloned);
4804
4805 sp<Camera3Device> parent = mParent.promote();
4806 if (parent != NULL) {
4807 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4808 0, mLatestRequest);
4809 }
4810 }
4811
4812 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004813 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4814 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004815 }
4816
Emilian Peevaebbe412018-01-15 13:53:24 +00004817 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4818
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004819 // Remove any previously queued triggers (after unlock)
4820 res = removeTriggers(mPrevRequest);
4821 if (res != OK) {
4822 SET_ERR("RequestThread: Unable to remove triggers "
4823 "(capture request %d, HAL device: %s (%d)",
4824 nextRequest.halRequest.frame_number, strerror(-res), res);
4825 cleanUpFailedRequests(/*sendRequestError*/ false);
4826 return false;
4827 }
4828 }
4829 return true;
4830}
4831
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004832nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4833 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4834 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4835 find_camera_metadata_ro_entry(request,
4836 ANDROID_CONTROL_AE_MODE,
4837 &e);
4838 if (e.count == 0) return maxExpectedDuration;
4839
4840 switch (e.data.u8[0]) {
4841 case ANDROID_CONTROL_AE_MODE_OFF:
4842 find_camera_metadata_ro_entry(request,
4843 ANDROID_SENSOR_EXPOSURE_TIME,
4844 &e);
4845 if (e.count > 0) {
4846 maxExpectedDuration = e.data.i64[0];
4847 }
4848 find_camera_metadata_ro_entry(request,
4849 ANDROID_SENSOR_FRAME_DURATION,
4850 &e);
4851 if (e.count > 0) {
4852 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4853 }
4854 break;
4855 default:
4856 find_camera_metadata_ro_entry(request,
4857 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4858 &e);
4859 if (e.count > 1) {
4860 maxExpectedDuration = 1e9 / e.data.u8[0];
4861 }
4862 break;
4863 }
4864
4865 return maxExpectedDuration;
4866}
4867
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004868bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4869 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4870 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4871 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4872 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4873 return true;
4874 }
4875
4876 return false;
4877}
4878
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004879bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4880 ATRACE_CALL();
4881 bool updatesDetected = false;
4882
4883 for (auto tag : mSessionParamKeys) {
4884 camera_metadata_ro_entry entry = settings.find(tag);
4885 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4886
4887 if (entry.count > 0) {
4888 bool isDifferent = false;
4889 if (lastEntry.count > 0) {
4890 // Have a last value, compare to see if changed
4891 if (lastEntry.type == entry.type &&
4892 lastEntry.count == entry.count) {
4893 // Same type and count, compare values
4894 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4895 size_t entryBytes = bytesPerValue * lastEntry.count;
4896 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4897 if (cmp != 0) {
4898 isDifferent = true;
4899 }
4900 } else {
4901 // Count or type has changed
4902 isDifferent = true;
4903 }
4904 } else {
4905 // No last entry, so always consider to be different
4906 isDifferent = true;
4907 }
4908
4909 if (isDifferent) {
4910 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004911 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4912 updatesDetected = true;
4913 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004914 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004915 }
4916 } else if (lastEntry.count > 0) {
4917 // Value has been removed
4918 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4919 mLatestSessionParams.erase(tag);
4920 updatesDetected = true;
4921 }
4922 }
4923
4924 return updatesDetected;
4925}
4926
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004927bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004928 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004929 status_t res;
4930
4931 // Handle paused state.
4932 if (waitIfPaused()) {
4933 return true;
4934 }
4935
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004936 // Wait for the next batch of requests.
4937 waitForNextRequestBatch();
4938 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004939 return true;
4940 }
4941
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004942 // Get the latest request ID, if any
4943 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004944 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004945 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004946 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004947 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004948 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004949 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4950 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004951 }
4952
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004953 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4954 // or a single request from streaming or burst. In either case the first element
4955 // should contain the latest camera settings that we need to check for any session
4956 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004957 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004958 res = OK;
4959
4960 //Input stream buffers are already acquired at this point so an input stream
4961 //will not be able to move to idle state unless we force it.
4962 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4963 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4964 if (res != OK) {
4965 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4966 cleanUpFailedRequests(/*sendRequestError*/ false);
4967 return false;
4968 }
4969 }
4970
4971 if (res == OK) {
4972 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4973 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004974 sp<Camera3Device> parent = mParent.promote();
4975 if (parent != nullptr) {
4976 parent->pauseStateNotify(true);
4977 }
4978
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004979 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4980
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004981 if (parent != nullptr) {
4982 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4983 }
4984
4985 statusTracker->markComponentActive(mStatusId);
4986 setPaused(false);
4987 }
4988
4989 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4990 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4991 if (res != OK) {
4992 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4993 cleanUpFailedRequests(/*sendRequestError*/ false);
4994 return false;
4995 }
4996 }
4997 }
4998 }
4999
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005000 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005001 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005002 if (res == TIMED_OUT) {
5003 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005004 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005005 // Check if any stream is abandoned.
5006 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005007 return true;
5008 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005009 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005010 return false;
5011 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005012
Zhijun Hecc27e112013-10-03 16:12:43 -07005013 // Inform waitUntilRequestProcessed thread of a new request ID
5014 {
5015 Mutex::Autolock al(mLatestRequestMutex);
5016
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005017 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005018 mLatestRequestSignal.signal();
5019 }
5020
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005021 // Submit a batch of requests to HAL.
5022 // Use flush lock only when submitting multilple requests in a batch.
5023 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5024 // which may take a long time to finish so synchronizing flush() and
5025 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5026 // For now, only synchronize for high speed recording and we should figure something out for
5027 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005028 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005029
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005030 if (useFlushLock) {
5031 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005032 }
5033
Zhijun Hef0645c12016-08-02 00:58:11 -07005034 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005035 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005036
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005037 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005038 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005039 if (mInterface->supportBatchRequest()) {
5040 submitRequestSuccess = sendRequestsBatch();
5041 } else {
5042 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005043 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005044 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5045 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005046
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005047 if (useFlushLock) {
5048 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005049 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005050
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005051 // Unset as current request
5052 {
5053 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005054 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005055 }
5056
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005057 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005058}
5059
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005060status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005061 ATRACE_CALL();
5062
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005063 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005064 for (size_t i = 0; i < mNextRequests.size(); i++) {
5065 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005066 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5067 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5068 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5069
5070 // Prepare a request to HAL
5071 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5072
5073 // Insert any queued triggers (before metadata is locked)
5074 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005075 if (res < 0) {
5076 SET_ERR("RequestThread: Unable to insert triggers "
5077 "(capture request %d, HAL device: %s (%d)",
5078 halRequest->frame_number, strerror(-res), res);
5079 return INVALID_OPERATION;
5080 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005081
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005082 int triggerCount = res;
5083 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5084 mPrevTriggers = triggerCount;
5085
5086 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005087 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5088 // Request settings are all the same within one batch, so only treat the first
5089 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005090 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005091 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005092 /**
5093 * HAL workaround:
5094 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5095 */
5096 res = addDummyTriggerIds(captureRequest);
5097 if (res != OK) {
5098 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5099 "(capture request %d, HAL device: %s (%d)",
5100 halRequest->frame_number, strerror(-res), res);
5101 return INVALID_OPERATION;
5102 }
5103
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005104 {
5105 // Correct metadata regions for distortion correction if enabled
5106 sp<Camera3Device> parent = mParent.promote();
5107 if (parent != nullptr) {
5108 res = parent->mDistortionMapper.correctCaptureRequest(
5109 &(captureRequest->mSettingsList.begin()->metadata));
5110 if (res != OK) {
5111 SET_ERR("RequestThread: Unable to correct capture requests "
5112 "for lens distortion for request %d: %s (%d)",
5113 halRequest->frame_number, strerror(-res), res);
5114 return INVALID_OPERATION;
5115 }
5116 }
5117 }
5118
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005119 /**
5120 * The request should be presorted so accesses in HAL
5121 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5122 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005123 captureRequest->mSettingsList.begin()->metadata.sort();
5124 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005125 mPrevRequest = captureRequest;
5126 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5127
5128 IF_ALOGV() {
5129 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5130 find_camera_metadata_ro_entry(
5131 halRequest->settings,
5132 ANDROID_CONTROL_AF_TRIGGER,
5133 &e
5134 );
5135 if (e.count > 0) {
5136 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5137 __FUNCTION__,
5138 halRequest->frame_number,
5139 e.data.u8[0]);
5140 }
5141 }
5142 } else {
5143 // leave request.settings NULL to indicate 'reuse latest given'
5144 ALOGVV("%s: Request settings are REUSED",
5145 __FUNCTION__);
5146 }
5147
Emilian Peevaebbe412018-01-15 13:53:24 +00005148 if (captureRequest->mSettingsList.size() > 1) {
5149 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5150 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005151 if (newRequest) {
5152 halRequest->physcam_settings =
5153 new const camera_metadata* [halRequest->num_physcam_settings];
5154 } else {
5155 halRequest->physcam_settings = nullptr;
5156 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005157 auto it = ++captureRequest->mSettingsList.begin();
5158 size_t i = 0;
5159 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5160 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005161 if (newRequest) {
5162 it->metadata.sort();
5163 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5164 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005165 }
5166 }
5167
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005168 uint32_t totalNumBuffers = 0;
5169
5170 // Fill in buffers
5171 if (captureRequest->mInputStream != NULL) {
5172 halRequest->input_buffer = &captureRequest->mInputBuffer;
5173 totalNumBuffers += 1;
5174 } else {
5175 halRequest->input_buffer = NULL;
5176 }
5177
5178 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5179 captureRequest->mOutputStreams.size());
5180 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005181 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005182
5183 sp<Camera3Device> parent = mParent.promote();
5184 if (parent == NULL) {
5185 // Should not happen, and nowhere to send errors to, so just log it
5186 CLOGE("RequestThread: Parent is gone");
5187 return INVALID_OPERATION;
5188 }
5189 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5190
Shuzhen Wang4a472662017-02-26 23:29:04 -08005191 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
5192 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005193
5194 // Prepare video buffers for high speed recording on the first video request.
5195 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5196 // Only try to prepare video stream on the first video request.
5197 mPrepareVideoStream = false;
5198
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005199 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5200 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005201 while (res == NOT_ENOUGH_DATA) {
5202 res = outputStream->prepareNextBuffer();
5203 }
5204 if (res != OK) {
5205 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5206 __FUNCTION__, strerror(-res), res);
5207 outputStream->cancelPrepare();
5208 }
5209 }
5210
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005211 if (mUseHalBufManager) {
5212 // HAL will request buffer through requestStreamBuffer API
5213 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5214 buffer.stream = outputStream->asHalStream();
5215 buffer.buffer = nullptr;
5216 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5217 buffer.acquire_fence = -1;
5218 buffer.release_fence = -1;
5219 } else {
5220 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5221 waitDuration,
5222 captureRequest->mOutputSurfaces[outputStream->getId()]);
5223 if (res != OK) {
5224 // Can't get output buffer from gralloc queue - this could be due to
5225 // abandoned queue or other consumer misbehavior, so not a fatal
5226 // error
5227 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5228 " %s (%d)", strerror(-res), res);
5229
5230 return TIMED_OUT;
5231 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005232 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005233
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005234 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5235
5236 if (!physicalCameraId.isEmpty()) {
5237 // Physical stream isn't supported for input request.
5238 if (halRequest->input_buffer) {
5239 CLOGE("Physical stream is not supported for input request");
5240 return INVALID_OPERATION;
5241 }
5242 requestedPhysicalCameras.insert(physicalCameraId);
5243 }
5244 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005245 }
5246 totalNumBuffers += halRequest->num_output_buffers;
5247
5248 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005249 // If this request list is for constrained high speed recording (not
5250 // preview), and the current request is not the last one in the batch,
5251 // do not send callback to the app.
5252 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005253 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005254 hasCallback = false;
5255 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005256 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005257 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005258 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5259 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5260 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5261 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5262 isStillCapture = true;
5263 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5264 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005265
5266 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5267 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5268 isZslCapture = true;
5269 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005270 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005271 res = parent->registerInFlight(halRequest->frame_number,
5272 totalNumBuffers, captureRequest->mResultExtras,
5273 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005274 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005275 calculateMaxExpectedDuration(halRequest->settings),
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005276 requestedPhysicalCameras, isStillCapture, isZslCapture);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005277 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5278 ", burstId = %" PRId32 ".",
5279 __FUNCTION__,
5280 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5281 captureRequest->mResultExtras.burstId);
5282 if (res != OK) {
5283 SET_ERR("RequestThread: Unable to register new in-flight request:"
5284 " %s (%d)", strerror(-res), res);
5285 return INVALID_OPERATION;
5286 }
5287 }
5288
5289 return OK;
5290}
5291
Igor Murashkin1e479c02013-09-06 16:55:14 -07005292CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005293 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005294 Mutex::Autolock al(mLatestRequestMutex);
5295
5296 ALOGV("RequestThread::%s", __FUNCTION__);
5297
5298 return mLatestRequest;
5299}
5300
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005301bool Camera3Device::RequestThread::isStreamPending(
5302 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005303 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005304 Mutex::Autolock l(mRequestLock);
5305
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005306 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005307 if (!nextRequest.submitted) {
5308 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5309 if (stream == s) return true;
5310 }
5311 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005312 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005313 }
5314
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005315 for (const auto& request : mRequestQueue) {
5316 for (const auto& s : request->mOutputStreams) {
5317 if (stream == s) return true;
5318 }
5319 if (stream == request->mInputStream) return true;
5320 }
5321
5322 for (const auto& request : mRepeatingRequests) {
5323 for (const auto& s : request->mOutputStreams) {
5324 if (stream == s) return true;
5325 }
5326 if (stream == request->mInputStream) return true;
5327 }
5328
5329 return false;
5330}
Jianing Weicb0652e2014-03-12 18:29:36 -07005331
Emilian Peev40ead602017-09-26 15:46:36 +01005332bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5333 ATRACE_CALL();
5334 Mutex::Autolock l(mRequestLock);
5335
5336 for (const auto& nextRequest : mNextRequests) {
5337 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5338 if (s.first == streamId) {
5339 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5340 if (it != s.second.end()) {
5341 return true;
5342 }
5343 }
5344 }
5345 }
5346
5347 for (const auto& request : mRequestQueue) {
5348 for (const auto& s : request->mOutputSurfaces) {
5349 if (s.first == streamId) {
5350 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5351 if (it != s.second.end()) {
5352 return true;
5353 }
5354 }
5355 }
5356 }
5357
5358 for (const auto& request : mRepeatingRequests) {
5359 for (const auto& s : request->mOutputSurfaces) {
5360 if (s.first == streamId) {
5361 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5362 if (it != s.second.end()) {
5363 return true;
5364 }
5365 }
5366 }
5367 }
5368
5369 return false;
5370}
5371
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005372nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005373 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005374 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005375 return mExpectedInflightDuration > kMinInflightDuration ?
5376 mExpectedInflightDuration : kMinInflightDuration;
5377}
5378
Emilian Peevaebbe412018-01-15 13:53:24 +00005379void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5380 camera3_capture_request_t *halRequest) {
5381 if ((request == nullptr) || (halRequest == nullptr)) {
5382 ALOGE("%s: Invalid request!", __FUNCTION__);
5383 return;
5384 }
5385
5386 if (halRequest->num_physcam_settings > 0) {
5387 if (halRequest->physcam_id != nullptr) {
5388 delete [] halRequest->physcam_id;
5389 halRequest->physcam_id = nullptr;
5390 }
5391 if (halRequest->physcam_settings != nullptr) {
5392 auto it = ++(request->mSettingsList.begin());
5393 size_t i = 0;
5394 for (; it != request->mSettingsList.end(); it++, i++) {
5395 it->metadata.unlock(halRequest->physcam_settings[i]);
5396 }
5397 delete [] halRequest->physcam_settings;
5398 halRequest->physcam_settings = nullptr;
5399 }
5400 }
5401}
5402
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005403void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5404 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005405 return;
5406 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005407
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005408 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005409 // Skip the ones that have been submitted successfully.
5410 if (nextRequest.submitted) {
5411 continue;
5412 }
5413
5414 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5415 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5416 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5417
5418 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005419 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005420 }
5421
Emilian Peevaebbe412018-01-15 13:53:24 +00005422 cleanupPhysicalSettings(captureRequest, halRequest);
5423
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005424 if (captureRequest->mInputStream != NULL) {
5425 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5426 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5427 }
5428
5429 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005430 //Buffers that failed processing could still have
5431 //valid acquire fence.
5432 int acquireFence = (*outputBuffers)[i].acquire_fence;
5433 if (0 <= acquireFence) {
5434 close(acquireFence);
5435 outputBuffers->editItemAt(i).acquire_fence = -1;
5436 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005437 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5438 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5439 }
5440
5441 if (sendRequestError) {
5442 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005443 sp<NotificationListener> listener = mListener.promote();
5444 if (listener != NULL) {
5445 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005446 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005447 captureRequest->mResultExtras);
5448 }
5449 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005450
5451 // Remove yet-to-be submitted inflight request from inflightMap
5452 {
5453 sp<Camera3Device> parent = mParent.promote();
5454 if (parent != NULL) {
5455 Mutex::Autolock l(parent->mInFlightLock);
5456 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5457 if (idx >= 0) {
5458 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5459 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5460 parent->removeInFlightMapEntryLocked(idx);
5461 }
5462 }
5463 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005464 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005465
5466 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005467 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005468}
5469
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005470void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005471 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005472 // Optimized a bit for the simple steady-state case (single repeating
5473 // request), to avoid putting that request in the queue temporarily.
5474 Mutex::Autolock l(mRequestLock);
5475
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005476 assert(mNextRequests.empty());
5477
5478 NextRequest nextRequest;
5479 nextRequest.captureRequest = waitForNextRequestLocked();
5480 if (nextRequest.captureRequest == nullptr) {
5481 return;
5482 }
5483
5484 nextRequest.halRequest = camera3_capture_request_t();
5485 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005486 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005487
5488 // Wait for additional requests
5489 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5490
5491 for (size_t i = 1; i < batchSize; i++) {
5492 NextRequest additionalRequest;
5493 additionalRequest.captureRequest = waitForNextRequestLocked();
5494 if (additionalRequest.captureRequest == nullptr) {
5495 break;
5496 }
5497
5498 additionalRequest.halRequest = camera3_capture_request_t();
5499 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005500 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005501 }
5502
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005503 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005504 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005505 mNextRequests.size(), batchSize);
5506 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005507 }
5508
5509 return;
5510}
5511
5512sp<Camera3Device::CaptureRequest>
5513 Camera3Device::RequestThread::waitForNextRequestLocked() {
5514 status_t res;
5515 sp<CaptureRequest> nextRequest;
5516
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005517 while (mRequestQueue.empty()) {
5518 if (!mRepeatingRequests.empty()) {
5519 // Always atomically enqueue all requests in a repeating request
5520 // list. Guarantees a complete in-sequence set of captures to
5521 // application.
5522 const RequestList &requests = mRepeatingRequests;
5523 RequestList::const_iterator firstRequest =
5524 requests.begin();
5525 nextRequest = *firstRequest;
5526 mRequestQueue.insert(mRequestQueue.end(),
5527 ++firstRequest,
5528 requests.end());
5529 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005530
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005531 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005532
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005533 break;
5534 }
5535
5536 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5537
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005538 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5539 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005540 Mutex::Autolock pl(mPauseLock);
5541 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005542 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005543 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005544 // Let the tracker know
5545 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5546 if (statusTracker != 0) {
5547 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5548 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005549 }
5550 // Stop waiting for now and let thread management happen
5551 return NULL;
5552 }
5553 }
5554
5555 if (nextRequest == NULL) {
5556 // Don't have a repeating request already in hand, so queue
5557 // must have an entry now.
5558 RequestList::iterator firstRequest =
5559 mRequestQueue.begin();
5560 nextRequest = *firstRequest;
5561 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005562 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5563 sp<NotificationListener> listener = mListener.promote();
5564 if (listener != NULL) {
5565 listener->notifyRequestQueueEmpty();
5566 }
5567 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005568 }
5569
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005570 // In case we've been unpaused by setPaused clearing mDoPause, need to
5571 // update internal pause state (capture/setRepeatingRequest unpause
5572 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005573 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005574 if (mPaused) {
5575 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5576 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5577 if (statusTracker != 0) {
5578 statusTracker->markComponentActive(mStatusId);
5579 }
5580 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005581 mPaused = false;
5582
5583 // Check if we've reconfigured since last time, and reset the preview
5584 // request if so. Can't use 'NULL request == repeat' across configure calls.
5585 if (mReconfigured) {
5586 mPrevRequest.clear();
5587 mReconfigured = false;
5588 }
5589
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005590 if (nextRequest != NULL) {
5591 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005592 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5593 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005594
5595 // Since RequestThread::clear() removes buffers from the input stream,
5596 // get the right buffer here before unlocking mRequestLock
5597 if (nextRequest->mInputStream != NULL) {
5598 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5599 if (res != OK) {
5600 // Can't get input buffer from gralloc queue - this could be due to
5601 // disconnected queue or other producer misbehavior, so not a fatal
5602 // error
5603 ALOGE("%s: Can't get input buffer, skipping request:"
5604 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005605
5606 sp<NotificationListener> listener = mListener.promote();
5607 if (listener != NULL) {
5608 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005609 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005610 nextRequest->mResultExtras);
5611 }
5612 return NULL;
5613 }
5614 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005615 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005616
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005617 return nextRequest;
5618}
5619
5620bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005621 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005622 status_t res;
5623 Mutex::Autolock l(mPauseLock);
5624 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005625 if (mPaused == false) {
5626 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005627 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5628 // Let the tracker know
5629 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5630 if (statusTracker != 0) {
5631 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5632 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005633 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005634
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005635 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005636 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005637 return true;
5638 }
5639 }
5640 // We don't set mPaused to false here, because waitForNextRequest needs
5641 // to further manage the paused state in case of starvation.
5642 return false;
5643}
5644
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005645void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005646 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005647 // With work to do, mark thread as unpaused.
5648 // If paused by request (setPaused), don't resume, to avoid
5649 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005650 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005651 Mutex::Autolock p(mPauseLock);
5652 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005653 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5654 if (mPaused) {
5655 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5656 if (statusTracker != 0) {
5657 statusTracker->markComponentActive(mStatusId);
5658 }
5659 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005660 mPaused = false;
5661 }
5662}
5663
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005664void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5665 sp<Camera3Device> parent = mParent.promote();
5666 if (parent != NULL) {
5667 va_list args;
5668 va_start(args, fmt);
5669
5670 parent->setErrorStateV(fmt, args);
5671
5672 va_end(args);
5673 }
5674}
5675
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005676status_t Camera3Device::RequestThread::insertTriggers(
5677 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005678 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005679 Mutex::Autolock al(mTriggerMutex);
5680
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005681 sp<Camera3Device> parent = mParent.promote();
5682 if (parent == NULL) {
5683 CLOGE("RequestThread: Parent is gone");
5684 return DEAD_OBJECT;
5685 }
5686
Emilian Peevaebbe412018-01-15 13:53:24 +00005687 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005688 size_t count = mTriggerMap.size();
5689
5690 for (size_t i = 0; i < count; ++i) {
5691 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005692 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005693
5694 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5695 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5696 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005697 if (isAeTrigger) {
5698 request->mResultExtras.precaptureTriggerId = triggerId;
5699 mCurrentPreCaptureTriggerId = triggerId;
5700 } else {
5701 request->mResultExtras.afTriggerId = triggerId;
5702 mCurrentAfTriggerId = triggerId;
5703 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005704 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005705 }
5706
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005707 camera_metadata_entry entry = metadata.find(tag);
5708
5709 if (entry.count > 0) {
5710 /**
5711 * Already has an entry for this trigger in the request.
5712 * Rewrite it with our requested trigger value.
5713 */
5714 RequestTrigger oldTrigger = trigger;
5715
5716 oldTrigger.entryValue = entry.data.u8[0];
5717
5718 mTriggerReplacedMap.add(tag, oldTrigger);
5719 } else {
5720 /**
5721 * More typical, no trigger entry, so we just add it
5722 */
5723 mTriggerRemovedMap.add(tag, trigger);
5724 }
5725
5726 status_t res;
5727
5728 switch (trigger.getTagType()) {
5729 case TYPE_BYTE: {
5730 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5731 res = metadata.update(tag,
5732 &entryValue,
5733 /*count*/1);
5734 break;
5735 }
5736 case TYPE_INT32:
5737 res = metadata.update(tag,
5738 &trigger.entryValue,
5739 /*count*/1);
5740 break;
5741 default:
5742 ALOGE("%s: Type not supported: 0x%x",
5743 __FUNCTION__,
5744 trigger.getTagType());
5745 return INVALID_OPERATION;
5746 }
5747
5748 if (res != OK) {
5749 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5750 ", value %d", __FUNCTION__, trigger.getTagName(),
5751 trigger.entryValue);
5752 return res;
5753 }
5754
5755 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5756 trigger.getTagName(),
5757 trigger.entryValue);
5758 }
5759
5760 mTriggerMap.clear();
5761
5762 return count;
5763}
5764
5765status_t Camera3Device::RequestThread::removeTriggers(
5766 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005767 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005768 Mutex::Autolock al(mTriggerMutex);
5769
Emilian Peevaebbe412018-01-15 13:53:24 +00005770 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005771
5772 /**
5773 * Replace all old entries with their old values.
5774 */
5775 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5776 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5777
5778 status_t res;
5779
5780 uint32_t tag = trigger.metadataTag;
5781 switch (trigger.getTagType()) {
5782 case TYPE_BYTE: {
5783 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5784 res = metadata.update(tag,
5785 &entryValue,
5786 /*count*/1);
5787 break;
5788 }
5789 case TYPE_INT32:
5790 res = metadata.update(tag,
5791 &trigger.entryValue,
5792 /*count*/1);
5793 break;
5794 default:
5795 ALOGE("%s: Type not supported: 0x%x",
5796 __FUNCTION__,
5797 trigger.getTagType());
5798 return INVALID_OPERATION;
5799 }
5800
5801 if (res != OK) {
5802 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5803 ", trigger value %d", __FUNCTION__,
5804 trigger.getTagName(), trigger.entryValue);
5805 return res;
5806 }
5807 }
5808 mTriggerReplacedMap.clear();
5809
5810 /**
5811 * Remove all new entries.
5812 */
5813 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5814 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5815 status_t res = metadata.erase(trigger.metadataTag);
5816
5817 if (res != OK) {
5818 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5819 ", trigger value %d", __FUNCTION__,
5820 trigger.getTagName(), trigger.entryValue);
5821 return res;
5822 }
5823 }
5824 mTriggerRemovedMap.clear();
5825
5826 return OK;
5827}
5828
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005829status_t Camera3Device::RequestThread::addDummyTriggerIds(
5830 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005831 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005832 static const int32_t dummyTriggerId = 1;
5833 status_t res;
5834
Emilian Peevaebbe412018-01-15 13:53:24 +00005835 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005836
5837 // If AF trigger is active, insert a dummy AF trigger ID if none already
5838 // exists
5839 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5840 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5841 if (afTrigger.count > 0 &&
5842 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5843 afId.count == 0) {
5844 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5845 if (res != OK) return res;
5846 }
5847
5848 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5849 // if none already exists
5850 camera_metadata_entry pcTrigger =
5851 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5852 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5853 if (pcTrigger.count > 0 &&
5854 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5855 pcId.count == 0) {
5856 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5857 &dummyTriggerId, 1);
5858 if (res != OK) return res;
5859 }
5860
5861 return OK;
5862}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005863
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005864/**
5865 * PreparerThread inner class methods
5866 */
5867
5868Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005869 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005870 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005871}
5872
5873Camera3Device::PreparerThread::~PreparerThread() {
5874 Thread::requestExitAndWait();
5875 if (mCurrentStream != nullptr) {
5876 mCurrentStream->cancelPrepare();
5877 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5878 mCurrentStream.clear();
5879 }
5880 clear();
5881}
5882
Ruben Brunkc78ac262015-08-13 17:58:46 -07005883status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005884 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005885 status_t res;
5886
5887 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005888 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005889
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005890 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005891 if (res == OK) {
5892 // No preparation needed, fire listener right off
5893 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005894 if (listener != NULL) {
5895 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005896 }
5897 return OK;
5898 } else if (res != NOT_ENOUGH_DATA) {
5899 return res;
5900 }
5901
5902 // Need to prepare, start up thread if necessary
5903 if (!mActive) {
5904 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5905 // isn't running
5906 Thread::requestExitAndWait();
5907 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5908 if (res != OK) {
5909 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005910 if (listener != NULL) {
5911 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005912 }
5913 return res;
5914 }
5915 mCancelNow = false;
5916 mActive = true;
5917 ALOGV("%s: Preparer stream started", __FUNCTION__);
5918 }
5919
5920 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005921 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005922 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5923
5924 return OK;
5925}
5926
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005927void Camera3Device::PreparerThread::pause() {
5928 ATRACE_CALL();
5929
5930 Mutex::Autolock l(mLock);
5931
5932 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5933 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5934 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5935 int currentMaxCount = mCurrentMaxCount;
5936 mPendingStreams.clear();
5937 mCancelNow = true;
5938 while (mActive) {
5939 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5940 if (res == TIMED_OUT) {
5941 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5942 return;
5943 } else if (res != OK) {
5944 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5945 return;
5946 }
5947 }
5948
5949 //Check whether the prepare thread was able to complete the current
5950 //stream. In case work is still pending emplace it along with the rest
5951 //of the streams in the pending list.
5952 if (currentStream != nullptr) {
5953 if (!mCurrentPrepareComplete) {
5954 pendingStreams.emplace(currentMaxCount, currentStream);
5955 }
5956 }
5957
5958 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5959 for (const auto& it : mPendingStreams) {
5960 it.second->cancelPrepare();
5961 }
5962}
5963
5964status_t Camera3Device::PreparerThread::resume() {
5965 ATRACE_CALL();
5966 status_t res;
5967
5968 Mutex::Autolock l(mLock);
5969 sp<NotificationListener> listener = mListener.promote();
5970
5971 if (mActive) {
5972 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5973 return NO_INIT;
5974 }
5975
5976 auto it = mPendingStreams.begin();
5977 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005978 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005979 if (res == OK) {
5980 if (listener != NULL) {
5981 listener->notifyPrepared(it->second->getId());
5982 }
5983 it = mPendingStreams.erase(it);
5984 } else if (res != NOT_ENOUGH_DATA) {
5985 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5986 res, strerror(-res));
5987 it = mPendingStreams.erase(it);
5988 } else {
5989 it++;
5990 }
5991 }
5992
5993 if (mPendingStreams.empty()) {
5994 return OK;
5995 }
5996
5997 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5998 if (res != OK) {
5999 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6000 __FUNCTION__, res, strerror(-res));
6001 return res;
6002 }
6003 mCancelNow = false;
6004 mActive = true;
6005 ALOGV("%s: Preparer stream started", __FUNCTION__);
6006
6007 return OK;
6008}
6009
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006010status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006011 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006012 Mutex::Autolock l(mLock);
6013
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006014 for (const auto& it : mPendingStreams) {
6015 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006016 }
6017 mPendingStreams.clear();
6018 mCancelNow = true;
6019
6020 return OK;
6021}
6022
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006023void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006024 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006025 Mutex::Autolock l(mLock);
6026 mListener = listener;
6027}
6028
6029bool Camera3Device::PreparerThread::threadLoop() {
6030 status_t res;
6031 {
6032 Mutex::Autolock l(mLock);
6033 if (mCurrentStream == nullptr) {
6034 // End thread if done with work
6035 if (mPendingStreams.empty()) {
6036 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6037 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6038 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6039 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006040 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006041 return false;
6042 }
6043
6044 // Get next stream to prepare
6045 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006046 mCurrentStream = it->second;
6047 mCurrentMaxCount = it->first;
6048 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006049 mPendingStreams.erase(it);
6050 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6051 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6052 } else if (mCancelNow) {
6053 mCurrentStream->cancelPrepare();
6054 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6055 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6056 mCurrentStream.clear();
6057 mCancelNow = false;
6058 return true;
6059 }
6060 }
6061
6062 res = mCurrentStream->prepareNextBuffer();
6063 if (res == NOT_ENOUGH_DATA) return true;
6064 if (res != OK) {
6065 // Something bad happened; try to recover by cancelling prepare and
6066 // signalling listener anyway
6067 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6068 mCurrentStream->getId(), res, strerror(-res));
6069 mCurrentStream->cancelPrepare();
6070 }
6071
6072 // This stream has finished, notify listener
6073 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006074 sp<NotificationListener> listener = mListener.promote();
6075 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006076 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6077 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006078 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006079 }
6080
6081 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6082 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006083 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006084
6085 return true;
6086}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006087
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006088}; // namespace android