blob: fa4e036b15322ca2740895c59b1d90327f48019a [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
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700227 if (mUseHalBufManager) {
228 res = mRequestBufferSM.initialize(mStatusTracker);
229 if (res != OK) {
230 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
231 strerror(-res), res);
232 mInterface->close();
233 mStatusTracker.clear();
234 return res;
235 }
236 }
237
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700238 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700239 mRequestThread = new RequestThread(
240 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800241 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800242 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700243 SET_ERR_L("Unable to start request queue thread: %s (%d)",
244 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800245 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800246 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800247 return res;
248 }
249
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700250 mPreparerThread = new PreparerThread();
251
Ruben Brunk183f0562015-08-12 12:55:02 -0700252 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800253 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700254 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700255 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700256 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800257
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800258 // Measure the clock domain offset between camera and video/hw_composer
259 camera_metadata_entry timestampSource =
260 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
261 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
262 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
263 mTimestampOffset = getMonoToBoottimeOffset();
264 }
265
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700266 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100267 camera_metadata_entry partialResultsCount =
268 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
269 if (partialResultsCount.count > 0) {
270 mNumPartialResults = partialResultsCount.data.i32[0];
271 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700272 }
273
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700274 camera_metadata_entry configs =
275 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
276 for (uint32_t i = 0; i < configs.count; i += 4) {
277 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
278 configs.data.i32[i + 3] ==
279 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
280 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
281 configs.data.i32[i + 2]));
282 }
283 }
284
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700285 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
286 res = mDistortionMapper.setupStaticInfo(mDeviceInfo);
287 if (res != OK) {
288 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
289 return res;
290 }
291 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800292 return OK;
293}
294
295status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700296 return disconnectImpl();
297}
298
299status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800300 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700301 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800302
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700303 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800304
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700305 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700306 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700307 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700308 {
309 Mutex::Autolock l(mLock);
310 if (mStatus == STATUS_UNINITIALIZED) return res;
311
312 if (mStatus == STATUS_ACTIVE ||
313 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
314 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700315 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700316 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700317 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700318 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700319 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700320 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700321 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
322 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700323 // Continue to close device even in case of error
324 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700325 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800326 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800327
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700328 if (mStatus == STATUS_ERROR) {
329 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700330 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700331
332 if (mStatusTracker != NULL) {
333 mStatusTracker->requestExit();
334 }
335
336 if (mRequestThread != NULL) {
337 mRequestThread->requestExit();
338 }
339
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700340 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
341 for (size_t i = 0; i < mOutputStreams.size(); i++) {
342 streams.push_back(mOutputStreams[i]);
343 }
344 if (mInputStream != nullptr) {
345 streams.push_back(mInputStream);
346 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700347 }
348
349 // Joining done without holding mLock, otherwise deadlocks may ensue
350 // as the threads try to access parent state
351 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
352 // HAL may be in a bad state, so waiting for request thread
353 // (which may be stuck in the HAL processCaptureRequest call)
354 // could be dangerous.
355 mRequestThread->join();
356 }
357
358 if (mStatusTracker != NULL) {
359 mStatusTracker->join();
360 }
361
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800362 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700363 {
364 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800365 mRequestThread.clear();
Emilian Peev2843c362018-09-26 08:49:40 +0100366 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700367 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800368 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700369 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800370
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700371 // Call close without internal mutex held, as the HAL close may need to
372 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800373 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700374
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700375 flushInflightRequests();
376
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700377 {
378 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800379 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700380 mOutputStreams.clear();
381 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700382 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700383 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700384 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700385 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800386
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700387 for (auto& weakStream : streams) {
388 sp<Camera3StreamInterface> stream = weakStream.promote();
389 if (stream != nullptr) {
390 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
391 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
392 }
393 }
394
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700395 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700396 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800397}
398
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700399// For dumping/debugging only -
400// try to acquire a lock a few times, eventually give up to proceed with
401// debug/dump operations
402bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
403 bool gotLock = false;
404 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
405 if (lock.tryLock() == NO_ERROR) {
406 gotLock = true;
407 break;
408 } else {
409 usleep(kDumpSleepDuration);
410 }
411 }
412 return gotLock;
413}
414
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700415Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
416 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100417 const int STREAM_CONFIGURATION_SIZE = 4;
418 const int STREAM_FORMAT_OFFSET = 0;
419 const int STREAM_WIDTH_OFFSET = 1;
420 const int STREAM_HEIGHT_OFFSET = 2;
421 const int STREAM_IS_INPUT_OFFSET = 3;
422 camera_metadata_ro_entry_t availableStreamConfigs =
423 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
424 if (availableStreamConfigs.count == 0 ||
425 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
426 return Size(0, 0);
427 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700428
Emilian Peev08dd2452017-04-06 16:55:14 +0100429 // Get max jpeg size (area-wise).
430 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
431 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
432 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
433 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
434 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
435 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
436 && format == HAL_PIXEL_FORMAT_BLOB &&
437 (width * height > maxJpegWidth * maxJpegHeight)) {
438 maxJpegWidth = width;
439 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700440 }
441 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100442
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700443 return Size(maxJpegWidth, maxJpegHeight);
444}
445
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800446nsecs_t Camera3Device::getMonoToBoottimeOffset() {
447 // try three times to get the clock offset, choose the one
448 // with the minimum gap in measurements.
449 const int tries = 3;
450 nsecs_t bestGap, measured;
451 for (int i = 0; i < tries; ++i) {
452 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
453 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
454 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
455 const nsecs_t gap = tmono2 - tmono;
456 if (i == 0 || gap < bestGap) {
457 bestGap = gap;
458 measured = tbase - ((tmono + tmono2) >> 1);
459 }
460 }
461 return measured;
462}
463
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800464hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
465 int frameworkFormat) {
466 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
467}
468
469DataspaceFlags Camera3Device::mapToHidlDataspace(
470 android_dataspace dataSpace) {
471 return dataSpace;
472}
473
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700474BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100475 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700476 return usage;
477}
478
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800479StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
480 switch (rotation) {
481 case CAMERA3_STREAM_ROTATION_0:
482 return StreamRotation::ROTATION_0;
483 case CAMERA3_STREAM_ROTATION_90:
484 return StreamRotation::ROTATION_90;
485 case CAMERA3_STREAM_ROTATION_180:
486 return StreamRotation::ROTATION_180;
487 case CAMERA3_STREAM_ROTATION_270:
488 return StreamRotation::ROTATION_270;
489 }
490 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
491 return StreamRotation::ROTATION_0;
492}
493
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800494status_t Camera3Device::mapToStreamConfigurationMode(
495 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
496 if (mode == nullptr) return BAD_VALUE;
497 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
498 switch(operationMode) {
499 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
500 *mode = StreamConfigurationMode::NORMAL_MODE;
501 break;
502 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
503 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
504 break;
505 default:
506 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
507 return BAD_VALUE;
508 }
509 } else {
510 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800511 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800512 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800513}
514
515camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
516 switch (status) {
517 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
518 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
519 }
520 return CAMERA3_BUFFER_STATUS_ERROR;
521}
522
523int Camera3Device::mapToFrameworkFormat(
524 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
525 return static_cast<uint32_t>(pixelFormat);
526}
527
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700528android_dataspace Camera3Device::mapToFrameworkDataspace(
529 DataspaceFlags dataSpace) {
530 return static_cast<android_dataspace>(dataSpace);
531}
532
Emilian Peev050f5dc2017-05-18 14:43:56 +0100533uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700534 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700535 return usage;
536}
537
Emilian Peev050f5dc2017-05-18 14:43:56 +0100538uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700539 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700540 return usage;
541}
542
Zhijun Hef7da0962014-04-24 13:27:56 -0700543ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700544 // Get max jpeg size (area-wise).
545 Size maxJpegResolution = getMaxJpegResolution();
546 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800547 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
548 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700549 return BAD_VALUE;
550 }
551
Zhijun Hef7da0962014-04-24 13:27:56 -0700552 // Get max jpeg buffer size
553 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700554 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
555 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800556 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
557 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700558 return BAD_VALUE;
559 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700560 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800561 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700562
563 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700564 float scaleFactor = ((float) (width * height)) /
565 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800566 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
567 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700568 if (jpegBufferSize > maxJpegBufferSize) {
569 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700570 }
571
572 return jpegBufferSize;
573}
574
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700575ssize_t Camera3Device::getPointCloudBufferSize() const {
576 const int FLOATS_PER_POINT=4;
577 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
578 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800579 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
580 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700581 return BAD_VALUE;
582 }
583 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
584 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
585 return maxBytesForPointCloud;
586}
587
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800588ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800589 const int PER_CONFIGURATION_SIZE = 3;
590 const int WIDTH_OFFSET = 0;
591 const int HEIGHT_OFFSET = 1;
592 const int SIZE_OFFSET = 2;
593 camera_metadata_ro_entry rawOpaqueSizes =
594 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800595 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800596 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800597 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
598 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800599 return BAD_VALUE;
600 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700601
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800602 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
603 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
604 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
605 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
606 }
607 }
608
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800609 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
610 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800611 return BAD_VALUE;
612}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700613
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800614status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
615 ATRACE_CALL();
616 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700617
618 // Try to lock, but continue in case of failure (to avoid blocking in
619 // deadlocks)
620 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
621 bool gotLock = tryLockSpinRightRound(mLock);
622
623 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800624 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
625 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700626 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800627 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
628 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700629
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800630 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700631
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800632 String16 templatesOption("-t");
633 int n = args.size();
634 for (int i = 0; i < n; i++) {
635 if (args[i] == templatesOption) {
636 dumpTemplates = true;
637 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000638 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700639 if (i + 1 < n) {
640 String8 monitorTags = String8(args[i + 1]);
641 if (monitorTags == "off") {
642 mTagMonitor.disableMonitoring();
643 } else {
644 mTagMonitor.parseTagsToMonitor(monitorTags);
645 }
646 } else {
647 mTagMonitor.disableMonitoring();
648 }
649 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800650 }
651
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800652 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800653
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800654 const char *status =
655 mStatus == STATUS_ERROR ? "ERROR" :
656 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700657 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
658 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800659 mStatus == STATUS_ACTIVE ? "ACTIVE" :
660 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700661
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800662 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700663 if (mStatus == STATUS_ERROR) {
664 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
665 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800666 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800667 const char *mode =
668 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
669 mOperatingMode == static_cast<int>(
670 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
671 "CUSTOM";
672 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800673
674 if (mInputStream != NULL) {
675 write(fd, lines.string(), lines.size());
676 mInputStream->dump(fd, args);
677 } else {
678 lines.appendFormat(" No input stream.\n");
679 write(fd, lines.string(), lines.size());
680 }
681 for (size_t i = 0; i < mOutputStreams.size(); i++) {
682 mOutputStreams[i]->dump(fd,args);
683 }
684
Zhijun He431503c2016-03-07 17:30:16 -0800685 if (mBufferManager != NULL) {
686 lines = String8(" Camera3 Buffer Manager:\n");
687 write(fd, lines.string(), lines.size());
688 mBufferManager->dump(fd, args);
689 }
Zhijun He125684a2015-12-26 15:07:30 -0800690
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700691 lines = String8(" In-flight requests:\n");
692 if (mInFlightMap.size() == 0) {
693 lines.append(" None\n");
694 } else {
695 for (size_t i = 0; i < mInFlightMap.size(); i++) {
696 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700697 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700698 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800699 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700700 r.numBuffersLeft);
701 }
702 }
703 write(fd, lines.string(), lines.size());
704
Shuzhen Wang686f6442017-06-20 16:16:04 -0700705 if (mRequestThread != NULL) {
706 mRequestThread->dumpCaptureRequestLatency(fd,
707 " ProcessCaptureRequest latency histogram:");
708 }
709
Igor Murashkin1e479c02013-09-06 16:55:14 -0700710 {
711 lines = String8(" Last request sent:\n");
712 write(fd, lines.string(), lines.size());
713
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700714 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700715 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
716 }
717
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800718 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800719 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800720 "TEMPLATE_PREVIEW",
721 "TEMPLATE_STILL_CAPTURE",
722 "TEMPLATE_VIDEO_RECORD",
723 "TEMPLATE_VIDEO_SNAPSHOT",
724 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800725 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800726 };
727
728 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800729 camera_metadata_t *templateRequest = nullptr;
730 mInterface->constructDefaultRequestSettings(
731 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800732 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800733 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800734 lines.append(" Not supported\n");
735 write(fd, lines.string(), lines.size());
736 } else {
737 write(fd, lines.string(), lines.size());
738 dump_indented_camera_metadata(templateRequest,
739 fd, /*verbosity*/2, /*indentation*/8);
740 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800741 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800742 }
743 }
744
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700745 mTagMonitor.dumpMonitoredMetadata(fd);
746
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800747 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800748 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800749 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800750 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800751 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800752
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700753 if (gotLock) mLock.unlock();
754 if (gotInterfaceLock) mInterfaceLock.unlock();
755
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800756 return OK;
757}
758
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700759const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800760 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800761 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
762 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700763 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800764 mStatus == STATUS_ERROR ?
765 "when in error state" : "before init");
766 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700767 if (physicalId.isEmpty()) {
768 return mDeviceInfo;
769 } else {
770 std::string id(physicalId.c_str());
771 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
772 return mPhysicalDeviceInfoMap.at(id);
773 } else {
774 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
775 return mDeviceInfo;
776 }
777 }
778}
779
780const CameraMetadata& Camera3Device::info() const {
781 String8 emptyId;
782 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800783}
784
Jianing Wei90e59c92014-03-12 18:29:36 -0700785status_t Camera3Device::checkStatusOkToCaptureLocked() {
786 switch (mStatus) {
787 case STATUS_ERROR:
788 CLOGE("Device has encountered a serious error");
789 return INVALID_OPERATION;
790 case STATUS_UNINITIALIZED:
791 CLOGE("Device not initialized");
792 return INVALID_OPERATION;
793 case STATUS_UNCONFIGURED:
794 case STATUS_CONFIGURED:
795 case STATUS_ACTIVE:
796 // OK
797 break;
798 default:
799 SET_ERR_L("Unexpected status: %d", mStatus);
800 return INVALID_OPERATION;
801 }
802 return OK;
803}
804
805status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000806 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700807 const std::list<const SurfaceMap> &surfaceMaps,
808 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700809 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700810 if (requestList == NULL) {
811 CLOGE("requestList cannot be NULL.");
812 return BAD_VALUE;
813 }
814
Jianing Weicb0652e2014-03-12 18:29:36 -0700815 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000816 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700817 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
818 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
819 ++metadataIt, ++surfaceMapIt) {
820 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700821 if (newRequest == 0) {
822 CLOGE("Can't create capture request");
823 return BAD_VALUE;
824 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700825
Shuzhen Wang9d066012016-09-30 11:30:20 -0700826 newRequest->mRepeating = repeating;
827
Jianing Weicb0652e2014-03-12 18:29:36 -0700828 // Setup burst Id and request Id
829 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000830 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
831 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700832 CLOGE("RequestID entry exists; but must not be empty in metadata");
833 return BAD_VALUE;
834 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000835 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
836 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700837 } else {
838 CLOGE("RequestID does not exist in metadata");
839 return BAD_VALUE;
840 }
841
Jianing Wei90e59c92014-03-12 18:29:36 -0700842 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700843
844 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700845 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700846 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
847 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
848 return BAD_VALUE;
849 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700850
851 // Setup batch size if this is a high speed video recording request.
852 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
853 auto firstRequest = requestList->begin();
854 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
855 if (outputStream->isVideoStream()) {
856 (*firstRequest)->mBatchSize = requestList->size();
857 break;
858 }
859 }
860 }
861
Jianing Wei90e59c92014-03-12 18:29:36 -0700862 return OK;
863}
864
Jianing Weicb0652e2014-03-12 18:29:36 -0700865status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800866 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800867
Emilian Peevaebbe412018-01-15 13:53:24 +0000868 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700869 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000870 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700871
Emilian Peevaebbe412018-01-15 13:53:24 +0000872 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700873}
874
Emilian Peevaebbe412018-01-15 13:53:24 +0000875void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700876 std::list<const SurfaceMap>& surfaceMaps,
877 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000878 PhysicalCameraSettingsList requestList;
879 requestList.push_back({std::string(getId().string()), request});
880 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700881
882 SurfaceMap surfaceMap;
883 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
884 // With no surface list passed in, stream and surface will have 1-to-1
885 // mapping. So the surface index is 0 for each stream in the surfaceMap.
886 for (size_t i = 0; i < streams.count; i++) {
887 surfaceMap[streams.data.i32[i]].push_back(0);
888 }
889 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800890}
891
Jianing Wei90e59c92014-03-12 18:29:36 -0700892status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000893 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700894 const std::list<const SurfaceMap> &surfaceMaps,
895 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700896 /*out*/
897 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700898 ATRACE_CALL();
899 Mutex::Autolock il(mInterfaceLock);
900 Mutex::Autolock l(mLock);
901
902 status_t res = checkStatusOkToCaptureLocked();
903 if (res != OK) {
904 // error logged by previous call
905 return res;
906 }
907
908 RequestList requestList;
909
Shuzhen Wang0129d522016-10-30 22:43:41 -0700910 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
911 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700912 if (res != OK) {
913 // error logged by previous call
914 return res;
915 }
916
917 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700918 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700919 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700920 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700921 }
922
923 if (res == OK) {
924 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
925 if (res != OK) {
926 SET_ERR_L("Can't transition to active in %f seconds!",
927 kActiveTimeout/1e9);
928 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800929 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700930 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700931 } else {
932 CLOGE("Cannot queue request. Impossible.");
933 return BAD_VALUE;
934 }
935
936 return res;
937}
938
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700939hardware::Return<void> Camera3Device::requestStreamBuffers(
940 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
941 requestStreamBuffers_cb _hidl_cb) {
942 using hardware::camera::device::V3_5::BufferRequestStatus;
943 using hardware::camera::device::V3_5::StreamBufferRet;
944 using hardware::camera::device::V3_5::StreamBufferRequestError;
945
946 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
947
948 hardware::hidl_vec<StreamBufferRet> bufRets;
949 if (!mUseHalBufManager) {
950 ALOGE("%s: Camera %s does not support HAL buffer management",
951 __FUNCTION__, mId.string());
952 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
953 return hardware::Void();
954 }
955
956 SortedVector<int32_t> streamIds;
957 ssize_t sz = streamIds.setCapacity(bufReqs.size());
958 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
959 ALOGE("%s: failed to allocate memory for %zu buffer requests",
960 __FUNCTION__, bufReqs.size());
961 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
962 return hardware::Void();
963 }
964
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700965 if (bufReqs.size() > mOutputStreams.size()) {
966 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
967 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
968 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
969 return hardware::Void();
970 }
971
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700972 // Check for repeated streamId
973 for (const auto& bufReq : bufReqs) {
974 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
975 ALOGE("%s: Stream %d appear multiple times in buffer requests",
976 __FUNCTION__, bufReq.streamId);
977 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
978 return hardware::Void();
979 }
980 streamIds.add(bufReq.streamId);
981 }
982
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700983 if (!mRequestBufferSM.startRequestBuffer()) {
984 ALOGE("%s: request buffer disallowed while camera service is configuring",
985 __FUNCTION__);
986 _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700987 return hardware::Void();
988 }
989
990 bufRets.resize(bufReqs.size());
991
992 bool allReqsSucceeds = true;
993 bool oneReqSucceeds = false;
994 for (size_t i = 0; i < bufReqs.size(); i++) {
995 const auto& bufReq = bufReqs[i];
996 auto& bufRet = bufRets[i];
997 int32_t streamId = bufReq.streamId;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -0700998 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
999 if (outputStream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001000 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
1001 hardware::hidl_vec<StreamBufferRet> emptyBufRets;
1002 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001003 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001004 return hardware::Void();
1005 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001006
1007 bufRet.streamId = streamId;
1008 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
1009 size_t totalHandout = outputStream->getOutstandingBuffersCount() + numBuffersRequested;
1010 if (totalHandout > outputStream->asHalStream()->max_buffers) {
1011 // Not able to allocate enough buffer. Exit early for this stream
1012 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1013 allReqsSucceeds = false;
1014 continue;
1015 }
1016
1017 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1018 bool currentReqSucceeds = true;
1019 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1020 size_t numAllocatedBuffers = 0;
1021 size_t numPushedInflightBuffers = 0;
1022 for (size_t b = 0; b < numBuffersRequested; b++) {
1023 camera3_stream_buffer_t& sb = streamBuffers[b];
1024 // Since this method can run concurrently with request thread
1025 // We need to update the wait duration everytime we call getbuffer
1026 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1027 status_t res = outputStream->getBuffer(&sb, waitDuration);
1028 if (res != OK) {
1029 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1030 __FUNCTION__, streamId, strerror(-res), res);
1031 if (res == NO_INIT || res == DEAD_OBJECT) {
1032 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1033 } else if (res == TIMED_OUT || res == NO_MEMORY) {
1034 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1035 } else {
1036 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1037 }
1038 currentReqSucceeds = false;
1039 break;
1040 }
1041 numAllocatedBuffers++;
1042
1043 buffer_handle_t *buffer = sb.buffer;
1044 auto pair = mInterface->getBufferId(*buffer, streamId);
1045 bool isNewBuffer = pair.first;
1046 uint64_t bufferId = pair.second;
1047 StreamBuffer& hBuf = tmpRetBuffers[b];
1048
1049 hBuf.streamId = streamId;
1050 hBuf.bufferId = bufferId;
1051 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1052 hBuf.status = BufferStatus::OK;
1053 hBuf.releaseFence = nullptr;
1054
1055 native_handle_t *acquireFence = nullptr;
1056 if (sb.acquire_fence != -1) {
1057 acquireFence = native_handle_create(1,0);
1058 acquireFence->data[0] = sb.acquire_fence;
1059 }
1060 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1061 hBuf.releaseFence = nullptr;
1062
1063 res = mInterface->pushInflightRequestBuffer(bufferId, buffer);
1064 if (res != OK) {
1065 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1066 __FUNCTION__, streamId, strerror(-res), res);
1067 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1068 currentReqSucceeds = false;
1069 break;
1070 }
1071 numPushedInflightBuffers++;
1072 }
1073 if (currentReqSucceeds) {
1074 bufRet.val.buffers(std::move(tmpRetBuffers));
1075 oneReqSucceeds = true;
1076 } else {
1077 allReqsSucceeds = false;
1078 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1079 StreamBuffer& hBuf = tmpRetBuffers[b];
1080 buffer_handle_t* buffer;
1081 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1082 if (res != OK) {
1083 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1084 __FUNCTION__, streamId, strerror(-res), res);
1085 }
1086 }
1087 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1088 }
1089 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001090
1091 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1092 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1093 BufferRequestStatus::FAILED_UNKNOWN,
1094 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001095 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001096 return hardware::Void();
1097}
1098
1099hardware::Return<void> Camera3Device::returnStreamBuffers(
1100 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1101 if (!mUseHalBufManager) {
1102 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1103 __FUNCTION__, mId.string());
1104 return hardware::Void();
1105 }
1106
1107 for (const auto& buf : buffers) {
1108 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1109 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1110 continue;
1111 }
1112
1113 buffer_handle_t* buffer;
1114 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1115
1116 if (res != OK) {
1117 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1118 __FUNCTION__, buf.bufferId, buf.streamId);
1119 continue;
1120 }
1121
1122 camera3_stream_buffer_t streamBuffer;
1123 streamBuffer.buffer = buffer;
1124 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1125 streamBuffer.acquire_fence = -1;
1126 streamBuffer.release_fence = -1;
1127
1128 if (buf.releaseFence == nullptr) {
1129 streamBuffer.release_fence = -1;
1130 } else if (buf.releaseFence->numFds == 1) {
1131 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1132 } else {
1133 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1134 __FUNCTION__, buf.releaseFence->numFds);
1135 continue;
1136 }
1137
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001138 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1139 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001140 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1141 continue;
1142 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001143 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001144 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1145 }
1146 return hardware::Void();
1147}
1148
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001149hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001150 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001151 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001152 // Ideally we should grab mLock, but that can lead to deadlock, and
1153 // it's not super important to get up to date value of mStatus for this
1154 // warning print, hence skipping the lock here
1155 if (mStatus == STATUS_ERROR) {
1156 // Per API contract, HAL should act as closed after device error
1157 // But mStatus can be set to error by framework as well, so just log
1158 // a warning here.
1159 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001160 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001161
1162 if (mProcessCaptureResultLock.tryLock() != OK) {
1163 // This should never happen; it indicates a wrong client implementation
1164 // that doesn't follow the contract. But, we can be tolerant here.
1165 ALOGE("%s: callback overlapped! waiting 1s...",
1166 __FUNCTION__);
1167 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1168 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1169 __FUNCTION__);
1170 // really don't know what to do, so bail out.
1171 return hardware::Void();
1172 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001173 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001174 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001175 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001176 }
1177 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001178 return hardware::Void();
1179}
1180
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001181// Only one processCaptureResult should be called at a time, so
1182// the locks won't block. The locks are present here simply to enforce this.
1183hardware::Return<void> Camera3Device::processCaptureResult(
1184 const hardware::hidl_vec<
1185 hardware::camera::device::V3_2::CaptureResult>& results) {
1186 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1187
1188 // Ideally we should grab mLock, but that can lead to deadlock, and
1189 // it's not super important to get up to date value of mStatus for this
1190 // warning print, hence skipping the lock here
1191 if (mStatus == STATUS_ERROR) {
1192 // Per API contract, HAL should act as closed after device error
1193 // But mStatus can be set to error by framework as well, so just log
1194 // a warning here.
1195 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1196 }
1197
1198 if (mProcessCaptureResultLock.tryLock() != OK) {
1199 // This should never happen; it indicates a wrong client implementation
1200 // that doesn't follow the contract. But, we can be tolerant here.
1201 ALOGE("%s: callback overlapped! waiting 1s...",
1202 __FUNCTION__);
1203 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1204 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1205 __FUNCTION__);
1206 // really don't know what to do, so bail out.
1207 return hardware::Void();
1208 }
1209 }
1210 for (const auto& result : results) {
1211 processOneCaptureResultLocked(result, noPhysMetadata);
1212 }
1213 mProcessCaptureResultLock.unlock();
1214 return hardware::Void();
1215}
1216
1217status_t Camera3Device::readOneCameraMetadataLocked(
1218 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1219 const hardware::camera::device::V3_2::CameraMetadata& result) {
1220 if (fmqResultSize > 0) {
1221 resultMetadata.resize(fmqResultSize);
1222 if (mResultMetadataQueue == nullptr) {
1223 return NO_MEMORY; // logged in initialize()
1224 }
1225 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1226 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1227 __FUNCTION__, fmqResultSize);
1228 return INVALID_OPERATION;
1229 }
1230 } else {
1231 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1232 result.size());
1233 }
1234
1235 if (resultMetadata.size() != 0) {
1236 status_t res;
1237 const camera_metadata_t* metadata =
1238 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1239 size_t expected_metadata_size = resultMetadata.size();
1240 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1241 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1242 __FUNCTION__, strerror(-res), res);
1243 return INVALID_OPERATION;
1244 }
1245 }
1246
1247 return OK;
1248}
1249
Yifan Honga640c5a2017-04-12 16:30:31 -07001250void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001251 const hardware::camera::device::V3_2::CaptureResult& result,
1252 const hardware::hidl_vec<
1253 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001254 camera3_capture_result r;
1255 status_t res;
1256 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001257
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001258 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001259 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001260 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1261 if (res != OK) {
1262 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1263 __FUNCTION__, result.frameNumber);
1264 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001265 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001266 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001267
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001268 // Read and validate physical camera metadata
1269 size_t physResultCount = physicalCameraMetadatas.size();
1270 std::vector<const char*> physCamIds(physResultCount);
1271 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1272 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1273 physResultMetadata.resize(physResultCount);
1274 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1275 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1276 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1277 if (res != OK) {
1278 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1279 __FUNCTION__, result.frameNumber,
1280 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001281 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001282 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001283 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1284 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1285 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001286 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001287 r.num_physcam_metadata = physResultCount;
1288 r.physcam_ids = physCamIds.data();
1289 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001290
1291 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1292 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1293 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1294 auto& bDst = outputBuffers[i];
1295 const StreamBuffer &bSrc = result.outputBuffers[i];
1296
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001297 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1298 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001299 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1300 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001301 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001302 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001303 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001304
1305 buffer_handle_t *buffer;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001306 if (mUseHalBufManager) {
1307 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1308 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1309 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1310 return;
1311 }
1312 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1313 } else {
1314 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1315 }
1316
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001317 if (res != OK) {
1318 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1319 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001320 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001321 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001322
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001323 bDst.buffer = buffer;
1324 bDst.status = mapHidlBufferStatus(bSrc.status);
1325 bDst.acquire_fence = -1;
1326 if (bSrc.releaseFence == nullptr) {
1327 bDst.release_fence = -1;
1328 } else if (bSrc.releaseFence->numFds == 1) {
1329 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1330 } else {
1331 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1332 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001333 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001334 }
1335 }
1336 r.num_output_buffers = outputBuffers.size();
1337 r.output_buffers = outputBuffers.data();
1338
1339 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001340 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001341 r.input_buffer = nullptr;
1342 } else {
1343 if (mInputStream->getId() != result.inputBuffer.streamId) {
1344 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1345 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001346 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001347 }
1348 inputBuffer.stream = mInputStream->asHalStream();
1349 buffer_handle_t *buffer;
1350 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1351 &buffer);
1352 if (res != OK) {
1353 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1354 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001355 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001356 }
1357 inputBuffer.buffer = buffer;
1358 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1359 inputBuffer.acquire_fence = -1;
1360 if (result.inputBuffer.releaseFence == nullptr) {
1361 inputBuffer.release_fence = -1;
1362 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1363 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1364 } else {
1365 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1366 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001367 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001368 }
1369 r.input_buffer = &inputBuffer;
1370 }
1371
1372 r.partial_result = result.partialResult;
1373
1374 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001375}
1376
1377hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001378 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001379 // Ideally we should grab mLock, but that can lead to deadlock, and
1380 // it's not super important to get up to date value of mStatus for this
1381 // warning print, hence skipping the lock here
1382 if (mStatus == STATUS_ERROR) {
1383 // Per API contract, HAL should act as closed after device error
1384 // But mStatus can be set to error by framework as well, so just log
1385 // a warning here.
1386 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001387 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001388
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001389 for (const auto& msg : msgs) {
1390 notify(msg);
1391 }
1392 return hardware::Void();
1393}
1394
1395void Camera3Device::notify(
1396 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1397
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001398 camera3_notify_msg m;
1399 switch (msg.type) {
1400 case MsgType::ERROR:
1401 m.type = CAMERA3_MSG_ERROR;
1402 m.message.error.frame_number = msg.msg.error.frameNumber;
1403 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001404 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1405 if (stream == nullptr) {
1406 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1407 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001408 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001409 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001410 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001411 } else {
1412 m.message.error.error_stream = nullptr;
1413 }
1414 switch (msg.msg.error.errorCode) {
1415 case ErrorCode::ERROR_DEVICE:
1416 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1417 break;
1418 case ErrorCode::ERROR_REQUEST:
1419 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1420 break;
1421 case ErrorCode::ERROR_RESULT:
1422 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1423 break;
1424 case ErrorCode::ERROR_BUFFER:
1425 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1426 break;
1427 }
1428 break;
1429 case MsgType::SHUTTER:
1430 m.type = CAMERA3_MSG_SHUTTER;
1431 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1432 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1433 break;
1434 }
1435 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001436}
1437
Emilian Peevaebbe412018-01-15 13:53:24 +00001438status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001439 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001440 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001441 ATRACE_CALL();
1442
Emilian Peevaebbe412018-01-15 13:53:24 +00001443 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001444}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001445
Jianing Weicb0652e2014-03-12 18:29:36 -07001446status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1447 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001448 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001449
Emilian Peevaebbe412018-01-15 13:53:24 +00001450 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001451 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001452 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001453
Emilian Peevaebbe412018-01-15 13:53:24 +00001454 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001455 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001456}
1457
Emilian Peevaebbe412018-01-15 13:53:24 +00001458status_t Camera3Device::setStreamingRequestList(
1459 const List<const PhysicalCameraSettingsList> &requestsList,
1460 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001461 ATRACE_CALL();
1462
Emilian Peevaebbe412018-01-15 13:53:24 +00001463 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001464}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001465
1466sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001467 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001468 status_t res;
1469
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001470 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001471 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1472 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001473 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1474 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001475 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001476 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001477 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001478 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001479 } else if (mStatus == STATUS_UNCONFIGURED) {
1480 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001481 CLOGE("No streams configured");
1482 return NULL;
1483 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 }
1485
Shuzhen Wang0129d522016-10-30 22:43:41 -07001486 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001487 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001488}
1489
Jianing Weicb0652e2014-03-12 18:29:36 -07001490status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001491 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001492 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001493 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001494
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 switch (mStatus) {
1496 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001497 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 return INVALID_OPERATION;
1499 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001500 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001501 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001502 case STATUS_UNCONFIGURED:
1503 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001504 case STATUS_ACTIVE:
1505 // OK
1506 break;
1507 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001508 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001509 return INVALID_OPERATION;
1510 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001511 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001512
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001513 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001514}
1515
1516status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1517 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001518 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001519
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001520 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001521}
1522
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001523status_t Camera3Device::createInputStream(
1524 uint32_t width, uint32_t height, int format, int *id) {
1525 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001526 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001527 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001528 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001529 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1530 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001531
1532 status_t res;
1533 bool wasActive = false;
1534
1535 switch (mStatus) {
1536 case STATUS_ERROR:
1537 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1538 return INVALID_OPERATION;
1539 case STATUS_UNINITIALIZED:
1540 ALOGE("%s: Device not initialized", __FUNCTION__);
1541 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001542 case STATUS_UNCONFIGURED:
1543 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001544 // OK
1545 break;
1546 case STATUS_ACTIVE:
1547 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001548 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001549 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001550 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001551 return res;
1552 }
1553 wasActive = true;
1554 break;
1555 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001556 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001557 return INVALID_OPERATION;
1558 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001559 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001560
1561 if (mInputStream != 0) {
1562 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1563 return INVALID_OPERATION;
1564 }
1565
1566 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1567 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001568 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001569
1570 mInputStream = newStream;
1571
1572 *id = mNextStreamId++;
1573
1574 // Continue captures if active at start
1575 if (wasActive) {
1576 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001577 // Reuse current operating mode and session parameters for new stream config
1578 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001579 if (res != OK) {
1580 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1581 __FUNCTION__, mNextStreamId, strerror(-res), res);
1582 return res;
1583 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001584 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001585 }
1586
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001587 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001588 return OK;
1589}
1590
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001591status_t Camera3Device::StreamSet::add(
1592 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1593 if (stream == nullptr) {
1594 ALOGE("%s: cannot add null stream", __FUNCTION__);
1595 return BAD_VALUE;
1596 }
1597 std::lock_guard<std::mutex> lock(mLock);
1598 return mData.add(streamId, stream);
1599}
1600
1601ssize_t Camera3Device::StreamSet::remove(int streamId) {
1602 std::lock_guard<std::mutex> lock(mLock);
1603 return mData.removeItem(streamId);
1604}
1605
1606sp<camera3::Camera3OutputStreamInterface>
1607Camera3Device::StreamSet::get(int streamId) {
1608 std::lock_guard<std::mutex> lock(mLock);
1609 ssize_t idx = mData.indexOfKey(streamId);
1610 if (idx == NAME_NOT_FOUND) {
1611 return nullptr;
1612 }
1613 return mData.editValueAt(idx);
1614}
1615
1616sp<camera3::Camera3OutputStreamInterface>
1617Camera3Device::StreamSet::operator[] (size_t index) {
1618 std::lock_guard<std::mutex> lock(mLock);
1619 return mData.editValueAt(index);
1620}
1621
1622size_t Camera3Device::StreamSet::size() const {
1623 std::lock_guard<std::mutex> lock(mLock);
1624 return mData.size();
1625}
1626
1627void Camera3Device::StreamSet::clear() {
1628 std::lock_guard<std::mutex> lock(mLock);
1629 return mData.clear();
1630}
1631
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001632std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1633 std::lock_guard<std::mutex> lock(mLock);
1634 std::vector<int> streamIds(mData.size());
1635 for (size_t i = 0; i < mData.size(); i++) {
1636 streamIds[i] = mData.keyAt(i);
1637 }
1638 return streamIds;
1639}
1640
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001641status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001642 uint32_t width, uint32_t height, int format,
1643 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001644 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001645 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001646 ATRACE_CALL();
1647
1648 if (consumer == nullptr) {
1649 ALOGE("%s: consumer must not be null", __FUNCTION__);
1650 return BAD_VALUE;
1651 }
1652
1653 std::vector<sp<Surface>> consumers;
1654 consumers.push_back(consumer);
1655
1656 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001657 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1658 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001659}
1660
1661status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1662 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1663 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001664 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001665 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001666 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001667
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001668 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001669 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001670 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001671 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001672 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1673 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1674 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001675
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001676 status_t res;
1677 bool wasActive = false;
1678
1679 switch (mStatus) {
1680 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001681 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001682 return INVALID_OPERATION;
1683 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001684 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001685 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001686 case STATUS_UNCONFIGURED:
1687 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001688 // OK
1689 break;
1690 case STATUS_ACTIVE:
1691 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001692 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001693 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001694 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001695 return res;
1696 }
1697 wasActive = true;
1698 break;
1699 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001700 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001701 return INVALID_OPERATION;
1702 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001703 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001704
1705 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001706
Shuzhen Wang0129d522016-10-30 22:43:41 -07001707 if (consumers.size() == 0 && !hasDeferredConsumer) {
1708 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1709 return BAD_VALUE;
1710 }
Zhijun He5d677d12016-05-29 16:52:39 -07001711
Shuzhen Wang0129d522016-10-30 22:43:41 -07001712 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001713 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1714 return BAD_VALUE;
1715 }
1716
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001717 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001718 ssize_t blobBufferSize;
1719 if (dataSpace != HAL_DATASPACE_DEPTH) {
1720 blobBufferSize = getJpegBufferSize(width, height);
1721 if (blobBufferSize <= 0) {
1722 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1723 return BAD_VALUE;
1724 }
1725 } else {
1726 blobBufferSize = getPointCloudBufferSize();
1727 if (blobBufferSize <= 0) {
1728 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1729 return BAD_VALUE;
1730 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001731 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001732 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001733 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001734 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001735 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1736 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1737 if (rawOpaqueBufferSize <= 0) {
1738 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1739 return BAD_VALUE;
1740 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001741 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001742 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001743 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001744 } else if (isShared) {
1745 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1746 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001747 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001748 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001749 newStream = new Camera3OutputStream(mNextStreamId,
1750 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001751 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001752 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001753 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001754 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001755 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001756 }
Emilian Peev40ead602017-09-26 15:46:36 +01001757
1758 size_t consumerCount = consumers.size();
1759 for (size_t i = 0; i < consumerCount; i++) {
1760 int id = newStream->getSurfaceId(consumers[i]);
1761 if (id < 0) {
1762 SET_ERR_L("Invalid surface id");
1763 return BAD_VALUE;
1764 }
1765 if (surfaceIds != nullptr) {
1766 surfaceIds->push_back(id);
1767 }
1768 }
1769
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001770 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001771
Emilian Peev08dd2452017-04-06 16:55:14 +01001772 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001773
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001774 res = mOutputStreams.add(mNextStreamId, newStream);
1775 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001776 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001777 return res;
1778 }
1779
1780 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001781 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001782
1783 // Continue captures if active at start
1784 if (wasActive) {
1785 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001786 // Reuse current operating mode and session parameters for new stream config
1787 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001788 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001789 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1790 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001791 return res;
1792 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001793 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001794 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001795 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001796 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001797}
1798
Emilian Peev710c1422017-08-30 11:19:38 +01001799status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001800 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001801 if (nullptr == streamInfo) {
1802 return BAD_VALUE;
1803 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001804 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001805 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001806
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001807 switch (mStatus) {
1808 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001809 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001810 return INVALID_OPERATION;
1811 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001812 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001813 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001814 case STATUS_UNCONFIGURED:
1815 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001816 case STATUS_ACTIVE:
1817 // OK
1818 break;
1819 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001820 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001821 return INVALID_OPERATION;
1822 }
1823
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001824 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1825 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001826 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001827 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001828 }
1829
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001830 streamInfo->width = stream->getWidth();
1831 streamInfo->height = stream->getHeight();
1832 streamInfo->format = stream->getFormat();
1833 streamInfo->dataSpace = stream->getDataSpace();
1834 streamInfo->formatOverridden = stream->isFormatOverridden();
1835 streamInfo->originalFormat = stream->getOriginalFormat();
1836 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1837 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001838 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001839}
1840
1841status_t Camera3Device::setStreamTransform(int id,
1842 int transform) {
1843 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001844 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001845 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001846
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001847 switch (mStatus) {
1848 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001849 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001850 return INVALID_OPERATION;
1851 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001852 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001853 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001854 case STATUS_UNCONFIGURED:
1855 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001856 case STATUS_ACTIVE:
1857 // OK
1858 break;
1859 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001860 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001861 return INVALID_OPERATION;
1862 }
1863
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001864 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1865 if (stream == nullptr) {
1866 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001867 return BAD_VALUE;
1868 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001869 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001870}
1871
1872status_t Camera3Device::deleteStream(int id) {
1873 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001874 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001875 Mutex::Autolock l(mLock);
1876 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001877
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001878 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001879
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001880 // CameraDevice semantics require device to already be idle before
1881 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001882 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001883 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001884 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001885 }
1886
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001887 if (mStatus == STATUS_ERROR) {
1888 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1889 __FUNCTION__, mId.string());
1890 return -EBUSY;
1891 }
1892
Igor Murashkin2fba5842013-04-22 14:03:54 -07001893 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001894 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001895 if (mInputStream != NULL && id == mInputStream->getId()) {
1896 deletedStream = mInputStream;
1897 mInputStream.clear();
1898 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001899 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001900 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001901 return BAD_VALUE;
1902 }
Zhijun He5f446352014-01-22 09:49:33 -08001903 }
1904
1905 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001906 if (stream != nullptr) {
1907 deletedStream = stream;
1908 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001909 }
1910
1911 // Free up the stream endpoint so that it can be used by some other stream
1912 res = deletedStream->disconnect();
1913 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001914 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001915 // fall through since we want to still list the stream as deleted.
1916 }
1917 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001918 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001919
1920 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001921}
1922
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001923status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001924 ATRACE_CALL();
1925 ALOGV("%s: E", __FUNCTION__);
1926
1927 Mutex::Autolock il(mInterfaceLock);
1928 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001929
Emilian Peev811d2952018-05-25 11:08:40 +01001930 // In case the client doesn't include any session parameter, try a
1931 // speculative configuration using the values from the last cached
1932 // default request.
1933 if (sessionParams.isEmpty() &&
1934 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1935 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1936 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1937 mLastTemplateId);
1938 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1939 operatingMode);
1940 }
1941
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001942 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1943}
1944
1945status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1946 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001947 //Filter out any incoming session parameters
1948 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001949 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1950 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001951 CameraMetadata filteredParams(availableSessionKeys.count);
1952 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1953 filteredParams.getAndLock());
1954 set_camera_metadata_vendor_id(meta, mVendorTagId);
1955 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001956 if (availableSessionKeys.count > 0) {
1957 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1958 camera_metadata_ro_entry entry = params.find(
1959 availableSessionKeys.data.i32[i]);
1960 if (entry.count > 0) {
1961 filteredParams.update(entry);
1962 }
1963 }
1964 }
1965
1966 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001967}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001968
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001969status_t Camera3Device::getInputBufferProducer(
1970 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001971 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001972 Mutex::Autolock il(mInterfaceLock);
1973 Mutex::Autolock l(mLock);
1974
1975 if (producer == NULL) {
1976 return BAD_VALUE;
1977 } else if (mInputStream == NULL) {
1978 return INVALID_OPERATION;
1979 }
1980
1981 return mInputStream->getInputBufferProducer(producer);
1982}
1983
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001984status_t Camera3Device::createDefaultRequest(int templateId,
1985 CameraMetadata *request) {
1986 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001987 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001988
1989 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1990 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001991 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001992 return BAD_VALUE;
1993 }
1994
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001995 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001996
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001997 {
1998 Mutex::Autolock l(mLock);
1999 switch (mStatus) {
2000 case STATUS_ERROR:
2001 CLOGE("Device has encountered a serious error");
2002 return INVALID_OPERATION;
2003 case STATUS_UNINITIALIZED:
2004 CLOGE("Device is not initialized!");
2005 return INVALID_OPERATION;
2006 case STATUS_UNCONFIGURED:
2007 case STATUS_CONFIGURED:
2008 case STATUS_ACTIVE:
2009 // OK
2010 break;
2011 default:
2012 SET_ERR_L("Unexpected status: %d", mStatus);
2013 return INVALID_OPERATION;
2014 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002015
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002016 if (!mRequestTemplateCache[templateId].isEmpty()) {
2017 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002018 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002019 return OK;
2020 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002021 }
2022
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002023 camera_metadata_t *rawRequest;
2024 status_t res = mInterface->constructDefaultRequestSettings(
2025 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002026
2027 {
2028 Mutex::Autolock l(mLock);
2029 if (res == BAD_VALUE) {
2030 ALOGI("%s: template %d is not supported on this camera device",
2031 __FUNCTION__, templateId);
2032 return res;
2033 } else if (res != OK) {
2034 CLOGE("Unable to construct request template %d: %s (%d)",
2035 templateId, strerror(-res), res);
2036 return res;
2037 }
2038
2039 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2040 mRequestTemplateCache[templateId].acquire(rawRequest);
2041
2042 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002043 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002044 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002045 return OK;
2046}
2047
2048status_t Camera3Device::waitUntilDrained() {
2049 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002050 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002051 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002052 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002053
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002054 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002055}
2056
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002057status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002058 switch (mStatus) {
2059 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002060 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002061 ALOGV("%s: Already idle", __FUNCTION__);
2062 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002063 case STATUS_CONFIGURED:
2064 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002065 case STATUS_ERROR:
2066 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002067 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002068 break;
2069 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002070 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002071 return INVALID_OPERATION;
2072 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002073 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2074 maxExpectedDuration);
2075 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002076 if (res != OK) {
2077 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2078 res);
2079 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002080 return res;
2081}
2082
Ruben Brunk183f0562015-08-12 12:55:02 -07002083
2084void Camera3Device::internalUpdateStatusLocked(Status status) {
2085 mStatus = status;
2086 mRecentStatusUpdates.add(mStatus);
2087 mStatusChanged.broadcast();
2088}
2089
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002090void Camera3Device::pauseStateNotify(bool enable) {
2091 Mutex::Autolock il(mInterfaceLock);
2092 Mutex::Autolock l(mLock);
2093
2094 mPauseStateNotify = enable;
2095}
2096
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002097// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002098status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002099 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002100
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002101 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2102 maxExpectedDuration);
2103 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002104 if (res != OK) {
2105 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002106 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002107 }
2108
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002109 return res;
2110}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002111
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002112// Resume after internalPauseAndWaitLocked
2113status_t Camera3Device::internalResumeLocked() {
2114 status_t res;
2115
2116 mRequestThread->setPaused(false);
2117
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002118 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2119 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002120 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2121 if (res != OK) {
2122 SET_ERR_L("Can't transition to active in %f seconds!",
2123 kActiveTimeout/1e9);
2124 }
2125 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002126 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002127}
2128
Ruben Brunk183f0562015-08-12 12:55:02 -07002129status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002130 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002131
2132 size_t startIndex = 0;
2133 if (mStatusWaiters == 0) {
2134 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2135 // this status list
2136 mRecentStatusUpdates.clear();
2137 } else {
2138 // If other threads are waiting on updates to this status list, set the position of the
2139 // first element that this list will check rather than clearing the list.
2140 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002141 }
2142
Ruben Brunk183f0562015-08-12 12:55:02 -07002143 mStatusWaiters++;
2144
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002145 // Notify HAL to start draining. We need to notify the HalInterface layer
2146 // even when the device is already IDLE, so HalInterface can reject incoming
2147 // requestStreamBuffers call.
2148 if (!active && mUseHalBufManager) {
2149 auto streamIds = mOutputStreams.getStreamIds();
2150 mRequestThread->signalPipelineDrain(streamIds);
2151 mRequestBufferSM.onWaitUntilIdle();
2152 }
2153
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002154 bool stateSeen = false;
2155 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002156 if (active == (mStatus == STATUS_ACTIVE)) {
2157 // Desired state is current
2158 break;
2159 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002160
2161 res = mStatusChanged.waitRelative(mLock, timeout);
2162 if (res != OK) break;
2163
Ruben Brunk183f0562015-08-12 12:55:02 -07002164 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2165 // transitions.
2166 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2167 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2168 __FUNCTION__);
2169
2170 // Encountered desired state since we began waiting
2171 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002172 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2173 stateSeen = true;
2174 break;
2175 }
2176 }
2177 } while (!stateSeen);
2178
Ruben Brunk183f0562015-08-12 12:55:02 -07002179 mStatusWaiters--;
2180
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002181 return res;
2182}
2183
2184
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002185status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002186 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002187 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002188
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002189 if (listener != NULL && mListener != NULL) {
2190 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2191 }
2192 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002193 mRequestThread->setNotificationListener(listener);
2194 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002195
2196 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002197}
2198
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002199bool Camera3Device::willNotify3A() {
2200 return false;
2201}
2202
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002203status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002204 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002205 status_t res;
2206 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002207
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002208 while (mResultQueue.empty()) {
2209 res = mResultSignal.waitRelative(mOutputLock, timeout);
2210 if (res == TIMED_OUT) {
2211 return res;
2212 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002213 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2214 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002215 return res;
2216 }
2217 }
2218 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002219}
2220
Jianing Weicb0652e2014-03-12 18:29:36 -07002221status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002222 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002223 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002224
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002225 if (mResultQueue.empty()) {
2226 return NOT_ENOUGH_DATA;
2227 }
2228
Jianing Weicb0652e2014-03-12 18:29:36 -07002229 if (frame == NULL) {
2230 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2231 return BAD_VALUE;
2232 }
2233
2234 CaptureResult &result = *(mResultQueue.begin());
2235 frame->mResultExtras = result.mResultExtras;
2236 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002237 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002238 mResultQueue.erase(mResultQueue.begin());
2239
2240 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002241}
2242
2243status_t Camera3Device::triggerAutofocus(uint32_t id) {
2244 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002245 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002246
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002247 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2248 // Mix-in this trigger into the next request and only the next request.
2249 RequestTrigger trigger[] = {
2250 {
2251 ANDROID_CONTROL_AF_TRIGGER,
2252 ANDROID_CONTROL_AF_TRIGGER_START
2253 },
2254 {
2255 ANDROID_CONTROL_AF_TRIGGER_ID,
2256 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002257 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002258 };
2259
2260 return mRequestThread->queueTrigger(trigger,
2261 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002262}
2263
2264status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2265 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002266 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002267
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002268 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2269 // Mix-in this trigger into the next request and only the next request.
2270 RequestTrigger trigger[] = {
2271 {
2272 ANDROID_CONTROL_AF_TRIGGER,
2273 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2274 },
2275 {
2276 ANDROID_CONTROL_AF_TRIGGER_ID,
2277 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002278 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002279 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002280
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002281 return mRequestThread->queueTrigger(trigger,
2282 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002283}
2284
2285status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2286 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002287 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002288
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002289 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2290 // Mix-in this trigger into the next request and only the next request.
2291 RequestTrigger trigger[] = {
2292 {
2293 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2294 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2295 },
2296 {
2297 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2298 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002299 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002300 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002301
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002302 return mRequestThread->queueTrigger(trigger,
2303 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002304}
2305
Jianing Weicb0652e2014-03-12 18:29:36 -07002306status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002307 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002308 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002309 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002310
Zhijun He7ef20392014-04-21 16:04:17 -07002311 {
2312 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002313
2314 // b/116514106 "disconnect()" can get called twice for the same device. The
2315 // camera device will not be initialized during the second run.
2316 if (mStatus == STATUS_UNINITIALIZED) {
2317 return OK;
2318 }
2319
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002320 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002321 }
2322
Emilian Peev08dd2452017-04-06 16:55:14 +01002323 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002324}
2325
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002326status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002327 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2328}
2329
2330status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002331 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002332 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002333 Mutex::Autolock il(mInterfaceLock);
2334 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002335
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002336 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2337 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002338 CLOGE("Stream %d does not exist", streamId);
2339 return BAD_VALUE;
2340 }
2341
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002342 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002343 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002344 return BAD_VALUE;
2345 }
2346
2347 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002348 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002349 return BAD_VALUE;
2350 }
2351
Ruben Brunkc78ac262015-08-13 17:58:46 -07002352 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002353}
2354
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002355status_t Camera3Device::tearDown(int streamId) {
2356 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002357 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002358 Mutex::Autolock il(mInterfaceLock);
2359 Mutex::Autolock l(mLock);
2360
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002361 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2362 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002363 CLOGE("Stream %d does not exist", streamId);
2364 return BAD_VALUE;
2365 }
2366
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002367 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2368 CLOGE("Stream %d is a target of a in-progress request", streamId);
2369 return BAD_VALUE;
2370 }
2371
2372 return stream->tearDown();
2373}
2374
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002375status_t Camera3Device::addBufferListenerForStream(int streamId,
2376 wp<Camera3StreamBufferListener> listener) {
2377 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002378 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002379 Mutex::Autolock il(mInterfaceLock);
2380 Mutex::Autolock l(mLock);
2381
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002382 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2383 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002384 CLOGE("Stream %d does not exist", streamId);
2385 return BAD_VALUE;
2386 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002387 stream->addBufferListener(listener);
2388
2389 return OK;
2390}
2391
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002392/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002393 * Methods called by subclasses
2394 */
2395
2396void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002397 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002398 {
2399 // Need mLock to safely update state and synchronize to current
2400 // state of methods in flight.
2401 Mutex::Autolock l(mLock);
2402 // We can get various system-idle notices from the status tracker
2403 // while starting up. Only care about them if we've actually sent
2404 // in some requests recently.
2405 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2406 return;
2407 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002408 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2409 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002410 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002411
2412 // Skip notifying listener if we're doing some user-transparent
2413 // state changes
2414 if (mPauseStateNotify) return;
2415 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002416
2417 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002418 {
2419 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002420 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002421 }
2422 if (idle && listener != NULL) {
2423 listener->notifyIdle();
2424 }
2425}
2426
Shuzhen Wang758c2152017-01-10 18:26:18 -08002427status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002428 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002429 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002430 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2431 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002432
2433 if (surfaceIds == nullptr) {
2434 return BAD_VALUE;
2435 }
2436
Zhijun He5d677d12016-05-29 16:52:39 -07002437 Mutex::Autolock il(mInterfaceLock);
2438 Mutex::Autolock l(mLock);
2439
Shuzhen Wang758c2152017-01-10 18:26:18 -08002440 if (consumers.size() == 0) {
2441 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002442 return BAD_VALUE;
2443 }
2444
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002445 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2446 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002447 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002448 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002449 }
Shuzhen Wang758c2152017-01-10 18:26:18 -08002450 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002451 if (res != OK) {
2452 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2453 return res;
2454 }
2455
Emilian Peev40ead602017-09-26 15:46:36 +01002456 for (auto &consumer : consumers) {
2457 int id = stream->getSurfaceId(consumer);
2458 if (id < 0) {
2459 CLOGE("Invalid surface id!");
2460 return BAD_VALUE;
2461 }
2462 surfaceIds->push_back(id);
2463 }
2464
Shuzhen Wang0129d522016-10-30 22:43:41 -07002465 if (stream->isConsumerConfigurationDeferred()) {
2466 if (!stream->isConfiguring()) {
2467 CLOGE("Stream %d was already fully configured.", streamId);
2468 return INVALID_OPERATION;
2469 }
Zhijun He5d677d12016-05-29 16:52:39 -07002470
Shuzhen Wang0129d522016-10-30 22:43:41 -07002471 res = stream->finishConfiguration();
2472 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002473 // If finishConfiguration fails due to abandoned surface, do not set
2474 // device to error state.
2475 bool isSurfaceAbandoned =
2476 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2477 if (!isSurfaceAbandoned) {
2478 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2479 stream->getId(), strerror(-res), res);
2480 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002481 return res;
2482 }
Zhijun He5d677d12016-05-29 16:52:39 -07002483 }
2484
2485 return OK;
2486}
2487
Emilian Peev40ead602017-09-26 15:46:36 +01002488status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2489 const std::vector<OutputStreamInfo> &outputInfo,
2490 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2491 Mutex::Autolock il(mInterfaceLock);
2492 Mutex::Autolock l(mLock);
2493
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002494 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2495 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002496 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002497 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002498 }
2499
2500 for (const auto &it : removedSurfaceIds) {
2501 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2502 CLOGE("Shared surface still part of a pending request!");
2503 return -EBUSY;
2504 }
2505 }
2506
Emilian Peev40ead602017-09-26 15:46:36 +01002507 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2508 if (res != OK) {
2509 CLOGE("Stream %d failed to update stream (error %d %s) ",
2510 streamId, res, strerror(-res));
2511 if (res == UNKNOWN_ERROR) {
2512 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2513 __FUNCTION__);
2514 }
2515 return res;
2516 }
2517
2518 return res;
2519}
2520
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002521status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2522 Mutex::Autolock il(mInterfaceLock);
2523 Mutex::Autolock l(mLock);
2524
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002525 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2526 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002527 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2528 return BAD_VALUE;
2529 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002530 return stream->dropBuffers(dropping);
2531}
2532
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002533/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002534 * Camera3Device private methods
2535 */
2536
2537sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002538 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002539 ATRACE_CALL();
2540 status_t res;
2541
2542 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002543 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002544
2545 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002546 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002547 if (inputStreams.count > 0) {
2548 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002549 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002550 CLOGE("Request references unknown input stream %d",
2551 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002552 return NULL;
2553 }
2554 // Lazy completion of stream configuration (allocation/registration)
2555 // on first use
2556 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002557 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002558 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002559 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002560 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002561 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002562 return NULL;
2563 }
2564 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002565 // Check if stream prepare is blocking requests.
2566 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002567 CLOGE("Request references an input stream that's being prepared!");
2568 return NULL;
2569 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002570
2571 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002572 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002573 }
2574
2575 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002576 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002577 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002578 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002579 return NULL;
2580 }
2581
2582 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002583 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2584 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002585 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002586 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002587 return NULL;
2588 }
Zhijun He5d677d12016-05-29 16:52:39 -07002589 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002590 auto iter = surfaceMap.find(streams.data.i32[i]);
2591 if (iter != surfaceMap.end()) {
2592 const std::vector<size_t>& surfaces = iter->second;
2593 for (const auto& surface : surfaces) {
2594 if (stream->isConsumerConfigurationDeferred(surface)) {
2595 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2596 "due to deferred consumer", stream->getId(), surface);
2597 return NULL;
2598 }
2599 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002600 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002601 }
2602
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002603 // Lazy completion of stream configuration (allocation/registration)
2604 // on first use
2605 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002606 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002607 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002608 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2609 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002610 return NULL;
2611 }
2612 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002613 // Check if stream prepare is blocking requests.
2614 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002615 CLOGE("Request references an output stream that's being prepared!");
2616 return NULL;
2617 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002618
2619 newRequest->mOutputStreams.push(stream);
2620 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002621 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002622 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002623
2624 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002625}
2626
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002627bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2628 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2629 Size size = mSupportedOpaqueInputSizes[i];
2630 if (size.width == width && size.height == height) {
2631 return true;
2632 }
2633 }
2634
2635 return false;
2636}
2637
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002638void Camera3Device::cancelStreamsConfigurationLocked() {
2639 int res = OK;
2640 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2641 res = mInputStream->cancelConfiguration();
2642 if (res != OK) {
2643 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2644 mInputStream->getId(), strerror(-res), res);
2645 }
2646 }
2647
2648 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002649 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002650 if (outputStream->isConfiguring()) {
2651 res = outputStream->cancelConfiguration();
2652 if (res != OK) {
2653 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2654 outputStream->getId(), strerror(-res), res);
2655 }
2656 }
2657 }
2658
2659 // Return state to that at start of call, so that future configures
2660 // properly clean things up
2661 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2662 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002663
2664 res = mPreparerThread->resume();
2665 if (res != OK) {
2666 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2667 }
2668}
2669
2670bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2671 ATRACE_CALL();
2672 bool ret = false;
2673
2674 Mutex::Autolock il(mInterfaceLock);
2675 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2676
2677 Mutex::Autolock l(mLock);
2678 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2679 if (rc == NO_ERROR) {
2680 mNeedConfig = true;
2681 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2682 if (rc == NO_ERROR) {
2683 ret = true;
2684 mPauseStateNotify = false;
2685 //Moving to active state while holding 'mLock' is important.
2686 //There could be pending calls to 'create-/deleteStream' which
2687 //will trigger another stream configuration while the already
2688 //present streams end up with outstanding buffers that will
2689 //not get drained.
2690 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002691 } else if (rc == DEAD_OBJECT) {
2692 // DEAD_OBJECT can be returned if either the consumer surface is
2693 // abandoned, or the HAL has died.
2694 // - If the HAL has died, configureStreamsLocked call will set
2695 // device to error state,
2696 // - If surface is abandoned, we should not set device to error
2697 // state.
2698 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002699 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002700 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002701 }
2702 } else {
2703 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2704 }
2705
2706 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002707}
2708
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002709status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002710 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002711 ATRACE_CALL();
2712 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002713
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002714 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002715 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002716 return INVALID_OPERATION;
2717 }
2718
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002719 if (operatingMode < 0) {
2720 CLOGE("Invalid operating mode: %d", operatingMode);
2721 return BAD_VALUE;
2722 }
2723
2724 bool isConstrainedHighSpeed =
2725 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2726 operatingMode;
2727
2728 if (mOperatingMode != operatingMode) {
2729 mNeedConfig = true;
2730 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2731 mOperatingMode = operatingMode;
2732 }
2733
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002734 if (!mNeedConfig) {
2735 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2736 return OK;
2737 }
2738
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002739 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2740 // adding a dummy stream instead.
2741 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2742 if (mOutputStreams.size() == 0) {
2743 addDummyStreamLocked();
2744 } else {
2745 tryRemoveDummyStreamLocked();
2746 }
2747
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002748 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002749 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002750
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002751 mPreparerThread->pause();
2752
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002753 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002754 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002755 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2756
2757 Vector<camera3_stream_t*> streams;
2758 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002759 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002760
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002761
2762 if (mInputStream != NULL) {
2763 camera3_stream_t *inputStream;
2764 inputStream = mInputStream->startConfiguration();
2765 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002766 CLOGE("Can't start input stream configuration");
2767 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002768 return INVALID_OPERATION;
2769 }
2770 streams.add(inputStream);
2771 }
2772
2773 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002774
2775 // Don't configure bidi streams twice, nor add them twice to the list
2776 if (mOutputStreams[i].get() ==
2777 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2778
2779 config.num_streams--;
2780 continue;
2781 }
2782
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002783 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002784 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002785 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002786 CLOGE("Can't start output stream configuration");
2787 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002788 return INVALID_OPERATION;
2789 }
2790 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002791
2792 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2793 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002794 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2795 // always occupy the initial entry.
2796 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002797 getJpegBufferSize(outputStream->width, outputStream->height));
2798 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002799 }
2800
2801 config.streams = streams.editArray();
2802
2803 // Do the HAL configuration; will potentially touch stream
2804 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002805
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002806 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002807 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002808 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002809
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002810 if (res == BAD_VALUE) {
2811 // HAL rejected this set of streams as unsupported, clean up config
2812 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002813 CLOGE("Set of requested inputs/outputs not supported by HAL");
2814 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002815 return BAD_VALUE;
2816 } else if (res != OK) {
2817 // Some other kind of error from configure_streams - this is not
2818 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002819 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2820 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002821 return res;
2822 }
2823
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002824 // Finish all stream configuration immediately.
2825 // TODO: Try to relax this later back to lazy completion, which should be
2826 // faster
2827
Igor Murashkin073f8572013-05-02 14:59:28 -07002828 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002829 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002830 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002831 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002832 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002833 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002834 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2835 return DEAD_OBJECT;
2836 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002837 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002838 }
2839 }
2840
2841 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002842 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002843 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002844 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002845 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002846 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002847 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002848 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002849 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2850 return DEAD_OBJECT;
2851 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002852 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002853 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002854 }
2855 }
2856
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002857 // Request thread needs to know to avoid using repeat-last-settings protocol
2858 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002859 if (notifyRequestThread) {
2860 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2861 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002862
Zhijun He90f7c372016-08-16 16:19:43 -07002863 char value[PROPERTY_VALUE_MAX];
2864 property_get("camera.fifo.disable", value, "0");
2865 int32_t disableFifo = atoi(value);
2866 if (disableFifo != 1) {
2867 // Boost priority of request thread to SCHED_FIFO.
2868 pid_t requestThreadTid = mRequestThread->getTid();
2869 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002870 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002871 if (res != OK) {
2872 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2873 strerror(-res), res);
2874 } else {
2875 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2876 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002877 }
2878
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002879 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002880 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2881 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2882 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2883 sessionParams.unlock(newSessionParams);
2884 mSessionParams.unlock(currentSessionParams);
2885 if (updateSessionParams) {
2886 mSessionParams = sessionParams;
2887 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002888
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002889 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002890
Ruben Brunk183f0562015-08-12 12:55:02 -07002891 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2892 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002893
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002894 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002895
Zhijun He0a210512014-07-24 13:45:15 -07002896 // tear down the deleted streams after configure streams.
2897 mDeletedStreams.clear();
2898
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002899 auto rc = mPreparerThread->resume();
2900 if (rc != OK) {
2901 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2902 return rc;
2903 }
2904
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002905 if (mDummyStreamId == NO_STREAM) {
2906 mRequestBufferSM.onStreamsConfigured();
2907 }
2908
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002909 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002910}
2911
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002912status_t Camera3Device::addDummyStreamLocked() {
2913 ATRACE_CALL();
2914 status_t res;
2915
2916 if (mDummyStreamId != NO_STREAM) {
2917 // Should never be adding a second dummy stream when one is already
2918 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002919 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2920 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002921 return INVALID_OPERATION;
2922 }
2923
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002924 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002925
2926 sp<Camera3OutputStreamInterface> dummyStream =
2927 new Camera3DummyStream(mNextStreamId);
2928
2929 res = mOutputStreams.add(mNextStreamId, dummyStream);
2930 if (res < 0) {
2931 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2932 return res;
2933 }
2934
2935 mDummyStreamId = mNextStreamId;
2936 mNextStreamId++;
2937
2938 return OK;
2939}
2940
2941status_t Camera3Device::tryRemoveDummyStreamLocked() {
2942 ATRACE_CALL();
2943 status_t res;
2944
2945 if (mDummyStreamId == NO_STREAM) return OK;
2946 if (mOutputStreams.size() == 1) return OK;
2947
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002948 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002949
2950 // Ok, have a dummy stream and there's at least one other output stream,
2951 // so remove the dummy
2952
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002953 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2954 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002955 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2956 return INVALID_OPERATION;
2957 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002958 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002959
2960 // Free up the stream endpoint so that it can be used by some other stream
2961 res = deletedStream->disconnect();
2962 if (res != OK) {
2963 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2964 // fall through since we want to still list the stream as deleted.
2965 }
2966 mDeletedStreams.add(deletedStream);
2967 mDummyStreamId = NO_STREAM;
2968
2969 return res;
2970}
2971
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002972void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002973 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002974 Mutex::Autolock l(mLock);
2975 va_list args;
2976 va_start(args, fmt);
2977
2978 setErrorStateLockedV(fmt, args);
2979
2980 va_end(args);
2981}
2982
2983void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002984 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002985 Mutex::Autolock l(mLock);
2986 setErrorStateLockedV(fmt, args);
2987}
2988
2989void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2990 va_list args;
2991 va_start(args, fmt);
2992
2993 setErrorStateLockedV(fmt, args);
2994
2995 va_end(args);
2996}
2997
2998void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002999 // Print out all error messages to log
3000 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003001 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003002
3003 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003004 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003005
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003006 mErrorCause = errorCause;
3007
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003008 if (mRequestThread != nullptr) {
3009 mRequestThread->setPaused(true);
3010 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003011 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003012
3013 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003014 sp<NotificationListener> listener = mListener.promote();
3015 if (listener != NULL) {
3016 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003017 CaptureResultExtras());
3018 }
3019
3020 // Save stack trace. View by dumping it later.
3021 CameraTraces::saveTrace();
3022 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003023}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003024
3025/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003026 * In-flight request management
3027 */
3028
Jianing Weicb0652e2014-03-12 18:29:36 -07003029status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003030 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003031 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003032 std::set<String8>& physicalCameraIds, bool isStillCapture,
3033 bool isZslCapture) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003034 ATRACE_CALL();
3035 Mutex::Autolock l(mInFlightLock);
3036
3037 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003038 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003039 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003040 if (res < 0) return res;
3041
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003042 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003043 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3044 // avoid a deadlock during reprocess requests.
3045 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003046 if (mStatusTracker != nullptr) {
3047 mStatusTracker->markComponentActive(mInFlightStatusId);
3048 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003049 }
3050
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003051 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003052 return OK;
3053}
3054
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003055void Camera3Device::returnOutputBuffers(
3056 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003057 nsecs_t timestamp, bool timestampIncreasing) {
3058
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003059 for (size_t i = 0; i < numBuffers; i++)
3060 {
3061 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003062 status_t res = stream->returnBuffer(outputBuffers[i], timestamp, timestampIncreasing);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003063 // Note: stream may be deallocated at this point, if this buffer was
3064 // the last reference to it.
3065 if (res != OK) {
3066 ALOGE("Can't return buffer to its stream: %s (%d)",
3067 strerror(-res), res);
3068 }
3069 }
3070}
3071
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003072void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003073 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003074 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003075 mInFlightMap.removeItemsAt(idx, 1);
3076
3077 // Indicate idle inFlightMap to the status tracker
3078 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003079 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003080 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3081 // avoid a deadlock during reprocess requests.
3082 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003083 if (mStatusTracker != nullptr) {
3084 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3085 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003086 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003087 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003088}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003089
3090void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3091
3092 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3093 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3094
3095 nsecs_t sensorTimestamp = request.sensorTimestamp;
3096 nsecs_t shutterTimestamp = request.shutterTimestamp;
3097
3098 // Check if it's okay to remove the request from InFlightMap:
3099 // In the case of a successful request:
3100 // all input and output buffers, all result metadata, shutter callback
3101 // arrived.
3102 // In the case of a unsuccessful request:
3103 // all input and output buffers arrived.
3104 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003105 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003106 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003107 if (request.stillCapture) {
3108 ATRACE_ASYNC_END("still capture", frameNumber);
3109 }
3110
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003111 ATRACE_ASYNC_END("frame capture", frameNumber);
3112
Shuzhen Wang403044a2017-02-26 23:29:04 -08003113 // Sanity check - if sensor timestamp matches shutter timestamp in the
3114 // case of request having callback.
3115 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003116 sensorTimestamp != shutterTimestamp) {
3117 SET_ERR("sensor timestamp (%" PRId64
3118 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3119 sensorTimestamp, frameNumber, shutterTimestamp);
3120 }
3121
3122 // for an unsuccessful request, it may have pending output buffers to
3123 // return.
3124 assert(request.requestStatus != OK ||
3125 request.pendingOutputBuffers.size() == 0);
3126 returnOutputBuffers(request.pendingOutputBuffers.array(),
3127 request.pendingOutputBuffers.size(), 0);
3128
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003129 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003130 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3131 }
3132
3133 // Sanity check - if we have too many in-flight frames, something has
3134 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003135 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003136 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003137 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3138 kInFlightWarnLimitHighSpeed) {
3139 CLOGE("In-flight list too large for high speed configuration: %zu",
3140 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003141 }
3142}
3143
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003144void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003145 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003146 { // First return buffers cached in mInFlightMap
3147 Mutex::Autolock l(mInFlightLock);
3148 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3149 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3150 returnOutputBuffers(request.pendingOutputBuffers.array(),
3151 request.pendingOutputBuffers.size(), 0);
3152 }
3153 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003154 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003155 }
3156
3157 // Then return all inflight buffers not returned by HAL
3158 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3159 mInterface->getInflightBufferKeys(&inflightKeys);
3160
3161 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3162 for (auto& pair : inflightKeys) {
3163 int32_t frameNumber = pair.first;
3164 int32_t streamId = pair.second;
3165 buffer_handle_t* buffer;
3166 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3167 if (res != OK) {
3168 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3169 __FUNCTION__, frameNumber, streamId);
3170 continue;
3171 }
3172
3173 camera3_stream_buffer_t streamBuffer;
3174 streamBuffer.buffer = buffer;
3175 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3176 streamBuffer.acquire_fence = -1;
3177 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003178
3179 // First check if the buffer belongs to deleted stream
3180 bool streamDeleted = false;
3181 for (auto& stream : mDeletedStreams) {
3182 if (streamId == stream->getId()) {
3183 streamDeleted = true;
3184 // Return buffer to deleted stream
3185 camera3_stream* halStream = stream->asHalStream();
3186 streamBuffer.stream = halStream;
3187 switch (halStream->stream_type) {
3188 case CAMERA3_STREAM_OUTPUT:
3189 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
3190 if (res != OK) {
3191 ALOGE("%s: Can't return output buffer for frame %d to"
3192 " stream %d: %s (%d)", __FUNCTION__,
3193 frameNumber, streamId, strerror(-res), res);
3194 }
3195 break;
3196 case CAMERA3_STREAM_INPUT:
3197 res = stream->returnInputBuffer(streamBuffer);
3198 if (res != OK) {
3199 ALOGE("%s: Can't return input buffer for frame %d to"
3200 " stream %d: %s (%d)", __FUNCTION__,
3201 frameNumber, streamId, strerror(-res), res);
3202 }
3203 break;
3204 default: // Bi-direcitonal stream is deprecated
3205 ALOGE("%s: stream %d has unknown stream type %d",
3206 __FUNCTION__, streamId, halStream->stream_type);
3207 break;
3208 }
3209 break;
3210 }
3211 }
3212 if (streamDeleted) {
3213 continue;
3214 }
3215
3216 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003217 if (streamId == inputStreamId) {
3218 streamBuffer.stream = mInputStream->asHalStream();
3219 res = mInputStream->returnInputBuffer(streamBuffer);
3220 if (res != OK) {
3221 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003222 " stream %d: %s (%d)", __FUNCTION__,
3223 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003224 }
3225 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003226 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3227 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003228 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3229 continue;
3230 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003231 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003232 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3233 }
3234 }
3235}
3236
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003237void Camera3Device::insertResultLocked(CaptureResult *result,
3238 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003239 if (result == nullptr) return;
3240
Emilian Peev71c73a22017-03-21 16:35:51 +00003241 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3242 result->mMetadata.getAndLock());
3243 set_camera_metadata_vendor_id(meta, mVendorTagId);
3244 result->mMetadata.unlock(meta);
3245
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003246 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3247 (int32_t*)&frameNumber, 1) != OK) {
3248 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3249 return;
3250 }
3251
3252 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3253 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3254 return;
3255 }
3256
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003257 // Valid result, insert into queue
3258 List<CaptureResult>::iterator queuedResult =
3259 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3260 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3261 ", burstId = %" PRId32, __FUNCTION__,
3262 queuedResult->mResultExtras.requestId,
3263 queuedResult->mResultExtras.frameNumber,
3264 queuedResult->mResultExtras.burstId);
3265
3266 mResultSignal.signal();
3267}
3268
3269
3270void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003271 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003272 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003273 Mutex::Autolock l(mOutputLock);
3274
3275 CaptureResult captureResult;
3276 captureResult.mResultExtras = resultExtras;
3277 captureResult.mMetadata = partialResult;
3278
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003279 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003280}
3281
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003282
3283void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3284 CaptureResultExtras &resultExtras,
3285 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003286 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003287 bool reprocess,
3288 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003289 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003290 if (pendingMetadata.isEmpty())
3291 return;
3292
3293 Mutex::Autolock l(mOutputLock);
3294
3295 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003296 if (reprocess) {
3297 if (frameNumber < mNextReprocessResultFrameNumber) {
3298 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003299 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003300 frameNumber, mNextReprocessResultFrameNumber);
3301 return;
3302 }
3303 mNextReprocessResultFrameNumber = frameNumber + 1;
3304 } else {
3305 if (frameNumber < mNextResultFrameNumber) {
3306 SET_ERR("Out-of-order capture result metadata submitted! "
3307 "(got frame number %d, expecting %d)",
3308 frameNumber, mNextResultFrameNumber);
3309 return;
3310 }
3311 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003312 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003313
3314 CaptureResult captureResult;
3315 captureResult.mResultExtras = resultExtras;
3316 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003317 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003318
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003319 // Append any previous partials to form a complete result
3320 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3321 captureResult.mMetadata.append(collectedPartialResult);
3322 }
3323
3324 captureResult.mMetadata.sort();
3325
3326 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003327 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3328 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003329 SET_ERR("No timestamp provided by HAL for frame %d!",
3330 frameNumber);
3331 return;
3332 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003333 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3334 camera_metadata_entry timestamp =
3335 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3336 if (timestamp.count == 0) {
3337 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3338 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3339 return;
3340 }
3341 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003342
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003343 // Fix up some result metadata to account for HAL-level distortion correction
3344 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3345 if (res != OK) {
3346 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3347 frameNumber, strerror(res), res);
3348 return;
3349 }
3350
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003351 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3352 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3353
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003354 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003355}
3356
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003357/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003358 * Camera HAL device callback methods
3359 */
3360
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003361void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003362 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003363
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003364 status_t res;
3365
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003366 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003367 if (result->result == NULL && result->num_output_buffers == 0 &&
3368 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003369 SET_ERR("No result data provided by HAL for frame %d",
3370 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003371 return;
3372 }
Zhijun He204e3292014-07-14 17:09:23 -07003373
Zhijun He204e3292014-07-14 17:09:23 -07003374 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003375 result->result != NULL &&
3376 result->partial_result != 1) {
3377 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3378 " if partial result is not supported",
3379 frameNumber, result->partial_result);
3380 return;
3381 }
3382
3383 bool isPartialResult = false;
3384 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003385 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003386
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003387 // Get shutter timestamp and resultExtras from list of in-flight requests,
3388 // where it was added by the shutter notification for this frame. If the
3389 // shutter timestamp isn't received yet, append the output buffers to the
3390 // in-flight request and they will be returned when the shutter timestamp
3391 // arrives. Update the in-flight status and remove the in-flight entry if
3392 // all result data and shutter timestamp have been received.
3393 nsecs_t shutterTimestamp = 0;
3394
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003395 {
3396 Mutex::Autolock l(mInFlightLock);
3397 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3398 if (idx == NAME_NOT_FOUND) {
3399 SET_ERR("Unknown frame number for capture result: %d",
3400 frameNumber);
3401 return;
3402 }
3403 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003404 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3405 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003406 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003407 __FUNCTION__, request.resultExtras.requestId,
3408 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003409 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003410 // Always update the partial count to the latest one if it's not 0
3411 // (buffers only). When framework aggregates adjacent partial results
3412 // into one, the latest partial count will be used.
3413 if (result->partial_result != 0)
3414 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003415
3416 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003417 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003418 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3419 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3420 " the range of [1, %d] when metadata is included in the result",
3421 frameNumber, result->partial_result, mNumPartialResults);
3422 return;
3423 }
3424 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003425 if (isPartialResult && result->num_physcam_metadata) {
3426 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3427 " physical camera result", frameNumber);
3428 return;
3429 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003430 if (isPartialResult) {
3431 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003432 }
3433
Shuzhen Wang4a472662017-02-26 23:29:04 -08003434 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003435 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003436 sendPartialCaptureResult(result->result, request.resultExtras,
3437 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003438 }
3439 }
3440
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003441 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003442 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003443
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003444 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003445 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003446 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3447 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3448 request.physicalCameraIds.size(), result->num_physcam_metadata);
3449 return;
3450 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003451 if (request.haveResultMetadata) {
3452 SET_ERR("Called multiple times with metadata for frame %d",
3453 frameNumber);
3454 return;
3455 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003456 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3457 String8 physicalId(result->physcam_ids[i]);
3458 std::set<String8>::iterator cameraIdIter =
3459 request.physicalCameraIds.find(physicalId);
3460 if (cameraIdIter != request.physicalCameraIds.end()) {
3461 request.physicalCameraIds.erase(cameraIdIter);
3462 } else {
3463 SET_ERR("Total result for frame %d has already returned for camera %s",
3464 frameNumber, physicalId.c_str());
3465 return;
3466 }
3467 }
Zhijun He204e3292014-07-14 17:09:23 -07003468 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003469 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003470 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003471 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003472 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003473 request.haveResultMetadata = true;
3474 }
3475
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003476 uint32_t numBuffersReturned = result->num_output_buffers;
3477 if (result->input_buffer != NULL) {
3478 if (hasInputBufferInRequest) {
3479 numBuffersReturned += 1;
3480 } else {
3481 ALOGW("%s: Input buffer should be NULL if there is no input"
3482 " buffer sent in the request",
3483 __FUNCTION__);
3484 }
3485 }
3486 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003487 if (request.numBuffersLeft < 0) {
3488 SET_ERR("Too many buffers returned for frame %d",
3489 frameNumber);
3490 return;
3491 }
3492
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003493 camera_metadata_ro_entry_t entry;
3494 res = find_camera_metadata_ro_entry(result->result,
3495 ANDROID_SENSOR_TIMESTAMP, &entry);
3496 if (res == OK && entry.count == 1) {
3497 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003498 }
3499
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003500 // If shutter event isn't received yet, append the output buffers to
3501 // the in-flight request. Otherwise, return the output buffers to
3502 // streams.
3503 if (shutterTimestamp == 0) {
3504 request.pendingOutputBuffers.appendArray(result->output_buffers,
3505 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003506 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003507 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003508 returnOutputBuffers(result->output_buffers,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003509 result->num_output_buffers, shutterTimestamp, timestampIncreasing);
Igor Murashkind2c90692013-04-02 12:32:32 -07003510 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003511
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003512 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003513 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3514 CameraMetadata physicalMetadata;
3515 physicalMetadata.append(result->physcam_metadata[i]);
3516 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3517 physicalMetadata});
3518 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003519 if (shutterTimestamp == 0) {
3520 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003521 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003522 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003523 CameraMetadata metadata;
3524 metadata = result->result;
3525 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003526 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003527 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003528 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003529 }
3530
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003531 removeInFlightRequestIfReadyLocked(idx);
3532 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003533
Zhijun Hef0d962a2014-06-30 10:24:11 -07003534 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003535 if (hasInputBufferInRequest) {
3536 Camera3Stream *stream =
3537 Camera3Stream::cast(result->input_buffer->stream);
3538 res = stream->returnInputBuffer(*(result->input_buffer));
3539 // Note: stream may be deallocated at this point, if this buffer was the
3540 // last reference to it.
3541 if (res != OK) {
3542 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3543 " its stream:%s (%d)", __FUNCTION__,
3544 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003545 }
3546 } else {
3547 ALOGW("%s: Input buffer should be NULL if there is no input"
3548 " buffer sent in the request, skipping input buffer return.",
3549 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003550 }
3551 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003552}
3553
3554void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003555 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003556 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003557 {
3558 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003559 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003560 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003561
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003562 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003563 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003564 return;
3565 }
3566
3567 switch (msg->type) {
3568 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003569 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003570 break;
3571 }
3572 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003573 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003574 break;
3575 }
3576 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003577 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003578 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003579 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003580}
3581
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003582void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003583 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003584 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003585 // Map camera HAL error codes to ICameraDeviceCallback error codes
3586 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003587 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003588 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003589 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003590 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003591 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003592 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003593 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003594 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003595 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003596 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003597 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003598 };
3599
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003600 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003601 ((msg.error_code >= 0) &&
3602 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3603 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003604 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003605
3606 int streamId = 0;
3607 if (msg.error_stream != NULL) {
3608 Camera3Stream *stream =
3609 Camera3Stream::cast(msg.error_stream);
3610 streamId = stream->getId();
3611 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003612 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3613 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003614 streamId, msg.error_code);
3615
3616 CaptureResultExtras resultExtras;
3617 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003618 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003619 // SET_ERR calls notifyError
3620 SET_ERR("Camera HAL reported serious device error");
3621 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003622 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3623 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3624 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003625 {
3626 Mutex::Autolock l(mInFlightLock);
3627 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3628 if (idx >= 0) {
3629 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3630 r.requestStatus = msg.error_code;
3631 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003632 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3633 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3634 errorCode) {
3635 r.skipResultMetadata = true;
3636 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003637 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3638 errorCode) {
3639 // In case of missing result check whether the buffers
3640 // returned. If they returned, then remove inflight
3641 // request.
3642 removeInFlightRequestIfReadyLocked(idx);
3643 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003644 } else {
3645 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003646 ALOGE("Camera %s: %s: cannot find in-flight request on "
3647 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003648 resultExtras.frameNumber);
3649 }
3650 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003651 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003652 if (listener != NULL) {
3653 listener->notifyError(errorCode, resultExtras);
3654 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003655 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003656 }
3657 break;
3658 default:
3659 // SET_ERR calls notifyError
3660 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3661 break;
3662 }
3663}
3664
3665void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003666 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003667 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003668 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003669
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003670 // Set timestamp for the request in the in-flight tracking
3671 // and get the request ID to send upstream
3672 {
3673 Mutex::Autolock l(mInFlightLock);
3674 idx = mInFlightMap.indexOfKey(msg.frame_number);
3675 if (idx >= 0) {
3676 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003677
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003678 // Verify ordering of shutter notifications
3679 {
3680 Mutex::Autolock l(mOutputLock);
3681 // TODO: need to track errors for tighter bounds on expected frame number.
3682 if (r.hasInputBuffer) {
3683 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3684 SET_ERR("Shutter notification out-of-order. Expected "
3685 "notification for frame %d, got frame %d",
3686 mNextReprocessShutterFrameNumber, msg.frame_number);
3687 return;
3688 }
3689 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3690 } else {
3691 if (msg.frame_number < mNextShutterFrameNumber) {
3692 SET_ERR("Shutter notification out-of-order. Expected "
3693 "notification for frame %d, got frame %d",
3694 mNextShutterFrameNumber, msg.frame_number);
3695 return;
3696 }
3697 mNextShutterFrameNumber = msg.frame_number + 1;
3698 }
3699 }
3700
Shuzhen Wang4a472662017-02-26 23:29:04 -08003701 r.shutterTimestamp = msg.timestamp;
3702 if (r.hasCallback) {
3703 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003704 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003705 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003706 // Call listener, if any
3707 if (listener != NULL) {
3708 listener->notifyShutter(r.resultExtras, msg.timestamp);
3709 }
3710 // send pending result and buffers
3711 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3712 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003713 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003714 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003715 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003716 returnOutputBuffers(r.pendingOutputBuffers.array(),
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003717 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003718 r.pendingOutputBuffers.clear();
3719
3720 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003721 }
3722 }
3723 if (idx < 0) {
3724 SET_ERR("Shutter notification for non-existent frame number %d",
3725 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003726 }
3727}
3728
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003729CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003730 ALOGV("%s", __FUNCTION__);
3731
Igor Murashkin1e479c02013-09-06 16:55:14 -07003732 CameraMetadata retVal;
3733
3734 if (mRequestThread != NULL) {
3735 retVal = mRequestThread->getLatestRequest();
3736 }
3737
Igor Murashkin1e479c02013-09-06 16:55:14 -07003738 return retVal;
3739}
3740
Jianing Weicb0652e2014-03-12 18:29:36 -07003741
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003742void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3743 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3744 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3745}
3746
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003747/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003748 * HalInterface inner class methods
3749 */
3750
Yifan Hongf79b5542017-04-11 14:44:25 -07003751Camera3Device::HalInterface::HalInterface(
3752 sp<ICameraDeviceSession> &session,
3753 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003754 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003755 mRequestMetadataQueue(queue) {
3756 // Check with hardware service manager if we can downcast these interfaces
3757 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003758 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3759 if (castResult_3_5.isOk()) {
3760 mHidlSession_3_5 = castResult_3_5;
3761 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003762 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3763 if (castResult_3_4.isOk()) {
3764 mHidlSession_3_4 = castResult_3_4;
3765 }
3766 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3767 if (castResult_3_3.isOk()) {
3768 mHidlSession_3_3 = castResult_3_3;
3769 }
3770}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003771
Emilian Peev31abd0a2017-05-11 18:37:46 +01003772Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003773
3774Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003775 mHidlSession(other.mHidlSession),
3776 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003777
3778bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003779 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003780}
3781
3782void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003783 mHidlSession_3_4.clear();
3784 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003785 mHidlSession.clear();
3786}
3787
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003788bool Camera3Device::HalInterface::supportBatchRequest() {
3789 return mHidlSession != nullptr;
3790}
3791
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003792status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3793 camera3_request_template_t templateId,
3794 /*out*/ camera_metadata_t **requestTemplate) {
3795 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3796 if (!valid()) return INVALID_OPERATION;
3797 status_t res = OK;
3798
Emilian Peev31abd0a2017-05-11 18:37:46 +01003799 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003800
3801 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003802 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003803 status = s;
3804 if (status == common::V1_0::Status::OK) {
3805 const camera_metadata *r =
3806 reinterpret_cast<const camera_metadata_t*>(request.data());
3807 size_t expectedSize = request.size();
3808 int ret = validate_camera_metadata_structure(r, &expectedSize);
3809 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3810 *requestTemplate = clone_camera_metadata(r);
3811 if (*requestTemplate == nullptr) {
3812 ALOGE("%s: Unable to clone camera metadata received from HAL",
3813 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003814 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003815 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003816 } else {
3817 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3818 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003819 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003820 }
3821 };
3822 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003823 RequestTemplate id;
3824 switch (templateId) {
3825 case CAMERA3_TEMPLATE_PREVIEW:
3826 id = RequestTemplate::PREVIEW;
3827 break;
3828 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3829 id = RequestTemplate::STILL_CAPTURE;
3830 break;
3831 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3832 id = RequestTemplate::VIDEO_RECORD;
3833 break;
3834 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3835 id = RequestTemplate::VIDEO_SNAPSHOT;
3836 break;
3837 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3838 id = RequestTemplate::ZERO_SHUTTER_LAG;
3839 break;
3840 case CAMERA3_TEMPLATE_MANUAL:
3841 id = RequestTemplate::MANUAL;
3842 break;
3843 default:
3844 // Unknown template ID, or this HAL is too old to support it
3845 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003846 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003847 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003848
Emilian Peev31abd0a2017-05-11 18:37:46 +01003849 if (!err.isOk()) {
3850 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3851 res = DEAD_OBJECT;
3852 } else {
3853 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003854 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003855
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003856 return res;
3857}
3858
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003859status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003860 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003861 ATRACE_NAME("CameraHal::configureStreams");
3862 if (!valid()) return INVALID_OPERATION;
3863 status_t res = OK;
3864
Emilian Peev31abd0a2017-05-11 18:37:46 +01003865 // Convert stream config to HIDL
3866 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003867 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3868 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3869 requestedConfiguration3_2.streams.resize(config->num_streams);
3870 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003871 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003872 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3873 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003874 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003875
Emilian Peev31abd0a2017-05-11 18:37:46 +01003876 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3877 cam3stream->setBufferFreedListener(this);
3878 int streamId = cam3stream->getId();
3879 StreamType streamType;
3880 switch (src->stream_type) {
3881 case CAMERA3_STREAM_OUTPUT:
3882 streamType = StreamType::OUTPUT;
3883 break;
3884 case CAMERA3_STREAM_INPUT:
3885 streamType = StreamType::INPUT;
3886 break;
3887 default:
3888 ALOGE("%s: Stream %d: Unsupported stream type %d",
3889 __FUNCTION__, streamId, config->streams[i]->stream_type);
3890 return BAD_VALUE;
3891 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003892 dst3_2.id = streamId;
3893 dst3_2.streamType = streamType;
3894 dst3_2.width = src->width;
3895 dst3_2.height = src->height;
3896 dst3_2.format = mapToPixelFormat(src->format);
3897 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3898 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3899 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3900 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003901 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003902 if (src->physical_camera_id != nullptr) {
3903 dst3_4.physicalCameraId = src->physical_camera_id;
3904 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003905
3906 activeStreams.insert(streamId);
3907 // Create Buffer ID map if necessary
3908 if (mBufferIdMaps.count(streamId) == 0) {
3909 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3910 }
3911 }
3912 // remove BufferIdMap for deleted streams
3913 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3914 int streamId = it->first;
3915 bool active = activeStreams.count(streamId) > 0;
3916 if (!active) {
3917 it = mBufferIdMaps.erase(it);
3918 } else {
3919 ++it;
3920 }
3921 }
3922
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003923 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003924 res = mapToStreamConfigurationMode(
3925 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003926 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003927 if (res != OK) {
3928 return res;
3929 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003930 requestedConfiguration3_2.operationMode = operationMode;
3931 requestedConfiguration3_4.operationMode = operationMode;
3932 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003933 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3934 get_camera_metadata_size(sessionParams));
3935
Emilian Peev31abd0a2017-05-11 18:37:46 +01003936 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003937 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003938 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003939 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003940
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003941 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003942 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3943 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003944 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003945 };
3946
3947 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3948 (hardware::Return<void>& err) -> status_t {
3949 if (!err.isOk()) {
3950 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3951 return DEAD_OBJECT;
3952 }
3953 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3954 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3955 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3956 }
3957 return OK;
3958 };
3959
3960 // See if we have v3.4 or v3.3 HAL
3961 if (mHidlSession_3_5 != nullptr) {
3962 ALOGV("%s: v3.5 device found", __FUNCTION__);
3963 device::V3_5::StreamConfiguration requestedConfiguration3_5;
3964 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
3965 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
3966 auto err = mHidlSession_3_5->configureStreams_3_5(
3967 requestedConfiguration3_5, configStream34Cb);
3968 res = postprocConfigStream34(err);
3969 if (res != OK) {
3970 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003971 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003972 } else if (mHidlSession_3_4 != nullptr) {
3973 // We do; use v3.4 for the call
3974 ALOGV("%s: v3.4 device found", __FUNCTION__);
3975 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
3976 auto err = mHidlSession_3_4->configureStreams_3_4(
3977 requestedConfiguration3_4, configStream34Cb);
3978 res = postprocConfigStream34(err);
3979 if (res != OK) {
3980 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003981 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003982 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003983 // We do; use v3.3 for the call
3984 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003985 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003986 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003987 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003988 finalConfiguration = halConfiguration;
3989 status = s;
3990 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003991 if (!err.isOk()) {
3992 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3993 return DEAD_OBJECT;
3994 }
3995 } else {
3996 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3997 ALOGV("%s: v3.2 device found", __FUNCTION__);
3998 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003999 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004000 [&status, &finalConfiguration_3_2]
4001 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4002 finalConfiguration_3_2 = halConfiguration;
4003 status = s;
4004 });
4005 if (!err.isOk()) {
4006 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4007 return DEAD_OBJECT;
4008 }
4009 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4010 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4011 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4012 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004013 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004014 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004015 }
4016
4017 if (status != common::V1_0::Status::OK ) {
4018 return CameraProviderManager::mapToStatusT(status);
4019 }
4020
4021 // And convert output stream configuration from HIDL
4022
4023 for (size_t i = 0; i < config->num_streams; i++) {
4024 camera3_stream_t *dst = config->streams[i];
4025 int streamId = Camera3Stream::cast(dst)->getId();
4026
4027 // Start scan at i, with the assumption that the stream order matches
4028 size_t realIdx = i;
4029 bool found = false;
4030 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004031 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004032 found = true;
4033 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004034 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004035 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4036 }
4037 if (!found) {
4038 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4039 __FUNCTION__, streamId);
4040 return INVALID_OPERATION;
4041 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004042 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004043
Emilian Peev710c1422017-08-30 11:19:38 +01004044 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4045 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004046 dstStream->setDataSpaceOverride(false);
4047 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4048 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4049
Emilian Peev31abd0a2017-05-11 18:37:46 +01004050 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4051 if (dst->format != overrideFormat) {
4052 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4053 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004054 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004055 if (dst->data_space != overrideDataSpace) {
4056 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4057 streamId, dst->format);
4058 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004059 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004060 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004061 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4062
Emilian Peev31abd0a2017-05-11 18:37:46 +01004063 // Override allowed with IMPLEMENTATION_DEFINED
4064 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004065 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004066 }
4067
Emilian Peev31abd0a2017-05-11 18:37:46 +01004068 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004069 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004070 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004071 __FUNCTION__, streamId);
4072 return INVALID_OPERATION;
4073 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004074 dstStream->setUsage(
4075 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004076 } else {
4077 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004078 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004079 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4080 __FUNCTION__, streamId);
4081 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004082 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004083 dstStream->setUsage(
4084 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004085 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004086 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004087 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004088
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004089 return res;
4090}
4091
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004092void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
4093 /*out*/device::V3_2::CaptureRequest* captureRequest,
4094 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004095 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004096 if (captureRequest == nullptr || handlesCreated == nullptr) {
4097 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4098 __FUNCTION__, captureRequest, handlesCreated);
4099 return;
4100 }
4101
4102 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004103
4104 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004105
4106 {
4107 std::lock_guard<std::mutex> lock(mInflightLock);
4108 if (request->input_buffer != nullptr) {
4109 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4110 buffer_handle_t buf = *(request->input_buffer->buffer);
4111 auto pair = getBufferId(buf, streamId);
4112 bool isNewBuffer = pair.first;
4113 uint64_t bufferId = pair.second;
4114 captureRequest->inputBuffer.streamId = streamId;
4115 captureRequest->inputBuffer.bufferId = bufferId;
4116 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4117 captureRequest->inputBuffer.status = BufferStatus::OK;
4118 native_handle_t *acquireFence = nullptr;
4119 if (request->input_buffer->acquire_fence != -1) {
4120 acquireFence = native_handle_create(1,0);
4121 acquireFence->data[0] = request->input_buffer->acquire_fence;
4122 handlesCreated->push_back(acquireFence);
4123 }
4124 captureRequest->inputBuffer.acquireFence = acquireFence;
4125 captureRequest->inputBuffer.releaseFence = nullptr;
4126
4127 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4128 request->input_buffer->buffer,
4129 request->input_buffer->acquire_fence);
4130 } else {
4131 captureRequest->inputBuffer.streamId = -1;
4132 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4133 }
4134
4135 captureRequest->outputBuffers.resize(request->num_output_buffers);
4136 for (size_t i = 0; i < request->num_output_buffers; i++) {
4137 const camera3_stream_buffer_t *src = request->output_buffers + i;
4138 StreamBuffer &dst = captureRequest->outputBuffers[i];
4139 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
4140 buffer_handle_t buf = *(src->buffer);
4141 auto pair = getBufferId(buf, streamId);
4142 bool isNewBuffer = pair.first;
4143 dst.streamId = streamId;
4144 dst.bufferId = pair.second;
4145 dst.buffer = isNewBuffer ? buf : nullptr;
4146 dst.status = BufferStatus::OK;
4147 native_handle_t *acquireFence = nullptr;
4148 if (src->acquire_fence != -1) {
4149 acquireFence = native_handle_create(1,0);
4150 acquireFence->data[0] = src->acquire_fence;
4151 handlesCreated->push_back(acquireFence);
4152 }
4153 dst.acquireFence = acquireFence;
4154 dst.releaseFence = nullptr;
4155
4156 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4157 src->buffer, src->acquire_fence);
4158 }
4159 }
4160}
4161
4162status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4163 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4164 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4165 if (!valid()) return INVALID_OPERATION;
4166
Emilian Peevaebbe412018-01-15 13:53:24 +00004167 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4168 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4169 if (castResult_3_4.isOk()) {
4170 hidlSession_3_4 = castResult_3_4;
4171 }
4172
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004173 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004174 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004175 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004176 if (hidlSession_3_4 != nullptr) {
4177 captureRequests_3_4.resize(batchSize);
4178 } else {
4179 captureRequests.resize(batchSize);
4180 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004181 std::vector<native_handle_t*> handlesCreated;
4182
4183 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004184 if (hidlSession_3_4 != nullptr) {
4185 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
4186 /*out*/&handlesCreated);
4187 } else {
4188 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
4189 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004190 }
4191
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004192 std::vector<device::V3_2::BufferCache> cachesToRemove;
4193 {
4194 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4195 for (auto& pair : mFreedBuffers) {
4196 // The stream might have been removed since onBufferFreed
4197 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4198 cachesToRemove.push_back({pair.first, pair.second});
4199 }
4200 }
4201 mFreedBuffers.clear();
4202 }
4203
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004204 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4205 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004206
4207 // Write metadata to FMQ.
4208 for (size_t i = 0; i < batchSize; i++) {
4209 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004210 device::V3_2::CaptureRequest* captureRequest;
4211 if (hidlSession_3_4 != nullptr) {
4212 captureRequest = &captureRequests_3_4[i].v3_2;
4213 } else {
4214 captureRequest = &captureRequests[i];
4215 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004216
4217 if (request->settings != nullptr) {
4218 size_t settingsSize = get_camera_metadata_size(request->settings);
4219 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4220 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4221 captureRequest->settings.resize(0);
4222 captureRequest->fmqSettingsSize = settingsSize;
4223 } else {
4224 if (mRequestMetadataQueue != nullptr) {
4225 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4226 }
4227 captureRequest->settings.setToExternal(
4228 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4229 get_camera_metadata_size(request->settings));
4230 captureRequest->fmqSettingsSize = 0u;
4231 }
4232 } else {
4233 // A null request settings maps to a size-0 CameraMetadata
4234 captureRequest->settings.resize(0);
4235 captureRequest->fmqSettingsSize = 0u;
4236 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004237
4238 if (hidlSession_3_4 != nullptr) {
4239 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4240 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004241 if (request->physcam_settings != nullptr) {
4242 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4243 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4244 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4245 settingsSize)) {
4246 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4247 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4248 settingsSize;
4249 } else {
4250 if (mRequestMetadataQueue != nullptr) {
4251 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4252 }
4253 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4254 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4255 request->physcam_settings[j])),
4256 get_camera_metadata_size(request->physcam_settings[j]));
4257 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004258 }
Emilian Peev00420d22018-02-05 21:33:13 +00004259 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004260 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004261 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004262 }
4263 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4264 request->physcam_id[j];
4265 }
4266 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004267 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004268
4269 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004270 auto resultCallback =
4271 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4272 status = s;
4273 *numRequestProcessed = n;
4274 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004275 if (hidlSession_3_4 != nullptr) {
4276 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004277 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004278 } else {
4279 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004280 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004281 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004282 if (!err.isOk()) {
4283 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4284 return DEAD_OBJECT;
4285 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004286 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4287 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4288 __FUNCTION__, *numRequestProcessed, batchSize);
4289 status = common::V1_0::Status::INTERNAL_ERROR;
4290 }
4291
4292 for (auto& handle : handlesCreated) {
4293 native_handle_delete(handle);
4294 }
4295 return CameraProviderManager::mapToStatusT(status);
4296}
4297
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004298status_t Camera3Device::HalInterface::processCaptureRequest(
4299 camera3_capture_request_t *request) {
4300 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004301 if (!valid()) return INVALID_OPERATION;
4302 status_t res = OK;
4303
Emilian Peev31abd0a2017-05-11 18:37:46 +01004304 uint32_t numRequestProcessed = 0;
4305 std::vector<camera3_capture_request_t*> requests(1);
4306 requests[0] = request;
4307 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4308
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004309 return res;
4310}
4311
4312status_t Camera3Device::HalInterface::flush() {
4313 ATRACE_NAME("CameraHal::flush");
4314 if (!valid()) return INVALID_OPERATION;
4315 status_t res = OK;
4316
Emilian Peev31abd0a2017-05-11 18:37:46 +01004317 auto err = mHidlSession->flush();
4318 if (!err.isOk()) {
4319 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4320 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004321 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004322 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004323 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004324
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004325 return res;
4326}
4327
Emilian Peev31abd0a2017-05-11 18:37:46 +01004328status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004329 ATRACE_NAME("CameraHal::dump");
4330 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004331
Emilian Peev31abd0a2017-05-11 18:37:46 +01004332 // Handled by CameraProviderManager::dump
4333
4334 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004335}
4336
4337status_t Camera3Device::HalInterface::close() {
4338 ATRACE_NAME("CameraHal::close()");
4339 if (!valid()) return INVALID_OPERATION;
4340 status_t res = OK;
4341
Emilian Peev31abd0a2017-05-11 18:37:46 +01004342 auto err = mHidlSession->close();
4343 // Interface will be dead shortly anyway, so don't log errors
4344 if (!err.isOk()) {
4345 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004346 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004347
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004348 return res;
4349}
4350
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004351void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4352 ATRACE_NAME("CameraHal::signalPipelineDrain");
4353 if (!valid() || mHidlSession_3_5 == nullptr) {
4354 ALOGE("%s called on invalid camera!", __FUNCTION__);
4355 return;
4356 }
4357
4358 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter);
4359 if (!err.isOk()) {
4360 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4361 return;
4362 }
4363}
4364
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004365void Camera3Device::HalInterface::getInflightBufferKeys(
4366 std::vector<std::pair<int32_t, int32_t>>* out) {
4367 std::lock_guard<std::mutex> lock(mInflightLock);
4368 out->clear();
4369 out->reserve(mInflightBufferMap.size());
4370 for (auto& pair : mInflightBufferMap) {
4371 uint64_t key = pair.first;
4372 int32_t streamId = key & 0xFFFFFFFF;
4373 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4374 out->push_back(std::make_pair(frameNumber, streamId));
4375 }
4376 return;
4377}
4378
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004379status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004380 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004381 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004382 auto pair = std::make_pair(buffer, acquireFence);
4383 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004384 return OK;
4385}
4386
4387status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004388 int32_t frameNumber, int32_t streamId,
4389 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004390 std::lock_guard<std::mutex> lock(mInflightLock);
4391
4392 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4393 auto it = mInflightBufferMap.find(key);
4394 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004395 auto pair = it->second;
4396 *buffer = pair.first;
4397 int acquireFence = pair.second;
4398 if (acquireFence > 0) {
4399 ::close(acquireFence);
4400 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004401 mInflightBufferMap.erase(it);
4402 return OK;
4403}
4404
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004405status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4406 uint64_t bufferId, buffer_handle_t* buf) {
4407 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4408 auto pair = mRequestedBuffers.insert({bufferId, buf});
4409 if (!pair.second) {
4410 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4411 __FUNCTION__, bufferId);
4412 return BAD_VALUE;
4413 }
4414 return OK;
4415}
4416
4417// Find and pop a buffer_handle_t based on bufferId
4418status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4419 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4420 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4421 auto it = mRequestedBuffers.find(bufferId);
4422 if (it == mRequestedBuffers.end()) {
4423 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4424 __FUNCTION__, bufferId);
4425 return BAD_VALUE;
4426 }
4427 *buffer = it->second;
4428 mRequestedBuffers.erase(it);
4429 return OK;
4430}
4431
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004432std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4433 const buffer_handle_t& buf, int streamId) {
4434 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4435
4436 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4437 auto it = bIdMap.find(buf);
4438 if (it == bIdMap.end()) {
4439 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004440 ALOGV("stream %d now have %zu buffer caches, buf %p",
4441 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004442 return std::make_pair(true, mNextBufferId - 1);
4443 } else {
4444 return std::make_pair(false, it->second);
4445 }
4446}
4447
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004448void Camera3Device::HalInterface::onBufferFreed(
4449 int streamId, const native_handle_t* handle) {
4450 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4451 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4452 auto mapIt = mBufferIdMaps.find(streamId);
4453 if (mapIt == mBufferIdMaps.end()) {
4454 // streamId might be from a deleted stream here
4455 ALOGI("%s: stream %d has been removed",
4456 __FUNCTION__, streamId);
4457 return;
4458 }
4459 BufferIdMap& bIdMap = mapIt->second;
4460 auto it = bIdMap.find(handle);
4461 if (it == bIdMap.end()) {
4462 ALOGW("%s: cannot find buffer %p in stream %d",
4463 __FUNCTION__, handle, streamId);
4464 return;
4465 } else {
4466 bufferId = it->second;
4467 bIdMap.erase(it);
4468 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4469 __FUNCTION__, streamId, bIdMap.size(), handle);
4470 }
4471 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4472}
4473
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004474/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004475 * RequestThread inner class methods
4476 */
4477
4478Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004479 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004480 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4481 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004482 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004483 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004484 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004485 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004486 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004487 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004488 mReconfigured(false),
4489 mDoPause(false),
4490 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004491 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004492 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004493 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004494 mCurrentAfTriggerId(0),
4495 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004496 mRepeatingLastFrameNumber(
4497 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004498 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004499 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004500 mRequestLatency(kRequestLatencyBinSize),
4501 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004502 mLatestSessionParams(sessionParamKeys.size()),
4503 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004504 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004505}
4506
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004507Camera3Device::RequestThread::~RequestThread() {}
4508
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004509void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004510 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004511 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004512 Mutex::Autolock l(mRequestLock);
4513 mListener = listener;
4514}
4515
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004516void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4517 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004518 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004519 Mutex::Autolock l(mRequestLock);
4520 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004521 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004522 // Prepare video stream for high speed recording.
4523 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004524 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004525}
4526
Jianing Wei90e59c92014-03-12 18:29:36 -07004527status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004528 List<sp<CaptureRequest> > &requests,
4529 /*out*/
4530 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004531 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004532 Mutex::Autolock l(mRequestLock);
4533 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4534 ++it) {
4535 mRequestQueue.push_back(*it);
4536 }
4537
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004538 if (lastFrameNumber != NULL) {
4539 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4540 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4541 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4542 *lastFrameNumber);
4543 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004544
Jianing Wei90e59c92014-03-12 18:29:36 -07004545 unpauseForNewRequests();
4546
4547 return OK;
4548}
4549
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004550
4551status_t Camera3Device::RequestThread::queueTrigger(
4552 RequestTrigger trigger[],
4553 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004554 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004555 Mutex::Autolock l(mTriggerMutex);
4556 status_t ret;
4557
4558 for (size_t i = 0; i < count; ++i) {
4559 ret = queueTriggerLocked(trigger[i]);
4560
4561 if (ret != OK) {
4562 return ret;
4563 }
4564 }
4565
4566 return OK;
4567}
4568
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004569const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4570 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004571 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004572 if (d != nullptr) return d->mId;
4573 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004574}
4575
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004576status_t Camera3Device::RequestThread::queueTriggerLocked(
4577 RequestTrigger trigger) {
4578
4579 uint32_t tag = trigger.metadataTag;
4580 ssize_t index = mTriggerMap.indexOfKey(tag);
4581
4582 switch (trigger.getTagType()) {
4583 case TYPE_BYTE:
4584 // fall-through
4585 case TYPE_INT32:
4586 break;
4587 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004588 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4589 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004590 return INVALID_OPERATION;
4591 }
4592
4593 /**
4594 * Collect only the latest trigger, since we only have 1 field
4595 * in the request settings per trigger tag, and can't send more than 1
4596 * trigger per request.
4597 */
4598 if (index != NAME_NOT_FOUND) {
4599 mTriggerMap.editValueAt(index) = trigger;
4600 } else {
4601 mTriggerMap.add(tag, trigger);
4602 }
4603
4604 return OK;
4605}
4606
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004607status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004608 const RequestList &requests,
4609 /*out*/
4610 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004611 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004612 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004613 if (lastFrameNumber != NULL) {
4614 *lastFrameNumber = mRepeatingLastFrameNumber;
4615 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004616 mRepeatingRequests.clear();
4617 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4618 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004619
4620 unpauseForNewRequests();
4621
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004622 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004623 return OK;
4624}
4625
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004626bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004627 if (mRepeatingRequests.empty()) {
4628 return false;
4629 }
4630 int32_t requestId = requestIn->mResultExtras.requestId;
4631 const RequestList &repeatRequests = mRepeatingRequests;
4632 // All repeating requests are guaranteed to have same id so only check first quest
4633 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4634 return (firstRequest->mResultExtras.requestId == requestId);
4635}
4636
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004637status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004638 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004639 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004640 return clearRepeatingRequestsLocked(lastFrameNumber);
4641
4642}
4643
4644status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004645 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004646 if (lastFrameNumber != NULL) {
4647 *lastFrameNumber = mRepeatingLastFrameNumber;
4648 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004649 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004650 return OK;
4651}
4652
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004653status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004654 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004655 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004656 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004657 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004658
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004659 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004660
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004661 // Send errors for all requests pending in the request queue, including
4662 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004663 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004664 if (listener != NULL) {
4665 for (RequestList::iterator it = mRequestQueue.begin();
4666 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004667 // Abort the input buffers for reprocess requests.
4668 if ((*it)->mInputStream != NULL) {
4669 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004670 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4671 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004672 if (res != OK) {
4673 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4674 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4675 } else {
4676 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4677 if (res != OK) {
4678 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4679 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4680 }
4681 }
4682 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004683 // Set the frame number this request would have had, if it
4684 // had been submitted; this frame number will not be reused.
4685 // The requestId and burstId fields were set when the request was
4686 // submitted originally (in convertMetadataListToRequestListLocked)
4687 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004688 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004689 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004690 }
4691 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004692 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004693
4694 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004695 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004696 if (lastFrameNumber != NULL) {
4697 *lastFrameNumber = mRepeatingLastFrameNumber;
4698 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004699 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004700 return OK;
4701}
4702
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004703status_t Camera3Device::RequestThread::flush() {
4704 ATRACE_CALL();
4705 Mutex::Autolock l(mFlushLock);
4706
Emilian Peev08dd2452017-04-06 16:55:14 +01004707 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004708}
4709
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004710void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004711 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004712 Mutex::Autolock l(mPauseLock);
4713 mDoPause = paused;
4714 mDoPauseSignal.signal();
4715}
4716
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004717status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4718 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004719 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004720 Mutex::Autolock l(mLatestRequestMutex);
4721 status_t res;
4722 while (mLatestRequestId != requestId) {
4723 nsecs_t startTime = systemTime();
4724
4725 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4726 if (res != OK) return res;
4727
4728 timeout -= (systemTime() - startTime);
4729 }
4730
4731 return OK;
4732}
4733
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004734void Camera3Device::RequestThread::requestExit() {
4735 // Call parent to set up shutdown
4736 Thread::requestExit();
4737 // The exit from any possible waits
4738 mDoPauseSignal.signal();
4739 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004740
4741 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4742 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004743}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004744
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004745void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004746 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004747 bool surfaceAbandoned = false;
4748 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004749 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004750 {
4751 Mutex::Autolock l(mRequestLock);
4752 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4753 // repeating requests.
4754 for (const auto& request : mRepeatingRequests) {
4755 for (const auto& s : request->mOutputStreams) {
4756 if (s->isAbandoned()) {
4757 surfaceAbandoned = true;
4758 clearRepeatingRequestsLocked(&lastFrameNumber);
4759 break;
4760 }
4761 }
4762 if (surfaceAbandoned) {
4763 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004764 }
4765 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004766 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004767 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004768
4769 if (listener != NULL && surfaceAbandoned) {
4770 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004771 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004772}
4773
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004774bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004775 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004776 status_t res;
4777 size_t batchSize = mNextRequests.size();
4778 std::vector<camera3_capture_request_t*> requests(batchSize);
4779 uint32_t numRequestProcessed = 0;
4780 for (size_t i = 0; i < batchSize; i++) {
4781 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004782 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004783 }
4784
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004785 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4786
4787 bool triggerRemoveFailed = false;
4788 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4789 for (size_t i = 0; i < numRequestProcessed; i++) {
4790 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4791 nextRequest.submitted = true;
4792
4793
4794 // Update the latest request sent to HAL
4795 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4796 Mutex::Autolock al(mLatestRequestMutex);
4797
4798 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4799 mLatestRequest.acquire(cloned);
4800
4801 sp<Camera3Device> parent = mParent.promote();
4802 if (parent != NULL) {
4803 parent->monitorMetadata(TagMonitor::REQUEST,
4804 nextRequest.halRequest.frame_number,
4805 0, mLatestRequest);
4806 }
4807 }
4808
4809 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004810 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4811 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004812 }
4813
Emilian Peevaebbe412018-01-15 13:53:24 +00004814 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4815
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004816 if (!triggerRemoveFailed) {
4817 // Remove any previously queued triggers (after unlock)
4818 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4819 if (removeTriggerRes != OK) {
4820 triggerRemoveFailed = true;
4821 triggerFailedRequest = nextRequest;
4822 }
4823 }
4824 }
4825
4826 if (triggerRemoveFailed) {
4827 SET_ERR("RequestThread: Unable to remove triggers "
4828 "(capture request %d, HAL device: %s (%d)",
4829 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4830 cleanUpFailedRequests(/*sendRequestError*/ false);
4831 return false;
4832 }
4833
4834 if (res != OK) {
4835 // Should only get a failure here for malformed requests or device-level
4836 // errors, so consider all errors fatal. Bad metadata failures should
4837 // come through notify.
4838 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4839 mNextRequests[numRequestProcessed].halRequest.frame_number,
4840 strerror(-res), res);
4841 cleanUpFailedRequests(/*sendRequestError*/ false);
4842 return false;
4843 }
4844 return true;
4845}
4846
4847bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4848 status_t res;
4849
4850 for (auto& nextRequest : mNextRequests) {
4851 // Submit request and block until ready for next one
4852 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4853 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4854
4855 if (res != OK) {
4856 // Should only get a failure here for malformed requests or device-level
4857 // errors, so consider all errors fatal. Bad metadata failures should
4858 // come through notify.
4859 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4860 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4861 res);
4862 cleanUpFailedRequests(/*sendRequestError*/ false);
4863 return false;
4864 }
4865
4866 // Mark that the request has be submitted successfully.
4867 nextRequest.submitted = true;
4868
4869 // Update the latest request sent to HAL
4870 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4871 Mutex::Autolock al(mLatestRequestMutex);
4872
4873 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4874 mLatestRequest.acquire(cloned);
4875
4876 sp<Camera3Device> parent = mParent.promote();
4877 if (parent != NULL) {
4878 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4879 0, mLatestRequest);
4880 }
4881 }
4882
4883 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004884 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4885 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004886 }
4887
Emilian Peevaebbe412018-01-15 13:53:24 +00004888 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4889
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004890 // Remove any previously queued triggers (after unlock)
4891 res = removeTriggers(mPrevRequest);
4892 if (res != OK) {
4893 SET_ERR("RequestThread: Unable to remove triggers "
4894 "(capture request %d, HAL device: %s (%d)",
4895 nextRequest.halRequest.frame_number, strerror(-res), res);
4896 cleanUpFailedRequests(/*sendRequestError*/ false);
4897 return false;
4898 }
4899 }
4900 return true;
4901}
4902
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004903nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4904 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4905 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4906 find_camera_metadata_ro_entry(request,
4907 ANDROID_CONTROL_AE_MODE,
4908 &e);
4909 if (e.count == 0) return maxExpectedDuration;
4910
4911 switch (e.data.u8[0]) {
4912 case ANDROID_CONTROL_AE_MODE_OFF:
4913 find_camera_metadata_ro_entry(request,
4914 ANDROID_SENSOR_EXPOSURE_TIME,
4915 &e);
4916 if (e.count > 0) {
4917 maxExpectedDuration = e.data.i64[0];
4918 }
4919 find_camera_metadata_ro_entry(request,
4920 ANDROID_SENSOR_FRAME_DURATION,
4921 &e);
4922 if (e.count > 0) {
4923 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4924 }
4925 break;
4926 default:
4927 find_camera_metadata_ro_entry(request,
4928 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4929 &e);
4930 if (e.count > 1) {
4931 maxExpectedDuration = 1e9 / e.data.u8[0];
4932 }
4933 break;
4934 }
4935
4936 return maxExpectedDuration;
4937}
4938
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004939bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4940 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4941 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4942 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4943 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4944 return true;
4945 }
4946
4947 return false;
4948}
4949
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004950bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4951 ATRACE_CALL();
4952 bool updatesDetected = false;
4953
4954 for (auto tag : mSessionParamKeys) {
4955 camera_metadata_ro_entry entry = settings.find(tag);
4956 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4957
4958 if (entry.count > 0) {
4959 bool isDifferent = false;
4960 if (lastEntry.count > 0) {
4961 // Have a last value, compare to see if changed
4962 if (lastEntry.type == entry.type &&
4963 lastEntry.count == entry.count) {
4964 // Same type and count, compare values
4965 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4966 size_t entryBytes = bytesPerValue * lastEntry.count;
4967 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4968 if (cmp != 0) {
4969 isDifferent = true;
4970 }
4971 } else {
4972 // Count or type has changed
4973 isDifferent = true;
4974 }
4975 } else {
4976 // No last entry, so always consider to be different
4977 isDifferent = true;
4978 }
4979
4980 if (isDifferent) {
4981 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004982 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4983 updatesDetected = true;
4984 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004985 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004986 }
4987 } else if (lastEntry.count > 0) {
4988 // Value has been removed
4989 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4990 mLatestSessionParams.erase(tag);
4991 updatesDetected = true;
4992 }
4993 }
4994
4995 return updatesDetected;
4996}
4997
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004998bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004999 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005000 status_t res;
5001
5002 // Handle paused state.
5003 if (waitIfPaused()) {
5004 return true;
5005 }
5006
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005007 // Wait for the next batch of requests.
5008 waitForNextRequestBatch();
5009 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005010 return true;
5011 }
5012
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005013 // Get the latest request ID, if any
5014 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005015 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005016 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005017 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005018 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005019 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005020 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5021 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005022 }
5023
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005024 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5025 // or a single request from streaming or burst. In either case the first element
5026 // should contain the latest camera settings that we need to check for any session
5027 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005028 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005029 res = OK;
5030
5031 //Input stream buffers are already acquired at this point so an input stream
5032 //will not be able to move to idle state unless we force it.
5033 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5034 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5035 if (res != OK) {
5036 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5037 cleanUpFailedRequests(/*sendRequestError*/ false);
5038 return false;
5039 }
5040 }
5041
5042 if (res == OK) {
5043 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5044 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005045 sp<Camera3Device> parent = mParent.promote();
5046 if (parent != nullptr) {
5047 parent->pauseStateNotify(true);
5048 }
5049
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005050 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5051
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005052 if (parent != nullptr) {
5053 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5054 }
5055
5056 statusTracker->markComponentActive(mStatusId);
5057 setPaused(false);
5058 }
5059
5060 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5061 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5062 if (res != OK) {
5063 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5064 cleanUpFailedRequests(/*sendRequestError*/ false);
5065 return false;
5066 }
5067 }
5068 }
5069 }
5070
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005071 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005072 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005073 if (res == TIMED_OUT) {
5074 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005075 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005076 // Check if any stream is abandoned.
5077 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005078 return true;
5079 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005080 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005081 return false;
5082 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005083
Zhijun Hecc27e112013-10-03 16:12:43 -07005084 // Inform waitUntilRequestProcessed thread of a new request ID
5085 {
5086 Mutex::Autolock al(mLatestRequestMutex);
5087
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005088 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005089 mLatestRequestSignal.signal();
5090 }
5091
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005092 // Submit a batch of requests to HAL.
5093 // Use flush lock only when submitting multilple requests in a batch.
5094 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5095 // which may take a long time to finish so synchronizing flush() and
5096 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5097 // For now, only synchronize for high speed recording and we should figure something out for
5098 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005099 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005100
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005101 if (useFlushLock) {
5102 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005103 }
5104
Zhijun Hef0645c12016-08-02 00:58:11 -07005105 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005106 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005107
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005108 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005109 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005110 if (mInterface->supportBatchRequest()) {
5111 submitRequestSuccess = sendRequestsBatch();
5112 } else {
5113 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005114 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005115 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5116 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005117
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005118 if (submitRequestSuccess) {
5119 sp<Camera3Device> parent = mParent.promote();
5120 if (parent != nullptr) {
5121 parent->mRequestBufferSM.onRequestSubmitted();
5122 }
5123 }
5124
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005125 if (useFlushLock) {
5126 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005127 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005128
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005129 // Unset as current request
5130 {
5131 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005132 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005133 }
5134
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005135 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005136}
5137
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005138status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005139 ATRACE_CALL();
5140
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005141 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005142 for (size_t i = 0; i < mNextRequests.size(); i++) {
5143 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005144 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5145 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5146 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5147
5148 // Prepare a request to HAL
5149 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5150
5151 // Insert any queued triggers (before metadata is locked)
5152 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005153 if (res < 0) {
5154 SET_ERR("RequestThread: Unable to insert triggers "
5155 "(capture request %d, HAL device: %s (%d)",
5156 halRequest->frame_number, strerror(-res), res);
5157 return INVALID_OPERATION;
5158 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005159
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005160 int triggerCount = res;
5161 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5162 mPrevTriggers = triggerCount;
5163
5164 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005165 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5166 // Request settings are all the same within one batch, so only treat the first
5167 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005168 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005169 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005170 /**
5171 * HAL workaround:
5172 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5173 */
5174 res = addDummyTriggerIds(captureRequest);
5175 if (res != OK) {
5176 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5177 "(capture request %d, HAL device: %s (%d)",
5178 halRequest->frame_number, strerror(-res), res);
5179 return INVALID_OPERATION;
5180 }
5181
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005182 {
5183 // Correct metadata regions for distortion correction if enabled
5184 sp<Camera3Device> parent = mParent.promote();
5185 if (parent != nullptr) {
5186 res = parent->mDistortionMapper.correctCaptureRequest(
5187 &(captureRequest->mSettingsList.begin()->metadata));
5188 if (res != OK) {
5189 SET_ERR("RequestThread: Unable to correct capture requests "
5190 "for lens distortion for request %d: %s (%d)",
5191 halRequest->frame_number, strerror(-res), res);
5192 return INVALID_OPERATION;
5193 }
5194 }
5195 }
5196
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005197 /**
5198 * The request should be presorted so accesses in HAL
5199 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5200 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005201 captureRequest->mSettingsList.begin()->metadata.sort();
5202 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005203 mPrevRequest = captureRequest;
5204 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5205
5206 IF_ALOGV() {
5207 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5208 find_camera_metadata_ro_entry(
5209 halRequest->settings,
5210 ANDROID_CONTROL_AF_TRIGGER,
5211 &e
5212 );
5213 if (e.count > 0) {
5214 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5215 __FUNCTION__,
5216 halRequest->frame_number,
5217 e.data.u8[0]);
5218 }
5219 }
5220 } else {
5221 // leave request.settings NULL to indicate 'reuse latest given'
5222 ALOGVV("%s: Request settings are REUSED",
5223 __FUNCTION__);
5224 }
5225
Emilian Peevaebbe412018-01-15 13:53:24 +00005226 if (captureRequest->mSettingsList.size() > 1) {
5227 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5228 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005229 if (newRequest) {
5230 halRequest->physcam_settings =
5231 new const camera_metadata* [halRequest->num_physcam_settings];
5232 } else {
5233 halRequest->physcam_settings = nullptr;
5234 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005235 auto it = ++captureRequest->mSettingsList.begin();
5236 size_t i = 0;
5237 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5238 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005239 if (newRequest) {
5240 it->metadata.sort();
5241 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5242 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005243 }
5244 }
5245
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005246 uint32_t totalNumBuffers = 0;
5247
5248 // Fill in buffers
5249 if (captureRequest->mInputStream != NULL) {
5250 halRequest->input_buffer = &captureRequest->mInputBuffer;
5251 totalNumBuffers += 1;
5252 } else {
5253 halRequest->input_buffer = NULL;
5254 }
5255
5256 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5257 captureRequest->mOutputStreams.size());
5258 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005259 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005260
5261 sp<Camera3Device> parent = mParent.promote();
5262 if (parent == NULL) {
5263 // Should not happen, and nowhere to send errors to, so just log it
5264 CLOGE("RequestThread: Parent is gone");
5265 return INVALID_OPERATION;
5266 }
5267 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5268
Shuzhen Wang4a472662017-02-26 23:29:04 -08005269 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
5270 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005271
5272 // Prepare video buffers for high speed recording on the first video request.
5273 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5274 // Only try to prepare video stream on the first video request.
5275 mPrepareVideoStream = false;
5276
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005277 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5278 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005279 while (res == NOT_ENOUGH_DATA) {
5280 res = outputStream->prepareNextBuffer();
5281 }
5282 if (res != OK) {
5283 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5284 __FUNCTION__, strerror(-res), res);
5285 outputStream->cancelPrepare();
5286 }
5287 }
5288
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005289 if (mUseHalBufManager) {
5290 // HAL will request buffer through requestStreamBuffer API
5291 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5292 buffer.stream = outputStream->asHalStream();
5293 buffer.buffer = nullptr;
5294 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5295 buffer.acquire_fence = -1;
5296 buffer.release_fence = -1;
5297 } else {
5298 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5299 waitDuration,
5300 captureRequest->mOutputSurfaces[outputStream->getId()]);
5301 if (res != OK) {
5302 // Can't get output buffer from gralloc queue - this could be due to
5303 // abandoned queue or other consumer misbehavior, so not a fatal
5304 // error
5305 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5306 " %s (%d)", strerror(-res), res);
5307
5308 return TIMED_OUT;
5309 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005310 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005311
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005312 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5313
5314 if (!physicalCameraId.isEmpty()) {
5315 // Physical stream isn't supported for input request.
5316 if (halRequest->input_buffer) {
5317 CLOGE("Physical stream is not supported for input request");
5318 return INVALID_OPERATION;
5319 }
5320 requestedPhysicalCameras.insert(physicalCameraId);
5321 }
5322 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005323 }
5324 totalNumBuffers += halRequest->num_output_buffers;
5325
5326 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005327 // If this request list is for constrained high speed recording (not
5328 // preview), and the current request is not the last one in the batch,
5329 // do not send callback to the app.
5330 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005331 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005332 hasCallback = false;
5333 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005334 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005335 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005336 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5337 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5338 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5339 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5340 isStillCapture = true;
5341 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5342 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005343
5344 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5345 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5346 isZslCapture = true;
5347 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005348 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005349 res = parent->registerInFlight(halRequest->frame_number,
5350 totalNumBuffers, captureRequest->mResultExtras,
5351 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005352 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005353 calculateMaxExpectedDuration(halRequest->settings),
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005354 requestedPhysicalCameras, isStillCapture, isZslCapture);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005355 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5356 ", burstId = %" PRId32 ".",
5357 __FUNCTION__,
5358 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5359 captureRequest->mResultExtras.burstId);
5360 if (res != OK) {
5361 SET_ERR("RequestThread: Unable to register new in-flight request:"
5362 " %s (%d)", strerror(-res), res);
5363 return INVALID_OPERATION;
5364 }
5365 }
5366
5367 return OK;
5368}
5369
Igor Murashkin1e479c02013-09-06 16:55:14 -07005370CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005371 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005372 Mutex::Autolock al(mLatestRequestMutex);
5373
5374 ALOGV("RequestThread::%s", __FUNCTION__);
5375
5376 return mLatestRequest;
5377}
5378
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005379bool Camera3Device::RequestThread::isStreamPending(
5380 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005381 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005382 Mutex::Autolock l(mRequestLock);
5383
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005384 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005385 if (!nextRequest.submitted) {
5386 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5387 if (stream == s) return true;
5388 }
5389 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005390 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005391 }
5392
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005393 for (const auto& request : mRequestQueue) {
5394 for (const auto& s : request->mOutputStreams) {
5395 if (stream == s) return true;
5396 }
5397 if (stream == request->mInputStream) return true;
5398 }
5399
5400 for (const auto& request : mRepeatingRequests) {
5401 for (const auto& s : request->mOutputStreams) {
5402 if (stream == s) return true;
5403 }
5404 if (stream == request->mInputStream) return true;
5405 }
5406
5407 return false;
5408}
Jianing Weicb0652e2014-03-12 18:29:36 -07005409
Emilian Peev40ead602017-09-26 15:46:36 +01005410bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5411 ATRACE_CALL();
5412 Mutex::Autolock l(mRequestLock);
5413
5414 for (const auto& nextRequest : mNextRequests) {
5415 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5416 if (s.first == streamId) {
5417 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5418 if (it != s.second.end()) {
5419 return true;
5420 }
5421 }
5422 }
5423 }
5424
5425 for (const auto& request : mRequestQueue) {
5426 for (const auto& s : request->mOutputSurfaces) {
5427 if (s.first == streamId) {
5428 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5429 if (it != s.second.end()) {
5430 return true;
5431 }
5432 }
5433 }
5434 }
5435
5436 for (const auto& request : mRepeatingRequests) {
5437 for (const auto& s : request->mOutputSurfaces) {
5438 if (s.first == streamId) {
5439 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5440 if (it != s.second.end()) {
5441 return true;
5442 }
5443 }
5444 }
5445 }
5446
5447 return false;
5448}
5449
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005450void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5451 if (!mUseHalBufManager) {
5452 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5453 return;
5454 }
5455
5456 Mutex::Autolock pl(mPauseLock);
5457 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005458 mInterface->signalPipelineDrain(streamIds);
5459 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005460 }
5461 // If request thread is still busy, wait until paused then notify HAL
5462 mNotifyPipelineDrain = true;
5463 mStreamIdsToBeDrained = streamIds;
5464}
5465
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005466nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005467 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005468 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005469 return mExpectedInflightDuration > kMinInflightDuration ?
5470 mExpectedInflightDuration : kMinInflightDuration;
5471}
5472
Emilian Peevaebbe412018-01-15 13:53:24 +00005473void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5474 camera3_capture_request_t *halRequest) {
5475 if ((request == nullptr) || (halRequest == nullptr)) {
5476 ALOGE("%s: Invalid request!", __FUNCTION__);
5477 return;
5478 }
5479
5480 if (halRequest->num_physcam_settings > 0) {
5481 if (halRequest->physcam_id != nullptr) {
5482 delete [] halRequest->physcam_id;
5483 halRequest->physcam_id = nullptr;
5484 }
5485 if (halRequest->physcam_settings != nullptr) {
5486 auto it = ++(request->mSettingsList.begin());
5487 size_t i = 0;
5488 for (; it != request->mSettingsList.end(); it++, i++) {
5489 it->metadata.unlock(halRequest->physcam_settings[i]);
5490 }
5491 delete [] halRequest->physcam_settings;
5492 halRequest->physcam_settings = nullptr;
5493 }
5494 }
5495}
5496
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005497void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5498 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005499 return;
5500 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005501
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005502 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005503 // Skip the ones that have been submitted successfully.
5504 if (nextRequest.submitted) {
5505 continue;
5506 }
5507
5508 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5509 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5510 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5511
5512 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005513 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005514 }
5515
Emilian Peevaebbe412018-01-15 13:53:24 +00005516 cleanupPhysicalSettings(captureRequest, halRequest);
5517
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005518 if (captureRequest->mInputStream != NULL) {
5519 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5520 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5521 }
5522
5523 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005524 //Buffers that failed processing could still have
5525 //valid acquire fence.
5526 int acquireFence = (*outputBuffers)[i].acquire_fence;
5527 if (0 <= acquireFence) {
5528 close(acquireFence);
5529 outputBuffers->editItemAt(i).acquire_fence = -1;
5530 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005531 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5532 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5533 }
5534
5535 if (sendRequestError) {
5536 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005537 sp<NotificationListener> listener = mListener.promote();
5538 if (listener != NULL) {
5539 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005540 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005541 captureRequest->mResultExtras);
5542 }
5543 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005544
5545 // Remove yet-to-be submitted inflight request from inflightMap
5546 {
5547 sp<Camera3Device> parent = mParent.promote();
5548 if (parent != NULL) {
5549 Mutex::Autolock l(parent->mInFlightLock);
5550 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5551 if (idx >= 0) {
5552 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5553 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5554 parent->removeInFlightMapEntryLocked(idx);
5555 }
5556 }
5557 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005558 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005559
5560 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005561 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005562}
5563
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005564void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005565 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005566 // Optimized a bit for the simple steady-state case (single repeating
5567 // request), to avoid putting that request in the queue temporarily.
5568 Mutex::Autolock l(mRequestLock);
5569
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005570 assert(mNextRequests.empty());
5571
5572 NextRequest nextRequest;
5573 nextRequest.captureRequest = waitForNextRequestLocked();
5574 if (nextRequest.captureRequest == nullptr) {
5575 return;
5576 }
5577
5578 nextRequest.halRequest = camera3_capture_request_t();
5579 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005580 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005581
5582 // Wait for additional requests
5583 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5584
5585 for (size_t i = 1; i < batchSize; i++) {
5586 NextRequest additionalRequest;
5587 additionalRequest.captureRequest = waitForNextRequestLocked();
5588 if (additionalRequest.captureRequest == nullptr) {
5589 break;
5590 }
5591
5592 additionalRequest.halRequest = camera3_capture_request_t();
5593 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005594 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005595 }
5596
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005597 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005598 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005599 mNextRequests.size(), batchSize);
5600 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005601 }
5602
5603 return;
5604}
5605
5606sp<Camera3Device::CaptureRequest>
5607 Camera3Device::RequestThread::waitForNextRequestLocked() {
5608 status_t res;
5609 sp<CaptureRequest> nextRequest;
5610
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005611 while (mRequestQueue.empty()) {
5612 if (!mRepeatingRequests.empty()) {
5613 // Always atomically enqueue all requests in a repeating request
5614 // list. Guarantees a complete in-sequence set of captures to
5615 // application.
5616 const RequestList &requests = mRepeatingRequests;
5617 RequestList::const_iterator firstRequest =
5618 requests.begin();
5619 nextRequest = *firstRequest;
5620 mRequestQueue.insert(mRequestQueue.end(),
5621 ++firstRequest,
5622 requests.end());
5623 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005624
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005625 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005626
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005627 break;
5628 }
5629
5630 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5631
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005632 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5633 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005634 Mutex::Autolock pl(mPauseLock);
5635 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005636 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005637 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005638 // Let the tracker know
5639 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5640 if (statusTracker != 0) {
5641 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5642 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005643 if (mNotifyPipelineDrain) {
5644 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5645 mNotifyPipelineDrain = false;
5646 mStreamIdsToBeDrained.clear();
5647 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005648 sp<Camera3Device> parent = mParent.promote();
5649 if (parent != nullptr) {
5650 parent->mRequestBufferSM.onRequestThreadPaused();
5651 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005652 }
5653 // Stop waiting for now and let thread management happen
5654 return NULL;
5655 }
5656 }
5657
5658 if (nextRequest == NULL) {
5659 // Don't have a repeating request already in hand, so queue
5660 // must have an entry now.
5661 RequestList::iterator firstRequest =
5662 mRequestQueue.begin();
5663 nextRequest = *firstRequest;
5664 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005665 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5666 sp<NotificationListener> listener = mListener.promote();
5667 if (listener != NULL) {
5668 listener->notifyRequestQueueEmpty();
5669 }
5670 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005671 }
5672
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005673 // In case we've been unpaused by setPaused clearing mDoPause, need to
5674 // update internal pause state (capture/setRepeatingRequest unpause
5675 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005676 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005677 if (mPaused) {
5678 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5679 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5680 if (statusTracker != 0) {
5681 statusTracker->markComponentActive(mStatusId);
5682 }
5683 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005684 mPaused = false;
5685
5686 // Check if we've reconfigured since last time, and reset the preview
5687 // request if so. Can't use 'NULL request == repeat' across configure calls.
5688 if (mReconfigured) {
5689 mPrevRequest.clear();
5690 mReconfigured = false;
5691 }
5692
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005693 if (nextRequest != NULL) {
5694 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005695 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5696 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005697
5698 // Since RequestThread::clear() removes buffers from the input stream,
5699 // get the right buffer here before unlocking mRequestLock
5700 if (nextRequest->mInputStream != NULL) {
5701 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5702 if (res != OK) {
5703 // Can't get input buffer from gralloc queue - this could be due to
5704 // disconnected queue or other producer misbehavior, so not a fatal
5705 // error
5706 ALOGE("%s: Can't get input buffer, skipping request:"
5707 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005708
5709 sp<NotificationListener> listener = mListener.promote();
5710 if (listener != NULL) {
5711 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005712 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005713 nextRequest->mResultExtras);
5714 }
5715 return NULL;
5716 }
5717 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005718 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005719
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005720 return nextRequest;
5721}
5722
5723bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005724 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005725 status_t res;
5726 Mutex::Autolock l(mPauseLock);
5727 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005728 if (mPaused == false) {
5729 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005730 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5731 // Let the tracker know
5732 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5733 if (statusTracker != 0) {
5734 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5735 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005736 if (mNotifyPipelineDrain) {
5737 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5738 mNotifyPipelineDrain = false;
5739 mStreamIdsToBeDrained.clear();
5740 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005741 sp<Camera3Device> parent = mParent.promote();
5742 if (parent != nullptr) {
5743 parent->mRequestBufferSM.onRequestThreadPaused();
5744 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005745 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005746
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005747 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005748 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005749 return true;
5750 }
5751 }
5752 // We don't set mPaused to false here, because waitForNextRequest needs
5753 // to further manage the paused state in case of starvation.
5754 return false;
5755}
5756
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005757void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005758 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005759 // With work to do, mark thread as unpaused.
5760 // If paused by request (setPaused), don't resume, to avoid
5761 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005762 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005763 Mutex::Autolock p(mPauseLock);
5764 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005765 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5766 if (mPaused) {
5767 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5768 if (statusTracker != 0) {
5769 statusTracker->markComponentActive(mStatusId);
5770 }
5771 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005772 mPaused = false;
5773 }
5774}
5775
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005776void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5777 sp<Camera3Device> parent = mParent.promote();
5778 if (parent != NULL) {
5779 va_list args;
5780 va_start(args, fmt);
5781
5782 parent->setErrorStateV(fmt, args);
5783
5784 va_end(args);
5785 }
5786}
5787
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005788status_t Camera3Device::RequestThread::insertTriggers(
5789 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005790 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005791 Mutex::Autolock al(mTriggerMutex);
5792
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005793 sp<Camera3Device> parent = mParent.promote();
5794 if (parent == NULL) {
5795 CLOGE("RequestThread: Parent is gone");
5796 return DEAD_OBJECT;
5797 }
5798
Emilian Peevaebbe412018-01-15 13:53:24 +00005799 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005800 size_t count = mTriggerMap.size();
5801
5802 for (size_t i = 0; i < count; ++i) {
5803 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005804 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005805
5806 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5807 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5808 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005809 if (isAeTrigger) {
5810 request->mResultExtras.precaptureTriggerId = triggerId;
5811 mCurrentPreCaptureTriggerId = triggerId;
5812 } else {
5813 request->mResultExtras.afTriggerId = triggerId;
5814 mCurrentAfTriggerId = triggerId;
5815 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005816 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005817 }
5818
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005819 camera_metadata_entry entry = metadata.find(tag);
5820
5821 if (entry.count > 0) {
5822 /**
5823 * Already has an entry for this trigger in the request.
5824 * Rewrite it with our requested trigger value.
5825 */
5826 RequestTrigger oldTrigger = trigger;
5827
5828 oldTrigger.entryValue = entry.data.u8[0];
5829
5830 mTriggerReplacedMap.add(tag, oldTrigger);
5831 } else {
5832 /**
5833 * More typical, no trigger entry, so we just add it
5834 */
5835 mTriggerRemovedMap.add(tag, trigger);
5836 }
5837
5838 status_t res;
5839
5840 switch (trigger.getTagType()) {
5841 case TYPE_BYTE: {
5842 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5843 res = metadata.update(tag,
5844 &entryValue,
5845 /*count*/1);
5846 break;
5847 }
5848 case TYPE_INT32:
5849 res = metadata.update(tag,
5850 &trigger.entryValue,
5851 /*count*/1);
5852 break;
5853 default:
5854 ALOGE("%s: Type not supported: 0x%x",
5855 __FUNCTION__,
5856 trigger.getTagType());
5857 return INVALID_OPERATION;
5858 }
5859
5860 if (res != OK) {
5861 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5862 ", value %d", __FUNCTION__, trigger.getTagName(),
5863 trigger.entryValue);
5864 return res;
5865 }
5866
5867 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5868 trigger.getTagName(),
5869 trigger.entryValue);
5870 }
5871
5872 mTriggerMap.clear();
5873
5874 return count;
5875}
5876
5877status_t Camera3Device::RequestThread::removeTriggers(
5878 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005879 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005880 Mutex::Autolock al(mTriggerMutex);
5881
Emilian Peevaebbe412018-01-15 13:53:24 +00005882 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005883
5884 /**
5885 * Replace all old entries with their old values.
5886 */
5887 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5888 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5889
5890 status_t res;
5891
5892 uint32_t tag = trigger.metadataTag;
5893 switch (trigger.getTagType()) {
5894 case TYPE_BYTE: {
5895 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5896 res = metadata.update(tag,
5897 &entryValue,
5898 /*count*/1);
5899 break;
5900 }
5901 case TYPE_INT32:
5902 res = metadata.update(tag,
5903 &trigger.entryValue,
5904 /*count*/1);
5905 break;
5906 default:
5907 ALOGE("%s: Type not supported: 0x%x",
5908 __FUNCTION__,
5909 trigger.getTagType());
5910 return INVALID_OPERATION;
5911 }
5912
5913 if (res != OK) {
5914 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5915 ", trigger value %d", __FUNCTION__,
5916 trigger.getTagName(), trigger.entryValue);
5917 return res;
5918 }
5919 }
5920 mTriggerReplacedMap.clear();
5921
5922 /**
5923 * Remove all new entries.
5924 */
5925 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5926 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5927 status_t res = metadata.erase(trigger.metadataTag);
5928
5929 if (res != OK) {
5930 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5931 ", trigger value %d", __FUNCTION__,
5932 trigger.getTagName(), trigger.entryValue);
5933 return res;
5934 }
5935 }
5936 mTriggerRemovedMap.clear();
5937
5938 return OK;
5939}
5940
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005941status_t Camera3Device::RequestThread::addDummyTriggerIds(
5942 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005943 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005944 static const int32_t dummyTriggerId = 1;
5945 status_t res;
5946
Emilian Peevaebbe412018-01-15 13:53:24 +00005947 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005948
5949 // If AF trigger is active, insert a dummy AF trigger ID if none already
5950 // exists
5951 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5952 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5953 if (afTrigger.count > 0 &&
5954 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5955 afId.count == 0) {
5956 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5957 if (res != OK) return res;
5958 }
5959
5960 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5961 // if none already exists
5962 camera_metadata_entry pcTrigger =
5963 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5964 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5965 if (pcTrigger.count > 0 &&
5966 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5967 pcId.count == 0) {
5968 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5969 &dummyTriggerId, 1);
5970 if (res != OK) return res;
5971 }
5972
5973 return OK;
5974}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005975
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005976/**
5977 * PreparerThread inner class methods
5978 */
5979
5980Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005981 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005982 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005983}
5984
5985Camera3Device::PreparerThread::~PreparerThread() {
5986 Thread::requestExitAndWait();
5987 if (mCurrentStream != nullptr) {
5988 mCurrentStream->cancelPrepare();
5989 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5990 mCurrentStream.clear();
5991 }
5992 clear();
5993}
5994
Ruben Brunkc78ac262015-08-13 17:58:46 -07005995status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005996 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005997 status_t res;
5998
5999 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006000 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006001
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006002 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006003 if (res == OK) {
6004 // No preparation needed, fire listener right off
6005 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006006 if (listener != NULL) {
6007 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006008 }
6009 return OK;
6010 } else if (res != NOT_ENOUGH_DATA) {
6011 return res;
6012 }
6013
6014 // Need to prepare, start up thread if necessary
6015 if (!mActive) {
6016 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6017 // isn't running
6018 Thread::requestExitAndWait();
6019 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6020 if (res != OK) {
6021 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006022 if (listener != NULL) {
6023 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006024 }
6025 return res;
6026 }
6027 mCancelNow = false;
6028 mActive = true;
6029 ALOGV("%s: Preparer stream started", __FUNCTION__);
6030 }
6031
6032 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006033 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006034 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6035
6036 return OK;
6037}
6038
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006039void Camera3Device::PreparerThread::pause() {
6040 ATRACE_CALL();
6041
6042 Mutex::Autolock l(mLock);
6043
6044 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6045 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6046 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6047 int currentMaxCount = mCurrentMaxCount;
6048 mPendingStreams.clear();
6049 mCancelNow = true;
6050 while (mActive) {
6051 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6052 if (res == TIMED_OUT) {
6053 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6054 return;
6055 } else if (res != OK) {
6056 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6057 return;
6058 }
6059 }
6060
6061 //Check whether the prepare thread was able to complete the current
6062 //stream. In case work is still pending emplace it along with the rest
6063 //of the streams in the pending list.
6064 if (currentStream != nullptr) {
6065 if (!mCurrentPrepareComplete) {
6066 pendingStreams.emplace(currentMaxCount, currentStream);
6067 }
6068 }
6069
6070 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6071 for (const auto& it : mPendingStreams) {
6072 it.second->cancelPrepare();
6073 }
6074}
6075
6076status_t Camera3Device::PreparerThread::resume() {
6077 ATRACE_CALL();
6078 status_t res;
6079
6080 Mutex::Autolock l(mLock);
6081 sp<NotificationListener> listener = mListener.promote();
6082
6083 if (mActive) {
6084 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6085 return NO_INIT;
6086 }
6087
6088 auto it = mPendingStreams.begin();
6089 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006090 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006091 if (res == OK) {
6092 if (listener != NULL) {
6093 listener->notifyPrepared(it->second->getId());
6094 }
6095 it = mPendingStreams.erase(it);
6096 } else if (res != NOT_ENOUGH_DATA) {
6097 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6098 res, strerror(-res));
6099 it = mPendingStreams.erase(it);
6100 } else {
6101 it++;
6102 }
6103 }
6104
6105 if (mPendingStreams.empty()) {
6106 return OK;
6107 }
6108
6109 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6110 if (res != OK) {
6111 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6112 __FUNCTION__, res, strerror(-res));
6113 return res;
6114 }
6115 mCancelNow = false;
6116 mActive = true;
6117 ALOGV("%s: Preparer stream started", __FUNCTION__);
6118
6119 return OK;
6120}
6121
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006122status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006123 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006124 Mutex::Autolock l(mLock);
6125
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006126 for (const auto& it : mPendingStreams) {
6127 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006128 }
6129 mPendingStreams.clear();
6130 mCancelNow = true;
6131
6132 return OK;
6133}
6134
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006135void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006136 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006137 Mutex::Autolock l(mLock);
6138 mListener = listener;
6139}
6140
6141bool Camera3Device::PreparerThread::threadLoop() {
6142 status_t res;
6143 {
6144 Mutex::Autolock l(mLock);
6145 if (mCurrentStream == nullptr) {
6146 // End thread if done with work
6147 if (mPendingStreams.empty()) {
6148 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6149 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6150 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6151 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006152 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006153 return false;
6154 }
6155
6156 // Get next stream to prepare
6157 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006158 mCurrentStream = it->second;
6159 mCurrentMaxCount = it->first;
6160 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006161 mPendingStreams.erase(it);
6162 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6163 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6164 } else if (mCancelNow) {
6165 mCurrentStream->cancelPrepare();
6166 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6167 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6168 mCurrentStream.clear();
6169 mCancelNow = false;
6170 return true;
6171 }
6172 }
6173
6174 res = mCurrentStream->prepareNextBuffer();
6175 if (res == NOT_ENOUGH_DATA) return true;
6176 if (res != OK) {
6177 // Something bad happened; try to recover by cancelling prepare and
6178 // signalling listener anyway
6179 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6180 mCurrentStream->getId(), res, strerror(-res));
6181 mCurrentStream->cancelPrepare();
6182 }
6183
6184 // This stream has finished, notify listener
6185 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006186 sp<NotificationListener> listener = mListener.promote();
6187 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006188 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6189 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006190 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006191 }
6192
6193 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6194 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006195 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006196
6197 return true;
6198}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006199
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006200status_t Camera3Device::RequestBufferStateMachine::initialize(
6201 sp<camera3::StatusTracker> statusTracker) {
6202 if (statusTracker == nullptr) {
6203 ALOGE("%s: statusTracker is null", __FUNCTION__);
6204 return BAD_VALUE;
6205 }
6206
6207 std::lock_guard<std::mutex> lock(mLock);
6208 mStatusTracker = statusTracker;
6209 mRequestBufferStatusId = statusTracker->addComponent();
6210 return OK;
6211}
6212
6213bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6214 std::lock_guard<std::mutex> lock(mLock);
6215 if (mStatus == RB_STATUS_READY) {
6216 mRequestBufferOngoing = true;
6217 return true;
6218 }
6219 return false;
6220}
6221
6222void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6223 std::lock_guard<std::mutex> lock(mLock);
6224 if (!mRequestBufferOngoing) {
6225 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6226 return;
6227 }
6228 mRequestBufferOngoing = false;
6229 if (mStatus == RB_STATUS_PENDING_STOP) {
6230 checkSwitchToStopLocked();
6231 }
6232}
6233
6234void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6235 std::lock_guard<std::mutex> lock(mLock);
6236 RequestBufferState oldStatus = mStatus;
6237 mStatus = RB_STATUS_READY;
6238 if (oldStatus != RB_STATUS_READY) {
6239 notifyTrackerLocked(/*active*/true);
6240 }
6241 return;
6242}
6243
6244void Camera3Device::RequestBufferStateMachine::onRequestSubmitted() {
6245 std::lock_guard<std::mutex> lock(mLock);
6246 mRequestThreadPaused = false;
6247 mInflightMapEmpty = false;
6248 if (mStatus == RB_STATUS_STOPPED) {
6249 mStatus = RB_STATUS_READY;
6250 notifyTrackerLocked(/*active*/true);
6251 }
6252 return;
6253}
6254
6255void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6256 std::lock_guard<std::mutex> lock(mLock);
6257 mRequestThreadPaused = true;
6258 if (mStatus == RB_STATUS_PENDING_STOP) {
6259 checkSwitchToStopLocked();
6260 }
6261 return;
6262}
6263
6264void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6265 std::lock_guard<std::mutex> lock(mLock);
6266 mInflightMapEmpty = true;
6267 if (mStatus == RB_STATUS_PENDING_STOP) {
6268 checkSwitchToStopLocked();
6269 }
6270 return;
6271}
6272
6273void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6274 std::lock_guard<std::mutex> lock(mLock);
6275 if (!checkSwitchToStopLocked()) {
6276 mStatus = RB_STATUS_PENDING_STOP;
6277 }
6278 return;
6279}
6280
6281void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6282 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6283 if (statusTracker != nullptr) {
6284 if (active) {
6285 statusTracker->markComponentActive(mRequestBufferStatusId);
6286 } else {
6287 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6288 }
6289 }
6290}
6291
6292bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6293 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6294 mStatus = RB_STATUS_STOPPED;
6295 notifyTrackerLocked(/*active*/false);
6296 return true;
6297 }
6298 return false;
6299}
6300
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006301}; // namespace android