blob: be1aaed700148c340c60d46b95f8c118a76e1adc [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Shuzhen Wang5c22c152017-12-31 17:12:25 -080042#include <utility>
43
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080044#include <utils/Log.h>
45#include <utils/Trace.h>
46#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070047#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070048
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080049#include <android/hardware/camera2/ICameraDeviceUser.h>
50
Igor Murashkinff3e31d2013-10-23 16:40:06 -070051#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070052#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "device3/Camera3Device.h"
54#include "device3/Camera3OutputStream.h"
55#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070056#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070057#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070058#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070059#include "utils/CameraThreadState.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080060
61using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080062using namespace android::hardware::camera;
63using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080064
65namespace android {
66
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080067Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080068 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080069 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070070 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070071 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070072 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070073 mUsePartialResult(false),
74 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080075 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070076 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070077 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070078 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070079 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000080 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010081 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
82 mLastTemplateId(-1)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080083{
84 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080085 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080086}
87
88Camera3Device::~Camera3Device()
89{
90 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080091 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -070092 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080093}
94
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080095const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080096 return mId;
97}
98
Emilian Peevbd8c5032018-02-14 23:05:40 +000099status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800100 ATRACE_CALL();
101 Mutex::Autolock il(mInterfaceLock);
102 Mutex::Autolock l(mLock);
103
104 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
105 if (mStatus != STATUS_UNINITIALIZED) {
106 CLOGE("Already initialized!");
107 return INVALID_OPERATION;
108 }
109 if (manager == nullptr) return INVALID_OPERATION;
110
111 sp<ICameraDeviceSession> session;
112 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800113 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800114 /*out*/ &session);
115 ATRACE_END();
116 if (res != OK) {
117 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
118 return res;
119 }
120
Steven Moreland5ff9c912017-03-09 23:13:00 -0800121 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800122 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700123 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800124 session->close();
125 return res;
126 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800127
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700128 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700129 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700130 if (isLogical) {
131 for (auto& physicalId : physicalCameraIds) {
132 res = manager->getCameraCharacteristics(physicalId, &mPhysicalDeviceInfoMap[physicalId]);
133 if (res != OK) {
134 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
135 physicalId.c_str(), strerror(-res), res);
136 session->close();
137 return res;
138 }
139 }
140 }
141
Yifan Hongf79b5542017-04-11 14:44:25 -0700142 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700143 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
144 [&queue](const auto& descriptor) {
145 queue = std::make_shared<RequestMetadataQueue>(descriptor);
146 if (!queue->isValid() || queue->availableToWrite() <= 0) {
147 ALOGE("HAL returns empty request metadata fmq, not use it");
148 queue = nullptr;
149 // don't use the queue onwards.
150 }
151 });
152 if (!requestQueueRet.isOk()) {
153 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
154 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700155 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700156 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700157
158 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700159 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700160 [&resQueue](const auto& descriptor) {
161 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
162 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700163 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700164 resQueue = nullptr;
165 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700166 }
167 });
168 if (!resultQueueRet.isOk()) {
169 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
170 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700171 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700172 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700173 IF_ALOGV() {
174 session->interfaceChain([](
175 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
176 ALOGV("Session interface chain:");
177 for (auto iface : interfaceChain) {
178 ALOGV(" %s", iface.c_str());
179 }
180 });
181 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700182
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700183 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000184 std::string providerType;
185 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000186 mTagMonitor.initialize(mVendorTagId);
187 if (!monitorTags.isEmpty()) {
188 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
189 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800190
191 return initializeCommonLocked();
192}
193
194status_t Camera3Device::initializeCommonLocked() {
195
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700196 /** Start up status tracker thread */
197 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800198 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700199 if (res != OK) {
200 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
201 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800202 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700203 mStatusTracker.clear();
204 return res;
205 }
206
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700207 /** Register in-flight map to the status tracker */
208 mInFlightStatusId = mStatusTracker->addComponent();
209
Zhijun He125684a2015-12-26 15:07:30 -0800210 /** Create buffer manager */
211 mBufferManager = new Camera3BufferManager();
212
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000213 Vector<int32_t> sessionParamKeys;
214 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
215 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
216 if (sessionKeysEntry.count > 0) {
217 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
218 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700219
220 camera_metadata_entry bufMgrMode =
221 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
222 if (bufMgrMode.count > 0) {
223 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
224 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
225 }
226
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 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001087 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1088 camera3_stream_buffer_t& sb = streamBuffers[b];
1089 sb.acquire_fence = -1;
1090 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1091 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001092 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1093 }
1094 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001095
1096 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1097 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1098 BufferRequestStatus::FAILED_UNKNOWN,
1099 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001100 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001101 return hardware::Void();
1102}
1103
1104hardware::Return<void> Camera3Device::returnStreamBuffers(
1105 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1106 if (!mUseHalBufManager) {
1107 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1108 __FUNCTION__, mId.string());
1109 return hardware::Void();
1110 }
1111
1112 for (const auto& buf : buffers) {
1113 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1114 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1115 continue;
1116 }
1117
1118 buffer_handle_t* buffer;
1119 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1120
1121 if (res != OK) {
1122 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1123 __FUNCTION__, buf.bufferId, buf.streamId);
1124 continue;
1125 }
1126
1127 camera3_stream_buffer_t streamBuffer;
1128 streamBuffer.buffer = buffer;
1129 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1130 streamBuffer.acquire_fence = -1;
1131 streamBuffer.release_fence = -1;
1132
1133 if (buf.releaseFence == nullptr) {
1134 streamBuffer.release_fence = -1;
1135 } else if (buf.releaseFence->numFds == 1) {
1136 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1137 } else {
1138 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1139 __FUNCTION__, buf.releaseFence->numFds);
1140 continue;
1141 }
1142
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001143 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1144 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001145 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1146 continue;
1147 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001148 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001149 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1150 }
1151 return hardware::Void();
1152}
1153
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001154hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001155 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001156 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001157 // Ideally we should grab mLock, but that can lead to deadlock, and
1158 // it's not super important to get up to date value of mStatus for this
1159 // warning print, hence skipping the lock here
1160 if (mStatus == STATUS_ERROR) {
1161 // Per API contract, HAL should act as closed after device error
1162 // But mStatus can be set to error by framework as well, so just log
1163 // a warning here.
1164 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001165 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001166
1167 if (mProcessCaptureResultLock.tryLock() != OK) {
1168 // This should never happen; it indicates a wrong client implementation
1169 // that doesn't follow the contract. But, we can be tolerant here.
1170 ALOGE("%s: callback overlapped! waiting 1s...",
1171 __FUNCTION__);
1172 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1173 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1174 __FUNCTION__);
1175 // really don't know what to do, so bail out.
1176 return hardware::Void();
1177 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001178 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001179 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001180 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001181 }
1182 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001183 return hardware::Void();
1184}
1185
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001186// Only one processCaptureResult should be called at a time, so
1187// the locks won't block. The locks are present here simply to enforce this.
1188hardware::Return<void> Camera3Device::processCaptureResult(
1189 const hardware::hidl_vec<
1190 hardware::camera::device::V3_2::CaptureResult>& results) {
1191 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1192
1193 // Ideally we should grab mLock, but that can lead to deadlock, and
1194 // it's not super important to get up to date value of mStatus for this
1195 // warning print, hence skipping the lock here
1196 if (mStatus == STATUS_ERROR) {
1197 // Per API contract, HAL should act as closed after device error
1198 // But mStatus can be set to error by framework as well, so just log
1199 // a warning here.
1200 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1201 }
1202
1203 if (mProcessCaptureResultLock.tryLock() != OK) {
1204 // This should never happen; it indicates a wrong client implementation
1205 // that doesn't follow the contract. But, we can be tolerant here.
1206 ALOGE("%s: callback overlapped! waiting 1s...",
1207 __FUNCTION__);
1208 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1209 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1210 __FUNCTION__);
1211 // really don't know what to do, so bail out.
1212 return hardware::Void();
1213 }
1214 }
1215 for (const auto& result : results) {
1216 processOneCaptureResultLocked(result, noPhysMetadata);
1217 }
1218 mProcessCaptureResultLock.unlock();
1219 return hardware::Void();
1220}
1221
1222status_t Camera3Device::readOneCameraMetadataLocked(
1223 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1224 const hardware::camera::device::V3_2::CameraMetadata& result) {
1225 if (fmqResultSize > 0) {
1226 resultMetadata.resize(fmqResultSize);
1227 if (mResultMetadataQueue == nullptr) {
1228 return NO_MEMORY; // logged in initialize()
1229 }
1230 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1231 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1232 __FUNCTION__, fmqResultSize);
1233 return INVALID_OPERATION;
1234 }
1235 } else {
1236 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1237 result.size());
1238 }
1239
1240 if (resultMetadata.size() != 0) {
1241 status_t res;
1242 const camera_metadata_t* metadata =
1243 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1244 size_t expected_metadata_size = resultMetadata.size();
1245 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1246 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1247 __FUNCTION__, strerror(-res), res);
1248 return INVALID_OPERATION;
1249 }
1250 }
1251
1252 return OK;
1253}
1254
Yifan Honga640c5a2017-04-12 16:30:31 -07001255void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001256 const hardware::camera::device::V3_2::CaptureResult& result,
1257 const hardware::hidl_vec<
1258 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001259 camera3_capture_result r;
1260 status_t res;
1261 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001262
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001263 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001264 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001265 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1266 if (res != OK) {
1267 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1268 __FUNCTION__, result.frameNumber);
1269 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001270 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001271 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001272
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001273 // Read and validate physical camera metadata
1274 size_t physResultCount = physicalCameraMetadatas.size();
1275 std::vector<const char*> physCamIds(physResultCount);
1276 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1277 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1278 physResultMetadata.resize(physResultCount);
1279 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1280 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1281 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1282 if (res != OK) {
1283 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1284 __FUNCTION__, result.frameNumber,
1285 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001286 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001287 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001288 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1289 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1290 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001291 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001292 r.num_physcam_metadata = physResultCount;
1293 r.physcam_ids = physCamIds.data();
1294 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001295
1296 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1297 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1298 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1299 auto& bDst = outputBuffers[i];
1300 const StreamBuffer &bSrc = result.outputBuffers[i];
1301
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001302 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1303 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001304 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1305 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001306 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001307 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001308 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001309
1310 buffer_handle_t *buffer;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001311 if (mUseHalBufManager) {
1312 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1313 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1314 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1315 return;
1316 }
1317 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1318 } else {
1319 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1320 }
1321
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001322 if (res != OK) {
1323 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1324 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001325 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001326 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001327
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001328 bDst.buffer = buffer;
1329 bDst.status = mapHidlBufferStatus(bSrc.status);
1330 bDst.acquire_fence = -1;
1331 if (bSrc.releaseFence == nullptr) {
1332 bDst.release_fence = -1;
1333 } else if (bSrc.releaseFence->numFds == 1) {
1334 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1335 } else {
1336 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1337 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001338 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001339 }
1340 }
1341 r.num_output_buffers = outputBuffers.size();
1342 r.output_buffers = outputBuffers.data();
1343
1344 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001345 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001346 r.input_buffer = nullptr;
1347 } else {
1348 if (mInputStream->getId() != result.inputBuffer.streamId) {
1349 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1350 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001351 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001352 }
1353 inputBuffer.stream = mInputStream->asHalStream();
1354 buffer_handle_t *buffer;
1355 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1356 &buffer);
1357 if (res != OK) {
1358 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1359 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001360 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001361 }
1362 inputBuffer.buffer = buffer;
1363 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1364 inputBuffer.acquire_fence = -1;
1365 if (result.inputBuffer.releaseFence == nullptr) {
1366 inputBuffer.release_fence = -1;
1367 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1368 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1369 } else {
1370 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1371 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001372 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001373 }
1374 r.input_buffer = &inputBuffer;
1375 }
1376
1377 r.partial_result = result.partialResult;
1378
1379 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001380}
1381
1382hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001383 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001384 // Ideally we should grab mLock, but that can lead to deadlock, and
1385 // it's not super important to get up to date value of mStatus for this
1386 // warning print, hence skipping the lock here
1387 if (mStatus == STATUS_ERROR) {
1388 // Per API contract, HAL should act as closed after device error
1389 // But mStatus can be set to error by framework as well, so just log
1390 // a warning here.
1391 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001392 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001393
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001394 for (const auto& msg : msgs) {
1395 notify(msg);
1396 }
1397 return hardware::Void();
1398}
1399
1400void Camera3Device::notify(
1401 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1402
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001403 camera3_notify_msg m;
1404 switch (msg.type) {
1405 case MsgType::ERROR:
1406 m.type = CAMERA3_MSG_ERROR;
1407 m.message.error.frame_number = msg.msg.error.frameNumber;
1408 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001409 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1410 if (stream == nullptr) {
1411 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1412 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001413 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001414 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001415 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001416 } else {
1417 m.message.error.error_stream = nullptr;
1418 }
1419 switch (msg.msg.error.errorCode) {
1420 case ErrorCode::ERROR_DEVICE:
1421 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1422 break;
1423 case ErrorCode::ERROR_REQUEST:
1424 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1425 break;
1426 case ErrorCode::ERROR_RESULT:
1427 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1428 break;
1429 case ErrorCode::ERROR_BUFFER:
1430 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1431 break;
1432 }
1433 break;
1434 case MsgType::SHUTTER:
1435 m.type = CAMERA3_MSG_SHUTTER;
1436 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1437 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1438 break;
1439 }
1440 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001441}
1442
Emilian Peevaebbe412018-01-15 13:53:24 +00001443status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001444 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001445 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001446 ATRACE_CALL();
1447
Emilian Peevaebbe412018-01-15 13:53:24 +00001448 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001449}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001450
Jianing Weicb0652e2014-03-12 18:29:36 -07001451status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1452 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001453 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001454
Emilian Peevaebbe412018-01-15 13:53:24 +00001455 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001456 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001457 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001458
Emilian Peevaebbe412018-01-15 13:53:24 +00001459 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001460 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001461}
1462
Emilian Peevaebbe412018-01-15 13:53:24 +00001463status_t Camera3Device::setStreamingRequestList(
1464 const List<const PhysicalCameraSettingsList> &requestsList,
1465 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001466 ATRACE_CALL();
1467
Emilian Peevaebbe412018-01-15 13:53:24 +00001468 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001469}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001470
1471sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001472 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001473 status_t res;
1474
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001475 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001476 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1477 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001478 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1479 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001480 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001482 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001483 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001484 } else if (mStatus == STATUS_UNCONFIGURED) {
1485 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001486 CLOGE("No streams configured");
1487 return NULL;
1488 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001489 }
1490
Shuzhen Wang0129d522016-10-30 22:43:41 -07001491 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001492 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001493}
1494
Jianing Weicb0652e2014-03-12 18:29:36 -07001495status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001496 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001497 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001499
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500 switch (mStatus) {
1501 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001502 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 return INVALID_OPERATION;
1504 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001505 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001507 case STATUS_UNCONFIGURED:
1508 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001509 case STATUS_ACTIVE:
1510 // OK
1511 break;
1512 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001513 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001514 return INVALID_OPERATION;
1515 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001516 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001517
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001518 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001519}
1520
1521status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1522 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001523 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001524
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001525 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001526}
1527
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001528status_t Camera3Device::createInputStream(
1529 uint32_t width, uint32_t height, int format, int *id) {
1530 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001531 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001532 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001533 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001534 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1535 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001536
1537 status_t res;
1538 bool wasActive = false;
1539
1540 switch (mStatus) {
1541 case STATUS_ERROR:
1542 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1543 return INVALID_OPERATION;
1544 case STATUS_UNINITIALIZED:
1545 ALOGE("%s: Device not initialized", __FUNCTION__);
1546 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001547 case STATUS_UNCONFIGURED:
1548 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001549 // OK
1550 break;
1551 case STATUS_ACTIVE:
1552 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001553 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001554 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001555 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001556 return res;
1557 }
1558 wasActive = true;
1559 break;
1560 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001561 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001562 return INVALID_OPERATION;
1563 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001564 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001565
1566 if (mInputStream != 0) {
1567 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1568 return INVALID_OPERATION;
1569 }
1570
1571 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1572 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001573 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001574
1575 mInputStream = newStream;
1576
1577 *id = mNextStreamId++;
1578
1579 // Continue captures if active at start
1580 if (wasActive) {
1581 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001582 // Reuse current operating mode and session parameters for new stream config
1583 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001584 if (res != OK) {
1585 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1586 __FUNCTION__, mNextStreamId, strerror(-res), res);
1587 return res;
1588 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001589 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001590 }
1591
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001592 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001593 return OK;
1594}
1595
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001596status_t Camera3Device::StreamSet::add(
1597 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1598 if (stream == nullptr) {
1599 ALOGE("%s: cannot add null stream", __FUNCTION__);
1600 return BAD_VALUE;
1601 }
1602 std::lock_guard<std::mutex> lock(mLock);
1603 return mData.add(streamId, stream);
1604}
1605
1606ssize_t Camera3Device::StreamSet::remove(int streamId) {
1607 std::lock_guard<std::mutex> lock(mLock);
1608 return mData.removeItem(streamId);
1609}
1610
1611sp<camera3::Camera3OutputStreamInterface>
1612Camera3Device::StreamSet::get(int streamId) {
1613 std::lock_guard<std::mutex> lock(mLock);
1614 ssize_t idx = mData.indexOfKey(streamId);
1615 if (idx == NAME_NOT_FOUND) {
1616 return nullptr;
1617 }
1618 return mData.editValueAt(idx);
1619}
1620
1621sp<camera3::Camera3OutputStreamInterface>
1622Camera3Device::StreamSet::operator[] (size_t index) {
1623 std::lock_guard<std::mutex> lock(mLock);
1624 return mData.editValueAt(index);
1625}
1626
1627size_t Camera3Device::StreamSet::size() const {
1628 std::lock_guard<std::mutex> lock(mLock);
1629 return mData.size();
1630}
1631
1632void Camera3Device::StreamSet::clear() {
1633 std::lock_guard<std::mutex> lock(mLock);
1634 return mData.clear();
1635}
1636
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001637std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1638 std::lock_guard<std::mutex> lock(mLock);
1639 std::vector<int> streamIds(mData.size());
1640 for (size_t i = 0; i < mData.size(); i++) {
1641 streamIds[i] = mData.keyAt(i);
1642 }
1643 return streamIds;
1644}
1645
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001646status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001647 uint32_t width, uint32_t height, int format,
1648 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001649 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001650 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001651 ATRACE_CALL();
1652
1653 if (consumer == nullptr) {
1654 ALOGE("%s: consumer must not be null", __FUNCTION__);
1655 return BAD_VALUE;
1656 }
1657
1658 std::vector<sp<Surface>> consumers;
1659 consumers.push_back(consumer);
1660
1661 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001662 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1663 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001664}
1665
1666status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1667 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1668 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001669 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001670 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001671 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001672
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001673 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001674 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001675 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001676 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001677 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1678 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1679 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001680
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001681 status_t res;
1682 bool wasActive = false;
1683
1684 switch (mStatus) {
1685 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001686 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001687 return INVALID_OPERATION;
1688 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001689 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001690 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001691 case STATUS_UNCONFIGURED:
1692 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001693 // OK
1694 break;
1695 case STATUS_ACTIVE:
1696 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001697 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001698 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001699 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001700 return res;
1701 }
1702 wasActive = true;
1703 break;
1704 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001705 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001706 return INVALID_OPERATION;
1707 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001708 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001709
1710 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001711
Shuzhen Wang0129d522016-10-30 22:43:41 -07001712 if (consumers.size() == 0 && !hasDeferredConsumer) {
1713 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1714 return BAD_VALUE;
1715 }
Zhijun He5d677d12016-05-29 16:52:39 -07001716
Shuzhen Wang0129d522016-10-30 22:43:41 -07001717 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001718 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1719 return BAD_VALUE;
1720 }
1721
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001722 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001723 ssize_t blobBufferSize;
1724 if (dataSpace != HAL_DATASPACE_DEPTH) {
1725 blobBufferSize = getJpegBufferSize(width, height);
1726 if (blobBufferSize <= 0) {
1727 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1728 return BAD_VALUE;
1729 }
1730 } else {
1731 blobBufferSize = getPointCloudBufferSize();
1732 if (blobBufferSize <= 0) {
1733 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1734 return BAD_VALUE;
1735 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001736 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001737 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001738 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001739 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001740 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1741 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1742 if (rawOpaqueBufferSize <= 0) {
1743 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1744 return BAD_VALUE;
1745 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001746 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001747 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001748 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001749 } else if (isShared) {
1750 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1751 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001752 mTimestampOffset, physicalCameraId, streamSetId,
1753 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001754 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001755 newStream = new Camera3OutputStream(mNextStreamId,
1756 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001757 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001758 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001759 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001760 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001761 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001762 }
Emilian Peev40ead602017-09-26 15:46:36 +01001763
1764 size_t consumerCount = consumers.size();
1765 for (size_t i = 0; i < consumerCount; i++) {
1766 int id = newStream->getSurfaceId(consumers[i]);
1767 if (id < 0) {
1768 SET_ERR_L("Invalid surface id");
1769 return BAD_VALUE;
1770 }
1771 if (surfaceIds != nullptr) {
1772 surfaceIds->push_back(id);
1773 }
1774 }
1775
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001776 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001777
Emilian Peev08dd2452017-04-06 16:55:14 +01001778 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001779
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001780 res = mOutputStreams.add(mNextStreamId, newStream);
1781 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001782 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001783 return res;
1784 }
1785
1786 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001787 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001788
1789 // Continue captures if active at start
1790 if (wasActive) {
1791 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001792 // Reuse current operating mode and session parameters for new stream config
1793 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001794 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001795 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1796 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001797 return res;
1798 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001799 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001800 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001801 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001802 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001803}
1804
Emilian Peev710c1422017-08-30 11:19:38 +01001805status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001806 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001807 if (nullptr == streamInfo) {
1808 return BAD_VALUE;
1809 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001810 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001811 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001812
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001813 switch (mStatus) {
1814 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001815 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001816 return INVALID_OPERATION;
1817 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001818 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001819 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001820 case STATUS_UNCONFIGURED:
1821 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001822 case STATUS_ACTIVE:
1823 // OK
1824 break;
1825 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001826 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001827 return INVALID_OPERATION;
1828 }
1829
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001830 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1831 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001832 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001833 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001834 }
1835
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001836 streamInfo->width = stream->getWidth();
1837 streamInfo->height = stream->getHeight();
1838 streamInfo->format = stream->getFormat();
1839 streamInfo->dataSpace = stream->getDataSpace();
1840 streamInfo->formatOverridden = stream->isFormatOverridden();
1841 streamInfo->originalFormat = stream->getOriginalFormat();
1842 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1843 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001844 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001845}
1846
1847status_t Camera3Device::setStreamTransform(int id,
1848 int transform) {
1849 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001850 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001851 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001852
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001853 switch (mStatus) {
1854 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001855 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001856 return INVALID_OPERATION;
1857 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001858 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001859 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001860 case STATUS_UNCONFIGURED:
1861 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001862 case STATUS_ACTIVE:
1863 // OK
1864 break;
1865 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001866 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001867 return INVALID_OPERATION;
1868 }
1869
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001870 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1871 if (stream == nullptr) {
1872 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001873 return BAD_VALUE;
1874 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001875 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001876}
1877
1878status_t Camera3Device::deleteStream(int id) {
1879 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001880 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001881 Mutex::Autolock l(mLock);
1882 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001883
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001884 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001885
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001886 // CameraDevice semantics require device to already be idle before
1887 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001888 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001889 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001890 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001891 }
1892
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001893 if (mStatus == STATUS_ERROR) {
1894 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1895 __FUNCTION__, mId.string());
1896 return -EBUSY;
1897 }
1898
Igor Murashkin2fba5842013-04-22 14:03:54 -07001899 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001900 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001901 if (mInputStream != NULL && id == mInputStream->getId()) {
1902 deletedStream = mInputStream;
1903 mInputStream.clear();
1904 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001905 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001906 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001907 return BAD_VALUE;
1908 }
Zhijun He5f446352014-01-22 09:49:33 -08001909 }
1910
1911 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001912 if (stream != nullptr) {
1913 deletedStream = stream;
1914 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001915 }
1916
1917 // Free up the stream endpoint so that it can be used by some other stream
1918 res = deletedStream->disconnect();
1919 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001920 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001921 // fall through since we want to still list the stream as deleted.
1922 }
1923 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001924 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001925
1926 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001927}
1928
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001929status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001930 ATRACE_CALL();
1931 ALOGV("%s: E", __FUNCTION__);
1932
1933 Mutex::Autolock il(mInterfaceLock);
1934 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001935
Emilian Peev811d2952018-05-25 11:08:40 +01001936 // In case the client doesn't include any session parameter, try a
1937 // speculative configuration using the values from the last cached
1938 // default request.
1939 if (sessionParams.isEmpty() &&
1940 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1941 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1942 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1943 mLastTemplateId);
1944 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1945 operatingMode);
1946 }
1947
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001948 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1949}
1950
1951status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1952 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001953 //Filter out any incoming session parameters
1954 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001955 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1956 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001957 CameraMetadata filteredParams(availableSessionKeys.count);
1958 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1959 filteredParams.getAndLock());
1960 set_camera_metadata_vendor_id(meta, mVendorTagId);
1961 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001962 if (availableSessionKeys.count > 0) {
1963 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1964 camera_metadata_ro_entry entry = params.find(
1965 availableSessionKeys.data.i32[i]);
1966 if (entry.count > 0) {
1967 filteredParams.update(entry);
1968 }
1969 }
1970 }
1971
1972 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001973}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001974
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001975status_t Camera3Device::getInputBufferProducer(
1976 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001977 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001978 Mutex::Autolock il(mInterfaceLock);
1979 Mutex::Autolock l(mLock);
1980
1981 if (producer == NULL) {
1982 return BAD_VALUE;
1983 } else if (mInputStream == NULL) {
1984 return INVALID_OPERATION;
1985 }
1986
1987 return mInputStream->getInputBufferProducer(producer);
1988}
1989
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001990status_t Camera3Device::createDefaultRequest(int templateId,
1991 CameraMetadata *request) {
1992 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001993 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001994
1995 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1996 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07001997 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001998 return BAD_VALUE;
1999 }
2000
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002001 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002002
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002003 {
2004 Mutex::Autolock l(mLock);
2005 switch (mStatus) {
2006 case STATUS_ERROR:
2007 CLOGE("Device has encountered a serious error");
2008 return INVALID_OPERATION;
2009 case STATUS_UNINITIALIZED:
2010 CLOGE("Device is not initialized!");
2011 return INVALID_OPERATION;
2012 case STATUS_UNCONFIGURED:
2013 case STATUS_CONFIGURED:
2014 case STATUS_ACTIVE:
2015 // OK
2016 break;
2017 default:
2018 SET_ERR_L("Unexpected status: %d", mStatus);
2019 return INVALID_OPERATION;
2020 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002021
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002022 if (!mRequestTemplateCache[templateId].isEmpty()) {
2023 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002024 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002025 return OK;
2026 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002027 }
2028
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002029 camera_metadata_t *rawRequest;
2030 status_t res = mInterface->constructDefaultRequestSettings(
2031 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002032
2033 {
2034 Mutex::Autolock l(mLock);
2035 if (res == BAD_VALUE) {
2036 ALOGI("%s: template %d is not supported on this camera device",
2037 __FUNCTION__, templateId);
2038 return res;
2039 } else if (res != OK) {
2040 CLOGE("Unable to construct request template %d: %s (%d)",
2041 templateId, strerror(-res), res);
2042 return res;
2043 }
2044
2045 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2046 mRequestTemplateCache[templateId].acquire(rawRequest);
2047
2048 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002049 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002050 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002051 return OK;
2052}
2053
2054status_t Camera3Device::waitUntilDrained() {
2055 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002056 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002057 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002058 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002059
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002060 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002061}
2062
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002063status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002064 switch (mStatus) {
2065 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002066 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002067 ALOGV("%s: Already idle", __FUNCTION__);
2068 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002069 case STATUS_CONFIGURED:
2070 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002071 case STATUS_ERROR:
2072 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002073 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002074 break;
2075 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002076 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002077 return INVALID_OPERATION;
2078 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002079 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2080 maxExpectedDuration);
2081 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002082 if (res != OK) {
2083 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2084 res);
2085 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002086 return res;
2087}
2088
Ruben Brunk183f0562015-08-12 12:55:02 -07002089
2090void Camera3Device::internalUpdateStatusLocked(Status status) {
2091 mStatus = status;
2092 mRecentStatusUpdates.add(mStatus);
2093 mStatusChanged.broadcast();
2094}
2095
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002096void Camera3Device::pauseStateNotify(bool enable) {
2097 Mutex::Autolock il(mInterfaceLock);
2098 Mutex::Autolock l(mLock);
2099
2100 mPauseStateNotify = enable;
2101}
2102
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002103// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002104status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002105 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002106
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002107 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2108 maxExpectedDuration);
2109 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002110 if (res != OK) {
2111 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002112 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002113 }
2114
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002115 return res;
2116}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002117
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002118// Resume after internalPauseAndWaitLocked
2119status_t Camera3Device::internalResumeLocked() {
2120 status_t res;
2121
2122 mRequestThread->setPaused(false);
2123
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002124 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2125 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002126 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2127 if (res != OK) {
2128 SET_ERR_L("Can't transition to active in %f seconds!",
2129 kActiveTimeout/1e9);
2130 }
2131 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002132 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002133}
2134
Ruben Brunk183f0562015-08-12 12:55:02 -07002135status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002136 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002137
2138 size_t startIndex = 0;
2139 if (mStatusWaiters == 0) {
2140 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2141 // this status list
2142 mRecentStatusUpdates.clear();
2143 } else {
2144 // If other threads are waiting on updates to this status list, set the position of the
2145 // first element that this list will check rather than clearing the list.
2146 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002147 }
2148
Ruben Brunk183f0562015-08-12 12:55:02 -07002149 mStatusWaiters++;
2150
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002151 // Notify HAL to start draining. We need to notify the HalInterface layer
2152 // even when the device is already IDLE, so HalInterface can reject incoming
2153 // requestStreamBuffers call.
2154 if (!active && mUseHalBufManager) {
2155 auto streamIds = mOutputStreams.getStreamIds();
2156 mRequestThread->signalPipelineDrain(streamIds);
2157 mRequestBufferSM.onWaitUntilIdle();
2158 }
2159
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002160 bool stateSeen = false;
2161 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002162 if (active == (mStatus == STATUS_ACTIVE)) {
2163 // Desired state is current
2164 break;
2165 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002166
2167 res = mStatusChanged.waitRelative(mLock, timeout);
2168 if (res != OK) break;
2169
Ruben Brunk183f0562015-08-12 12:55:02 -07002170 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2171 // transitions.
2172 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2173 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2174 __FUNCTION__);
2175
2176 // Encountered desired state since we began waiting
2177 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002178 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2179 stateSeen = true;
2180 break;
2181 }
2182 }
2183 } while (!stateSeen);
2184
Ruben Brunk183f0562015-08-12 12:55:02 -07002185 mStatusWaiters--;
2186
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002187 return res;
2188}
2189
2190
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002191status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002192 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002193 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002194
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002195 if (listener != NULL && mListener != NULL) {
2196 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2197 }
2198 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002199 mRequestThread->setNotificationListener(listener);
2200 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002201
2202 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002203}
2204
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002205bool Camera3Device::willNotify3A() {
2206 return false;
2207}
2208
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002209status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002210 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002211 status_t res;
2212 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002213
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002214 while (mResultQueue.empty()) {
2215 res = mResultSignal.waitRelative(mOutputLock, timeout);
2216 if (res == TIMED_OUT) {
2217 return res;
2218 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002219 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2220 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002221 return res;
2222 }
2223 }
2224 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002225}
2226
Jianing Weicb0652e2014-03-12 18:29:36 -07002227status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002228 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002229 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002230
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002231 if (mResultQueue.empty()) {
2232 return NOT_ENOUGH_DATA;
2233 }
2234
Jianing Weicb0652e2014-03-12 18:29:36 -07002235 if (frame == NULL) {
2236 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2237 return BAD_VALUE;
2238 }
2239
2240 CaptureResult &result = *(mResultQueue.begin());
2241 frame->mResultExtras = result.mResultExtras;
2242 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002243 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002244 mResultQueue.erase(mResultQueue.begin());
2245
2246 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002247}
2248
2249status_t Camera3Device::triggerAutofocus(uint32_t id) {
2250 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002251 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002252
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002253 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2254 // Mix-in this trigger into the next request and only the next request.
2255 RequestTrigger trigger[] = {
2256 {
2257 ANDROID_CONTROL_AF_TRIGGER,
2258 ANDROID_CONTROL_AF_TRIGGER_START
2259 },
2260 {
2261 ANDROID_CONTROL_AF_TRIGGER_ID,
2262 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002263 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002264 };
2265
2266 return mRequestThread->queueTrigger(trigger,
2267 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002268}
2269
2270status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2271 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002272 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002273
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002274 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2275 // Mix-in this trigger into the next request and only the next request.
2276 RequestTrigger trigger[] = {
2277 {
2278 ANDROID_CONTROL_AF_TRIGGER,
2279 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2280 },
2281 {
2282 ANDROID_CONTROL_AF_TRIGGER_ID,
2283 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002284 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002285 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002286
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002287 return mRequestThread->queueTrigger(trigger,
2288 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002289}
2290
2291status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2292 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002293 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002294
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002295 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2296 // Mix-in this trigger into the next request and only the next request.
2297 RequestTrigger trigger[] = {
2298 {
2299 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2300 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2301 },
2302 {
2303 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2304 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002305 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002306 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002307
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002308 return mRequestThread->queueTrigger(trigger,
2309 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002310}
2311
Jianing Weicb0652e2014-03-12 18:29:36 -07002312status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002313 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002314 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002315 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002316
Zhijun He7ef20392014-04-21 16:04:17 -07002317 {
2318 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002319
2320 // b/116514106 "disconnect()" can get called twice for the same device. The
2321 // camera device will not be initialized during the second run.
2322 if (mStatus == STATUS_UNINITIALIZED) {
2323 return OK;
2324 }
2325
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002326 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002327 }
2328
Emilian Peev08dd2452017-04-06 16:55:14 +01002329 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002330}
2331
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002332status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002333 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2334}
2335
2336status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002337 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002338 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002339 Mutex::Autolock il(mInterfaceLock);
2340 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002341
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002342 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2343 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002344 CLOGE("Stream %d does not exist", streamId);
2345 return BAD_VALUE;
2346 }
2347
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002348 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002349 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002350 return BAD_VALUE;
2351 }
2352
2353 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002354 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002355 return BAD_VALUE;
2356 }
2357
Ruben Brunkc78ac262015-08-13 17:58:46 -07002358 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002359}
2360
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002361status_t Camera3Device::tearDown(int streamId) {
2362 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002363 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002364 Mutex::Autolock il(mInterfaceLock);
2365 Mutex::Autolock l(mLock);
2366
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002367 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2368 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002369 CLOGE("Stream %d does not exist", streamId);
2370 return BAD_VALUE;
2371 }
2372
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002373 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2374 CLOGE("Stream %d is a target of a in-progress request", streamId);
2375 return BAD_VALUE;
2376 }
2377
2378 return stream->tearDown();
2379}
2380
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002381status_t Camera3Device::addBufferListenerForStream(int streamId,
2382 wp<Camera3StreamBufferListener> listener) {
2383 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002384 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002385 Mutex::Autolock il(mInterfaceLock);
2386 Mutex::Autolock l(mLock);
2387
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002388 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2389 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002390 CLOGE("Stream %d does not exist", streamId);
2391 return BAD_VALUE;
2392 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002393 stream->addBufferListener(listener);
2394
2395 return OK;
2396}
2397
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002398/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002399 * Methods called by subclasses
2400 */
2401
2402void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002403 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002404 {
2405 // Need mLock to safely update state and synchronize to current
2406 // state of methods in flight.
2407 Mutex::Autolock l(mLock);
2408 // We can get various system-idle notices from the status tracker
2409 // while starting up. Only care about them if we've actually sent
2410 // in some requests recently.
2411 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2412 return;
2413 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002414 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2415 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002416 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002417
2418 // Skip notifying listener if we're doing some user-transparent
2419 // state changes
2420 if (mPauseStateNotify) return;
2421 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002422
2423 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002424 {
2425 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002426 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002427 }
2428 if (idle && listener != NULL) {
2429 listener->notifyIdle();
2430 }
2431}
2432
Shuzhen Wang758c2152017-01-10 18:26:18 -08002433status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002434 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002435 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002436 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2437 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002438
2439 if (surfaceIds == nullptr) {
2440 return BAD_VALUE;
2441 }
2442
Zhijun He5d677d12016-05-29 16:52:39 -07002443 Mutex::Autolock il(mInterfaceLock);
2444 Mutex::Autolock l(mLock);
2445
Shuzhen Wang758c2152017-01-10 18:26:18 -08002446 if (consumers.size() == 0) {
2447 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002448 return BAD_VALUE;
2449 }
2450
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002451 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2452 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002453 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002454 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002455 }
Shuzhen Wang758c2152017-01-10 18:26:18 -08002456 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002457 if (res != OK) {
2458 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2459 return res;
2460 }
2461
Emilian Peev40ead602017-09-26 15:46:36 +01002462 for (auto &consumer : consumers) {
2463 int id = stream->getSurfaceId(consumer);
2464 if (id < 0) {
2465 CLOGE("Invalid surface id!");
2466 return BAD_VALUE;
2467 }
2468 surfaceIds->push_back(id);
2469 }
2470
Shuzhen Wang0129d522016-10-30 22:43:41 -07002471 if (stream->isConsumerConfigurationDeferred()) {
2472 if (!stream->isConfiguring()) {
2473 CLOGE("Stream %d was already fully configured.", streamId);
2474 return INVALID_OPERATION;
2475 }
Zhijun He5d677d12016-05-29 16:52:39 -07002476
Shuzhen Wang0129d522016-10-30 22:43:41 -07002477 res = stream->finishConfiguration();
2478 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002479 // If finishConfiguration fails due to abandoned surface, do not set
2480 // device to error state.
2481 bool isSurfaceAbandoned =
2482 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2483 if (!isSurfaceAbandoned) {
2484 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2485 stream->getId(), strerror(-res), res);
2486 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002487 return res;
2488 }
Zhijun He5d677d12016-05-29 16:52:39 -07002489 }
2490
2491 return OK;
2492}
2493
Emilian Peev40ead602017-09-26 15:46:36 +01002494status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2495 const std::vector<OutputStreamInfo> &outputInfo,
2496 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2497 Mutex::Autolock il(mInterfaceLock);
2498 Mutex::Autolock l(mLock);
2499
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002500 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2501 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002502 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002503 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002504 }
2505
2506 for (const auto &it : removedSurfaceIds) {
2507 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2508 CLOGE("Shared surface still part of a pending request!");
2509 return -EBUSY;
2510 }
2511 }
2512
Emilian Peev40ead602017-09-26 15:46:36 +01002513 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2514 if (res != OK) {
2515 CLOGE("Stream %d failed to update stream (error %d %s) ",
2516 streamId, res, strerror(-res));
2517 if (res == UNKNOWN_ERROR) {
2518 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2519 __FUNCTION__);
2520 }
2521 return res;
2522 }
2523
2524 return res;
2525}
2526
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002527status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2528 Mutex::Autolock il(mInterfaceLock);
2529 Mutex::Autolock l(mLock);
2530
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002531 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2532 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002533 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2534 return BAD_VALUE;
2535 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002536 return stream->dropBuffers(dropping);
2537}
2538
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002539/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002540 * Camera3Device private methods
2541 */
2542
2543sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002544 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002545 ATRACE_CALL();
2546 status_t res;
2547
2548 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002549 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002550
2551 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002552 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002553 if (inputStreams.count > 0) {
2554 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002555 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002556 CLOGE("Request references unknown input stream %d",
2557 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002558 return NULL;
2559 }
2560 // Lazy completion of stream configuration (allocation/registration)
2561 // on first use
2562 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002563 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002564 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002565 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002566 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002567 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002568 return NULL;
2569 }
2570 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002571 // Check if stream prepare is blocking requests.
2572 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002573 CLOGE("Request references an input stream that's being prepared!");
2574 return NULL;
2575 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002576
2577 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002578 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002579 }
2580
2581 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002582 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002583 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002584 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002585 return NULL;
2586 }
2587
2588 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002589 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2590 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002591 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002592 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002593 return NULL;
2594 }
Zhijun He5d677d12016-05-29 16:52:39 -07002595 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002596 auto iter = surfaceMap.find(streams.data.i32[i]);
2597 if (iter != surfaceMap.end()) {
2598 const std::vector<size_t>& surfaces = iter->second;
2599 for (const auto& surface : surfaces) {
2600 if (stream->isConsumerConfigurationDeferred(surface)) {
2601 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2602 "due to deferred consumer", stream->getId(), surface);
2603 return NULL;
2604 }
2605 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002606 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002607 }
2608
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002609 // Lazy completion of stream configuration (allocation/registration)
2610 // on first use
2611 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002612 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002613 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002614 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2615 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002616 return NULL;
2617 }
2618 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002619 // Check if stream prepare is blocking requests.
2620 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002621 CLOGE("Request references an output stream that's being prepared!");
2622 return NULL;
2623 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002624
2625 newRequest->mOutputStreams.push(stream);
2626 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002627 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002628 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002629
2630 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002631}
2632
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002633bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2634 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2635 Size size = mSupportedOpaqueInputSizes[i];
2636 if (size.width == width && size.height == height) {
2637 return true;
2638 }
2639 }
2640
2641 return false;
2642}
2643
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002644void Camera3Device::cancelStreamsConfigurationLocked() {
2645 int res = OK;
2646 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2647 res = mInputStream->cancelConfiguration();
2648 if (res != OK) {
2649 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2650 mInputStream->getId(), strerror(-res), res);
2651 }
2652 }
2653
2654 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002655 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002656 if (outputStream->isConfiguring()) {
2657 res = outputStream->cancelConfiguration();
2658 if (res != OK) {
2659 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2660 outputStream->getId(), strerror(-res), res);
2661 }
2662 }
2663 }
2664
2665 // Return state to that at start of call, so that future configures
2666 // properly clean things up
2667 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2668 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002669
2670 res = mPreparerThread->resume();
2671 if (res != OK) {
2672 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2673 }
2674}
2675
2676bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2677 ATRACE_CALL();
2678 bool ret = false;
2679
2680 Mutex::Autolock il(mInterfaceLock);
2681 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2682
2683 Mutex::Autolock l(mLock);
2684 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2685 if (rc == NO_ERROR) {
2686 mNeedConfig = true;
2687 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2688 if (rc == NO_ERROR) {
2689 ret = true;
2690 mPauseStateNotify = false;
2691 //Moving to active state while holding 'mLock' is important.
2692 //There could be pending calls to 'create-/deleteStream' which
2693 //will trigger another stream configuration while the already
2694 //present streams end up with outstanding buffers that will
2695 //not get drained.
2696 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002697 } else if (rc == DEAD_OBJECT) {
2698 // DEAD_OBJECT can be returned if either the consumer surface is
2699 // abandoned, or the HAL has died.
2700 // - If the HAL has died, configureStreamsLocked call will set
2701 // device to error state,
2702 // - If surface is abandoned, we should not set device to error
2703 // state.
2704 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002705 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002706 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002707 }
2708 } else {
2709 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2710 }
2711
2712 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002713}
2714
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002715status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002716 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002717 ATRACE_CALL();
2718 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002719
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002720 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002721 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002722 return INVALID_OPERATION;
2723 }
2724
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002725 if (operatingMode < 0) {
2726 CLOGE("Invalid operating mode: %d", operatingMode);
2727 return BAD_VALUE;
2728 }
2729
2730 bool isConstrainedHighSpeed =
2731 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2732 operatingMode;
2733
2734 if (mOperatingMode != operatingMode) {
2735 mNeedConfig = true;
2736 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2737 mOperatingMode = operatingMode;
2738 }
2739
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002740 if (!mNeedConfig) {
2741 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2742 return OK;
2743 }
2744
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002745 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2746 // adding a dummy stream instead.
2747 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2748 if (mOutputStreams.size() == 0) {
2749 addDummyStreamLocked();
2750 } else {
2751 tryRemoveDummyStreamLocked();
2752 }
2753
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002754 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002755 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002756
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002757 mPreparerThread->pause();
2758
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002759 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002760 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002761 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2762
2763 Vector<camera3_stream_t*> streams;
2764 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002765 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002766
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002767
2768 if (mInputStream != NULL) {
2769 camera3_stream_t *inputStream;
2770 inputStream = mInputStream->startConfiguration();
2771 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002772 CLOGE("Can't start input stream configuration");
2773 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002774 return INVALID_OPERATION;
2775 }
2776 streams.add(inputStream);
2777 }
2778
2779 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002780
2781 // Don't configure bidi streams twice, nor add them twice to the list
2782 if (mOutputStreams[i].get() ==
2783 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2784
2785 config.num_streams--;
2786 continue;
2787 }
2788
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002789 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002790 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002791 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002792 CLOGE("Can't start output stream configuration");
2793 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002794 return INVALID_OPERATION;
2795 }
2796 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002797
2798 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2799 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002800 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2801 // always occupy the initial entry.
2802 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002803 getJpegBufferSize(outputStream->width, outputStream->height));
2804 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002805 }
2806
2807 config.streams = streams.editArray();
2808
2809 // Do the HAL configuration; will potentially touch stream
2810 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002811
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002812 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002813 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002814 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002815
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002816 if (res == BAD_VALUE) {
2817 // HAL rejected this set of streams as unsupported, clean up config
2818 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002819 CLOGE("Set of requested inputs/outputs not supported by HAL");
2820 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002821 return BAD_VALUE;
2822 } else if (res != OK) {
2823 // Some other kind of error from configure_streams - this is not
2824 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002825 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2826 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002827 return res;
2828 }
2829
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002830 // Finish all stream configuration immediately.
2831 // TODO: Try to relax this later back to lazy completion, which should be
2832 // faster
2833
Igor Murashkin073f8572013-05-02 14:59:28 -07002834 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002835 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002836 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002837 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002838 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002839 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002840 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2841 return DEAD_OBJECT;
2842 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002843 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002844 }
2845 }
2846
2847 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002848 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002849 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002850 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002851 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002852 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002853 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002854 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002855 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2856 return DEAD_OBJECT;
2857 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002858 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002859 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002860 }
2861 }
2862
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002863 // Request thread needs to know to avoid using repeat-last-settings protocol
2864 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002865 if (notifyRequestThread) {
2866 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2867 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002868
Zhijun He90f7c372016-08-16 16:19:43 -07002869 char value[PROPERTY_VALUE_MAX];
2870 property_get("camera.fifo.disable", value, "0");
2871 int32_t disableFifo = atoi(value);
2872 if (disableFifo != 1) {
2873 // Boost priority of request thread to SCHED_FIFO.
2874 pid_t requestThreadTid = mRequestThread->getTid();
2875 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002876 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002877 if (res != OK) {
2878 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2879 strerror(-res), res);
2880 } else {
2881 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2882 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002883 }
2884
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002885 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002886 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2887 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2888 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2889 sessionParams.unlock(newSessionParams);
2890 mSessionParams.unlock(currentSessionParams);
2891 if (updateSessionParams) {
2892 mSessionParams = sessionParams;
2893 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002894
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002895 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002896
Ruben Brunk183f0562015-08-12 12:55:02 -07002897 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2898 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002899
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002900 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002901
Zhijun He0a210512014-07-24 13:45:15 -07002902 // tear down the deleted streams after configure streams.
2903 mDeletedStreams.clear();
2904
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002905 auto rc = mPreparerThread->resume();
2906 if (rc != OK) {
2907 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2908 return rc;
2909 }
2910
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002911 if (mDummyStreamId == NO_STREAM) {
2912 mRequestBufferSM.onStreamsConfigured();
2913 }
2914
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002915 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002916}
2917
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002918status_t Camera3Device::addDummyStreamLocked() {
2919 ATRACE_CALL();
2920 status_t res;
2921
2922 if (mDummyStreamId != NO_STREAM) {
2923 // Should never be adding a second dummy stream when one is already
2924 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002925 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2926 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002927 return INVALID_OPERATION;
2928 }
2929
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002930 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002931
2932 sp<Camera3OutputStreamInterface> dummyStream =
2933 new Camera3DummyStream(mNextStreamId);
2934
2935 res = mOutputStreams.add(mNextStreamId, dummyStream);
2936 if (res < 0) {
2937 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2938 return res;
2939 }
2940
2941 mDummyStreamId = mNextStreamId;
2942 mNextStreamId++;
2943
2944 return OK;
2945}
2946
2947status_t Camera3Device::tryRemoveDummyStreamLocked() {
2948 ATRACE_CALL();
2949 status_t res;
2950
2951 if (mDummyStreamId == NO_STREAM) return OK;
2952 if (mOutputStreams.size() == 1) return OK;
2953
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002954 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002955
2956 // Ok, have a dummy stream and there's at least one other output stream,
2957 // so remove the dummy
2958
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002959 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2960 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002961 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2962 return INVALID_OPERATION;
2963 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002964 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002965
2966 // Free up the stream endpoint so that it can be used by some other stream
2967 res = deletedStream->disconnect();
2968 if (res != OK) {
2969 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2970 // fall through since we want to still list the stream as deleted.
2971 }
2972 mDeletedStreams.add(deletedStream);
2973 mDummyStreamId = NO_STREAM;
2974
2975 return res;
2976}
2977
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002978void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002979 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002980 Mutex::Autolock l(mLock);
2981 va_list args;
2982 va_start(args, fmt);
2983
2984 setErrorStateLockedV(fmt, args);
2985
2986 va_end(args);
2987}
2988
2989void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002990 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002991 Mutex::Autolock l(mLock);
2992 setErrorStateLockedV(fmt, args);
2993}
2994
2995void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2996 va_list args;
2997 va_start(args, fmt);
2998
2999 setErrorStateLockedV(fmt, args);
3000
3001 va_end(args);
3002}
3003
3004void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003005 // Print out all error messages to log
3006 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003007 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003008
3009 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003010 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003011
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003012 mErrorCause = errorCause;
3013
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003014 if (mRequestThread != nullptr) {
3015 mRequestThread->setPaused(true);
3016 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003017 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003018
3019 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003020 sp<NotificationListener> listener = mListener.promote();
3021 if (listener != NULL) {
3022 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003023 CaptureResultExtras());
3024 }
3025
3026 // Save stack trace. View by dumping it later.
3027 CameraTraces::saveTrace();
3028 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003029}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003030
3031/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003032 * In-flight request management
3033 */
3034
Jianing Weicb0652e2014-03-12 18:29:36 -07003035status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003036 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003037 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003038 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003039 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003040 ATRACE_CALL();
3041 Mutex::Autolock l(mInFlightLock);
3042
3043 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003044 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003045 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3046 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003047 if (res < 0) return res;
3048
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003049 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003050 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3051 // avoid a deadlock during reprocess requests.
3052 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003053 if (mStatusTracker != nullptr) {
3054 mStatusTracker->markComponentActive(mInFlightStatusId);
3055 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003056 }
3057
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003058 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003059 return OK;
3060}
3061
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003062void Camera3Device::returnOutputBuffers(
3063 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003064 nsecs_t timestamp, bool timestampIncreasing,
3065 const SurfaceMap& outputSurfaces,
3066 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003067
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003068 for (size_t i = 0; i < numBuffers; i++)
3069 {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003070 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3071 int streamId = stream->getId();
3072 const auto& it = outputSurfaces.find(streamId);
3073 status_t res = OK;
3074 if (it != outputSurfaces.end()) {
3075 res = stream->returnBuffer(
3076 outputBuffers[i], timestamp, timestampIncreasing, it->second);
3077 } else {
3078 res = stream->returnBuffer(
3079 outputBuffers[i], timestamp, timestampIncreasing);
3080 }
3081
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003082 // Note: stream may be deallocated at this point, if this buffer was
3083 // the last reference to it.
3084 if (res != OK) {
3085 ALOGE("Can't return buffer to its stream: %s (%d)",
3086 strerror(-res), res);
3087 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003088
3089 // Long processing consumers can cause returnBuffer timeout for shared stream
3090 // If that happens, cancel the buffer and send a buffer error to client
3091 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3092 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3093 // cancel the buffer
3094 camera3_stream_buffer_t sb = outputBuffers[i];
3095 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
3096 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing);
3097
3098 // notify client buffer error
3099 sp<NotificationListener> listener;
3100 {
3101 Mutex::Autolock l(mOutputLock);
3102 listener = mListener.promote();
3103 }
3104
3105 if (listener != nullptr) {
3106 CaptureResultExtras extras = inResultExtras;
3107 extras.errorStreamId = streamId;
3108 listener->notifyError(
3109 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3110 extras);
3111 }
3112 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003113 }
3114}
3115
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003116void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003117 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003118 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003119 mInFlightMap.removeItemsAt(idx, 1);
3120
3121 // Indicate idle inFlightMap to the status tracker
3122 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003123 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003124 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3125 // avoid a deadlock during reprocess requests.
3126 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003127 if (mStatusTracker != nullptr) {
3128 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3129 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003130 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003131 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003132}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003133
3134void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3135
3136 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3137 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3138
3139 nsecs_t sensorTimestamp = request.sensorTimestamp;
3140 nsecs_t shutterTimestamp = request.shutterTimestamp;
3141
3142 // Check if it's okay to remove the request from InFlightMap:
3143 // In the case of a successful request:
3144 // all input and output buffers, all result metadata, shutter callback
3145 // arrived.
3146 // In the case of a unsuccessful request:
3147 // all input and output buffers arrived.
3148 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003149 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003150 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003151 if (request.stillCapture) {
3152 ATRACE_ASYNC_END("still capture", frameNumber);
3153 }
3154
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003155 ATRACE_ASYNC_END("frame capture", frameNumber);
3156
Shuzhen Wang403044a2017-02-26 23:29:04 -08003157 // Sanity check - if sensor timestamp matches shutter timestamp in the
3158 // case of request having callback.
3159 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003160 sensorTimestamp != shutterTimestamp) {
3161 SET_ERR("sensor timestamp (%" PRId64
3162 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3163 sensorTimestamp, frameNumber, shutterTimestamp);
3164 }
3165
3166 // for an unsuccessful request, it may have pending output buffers to
3167 // return.
3168 assert(request.requestStatus != OK ||
3169 request.pendingOutputBuffers.size() == 0);
3170 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003171 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3172 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003173
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003174 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003175 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3176 }
3177
3178 // Sanity check - if we have too many in-flight frames, something has
3179 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003180 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003181 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003182 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3183 kInFlightWarnLimitHighSpeed) {
3184 CLOGE("In-flight list too large for high speed configuration: %zu",
3185 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003186 }
3187}
3188
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003189void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003190 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003191 { // First return buffers cached in mInFlightMap
3192 Mutex::Autolock l(mInFlightLock);
3193 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3194 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3195 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003196 request.pendingOutputBuffers.size(), 0,
3197 /*timestampIncreasing*/true, request.outputSurfaces,
3198 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003199 }
3200 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003201 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003202 }
3203
3204 // Then return all inflight buffers not returned by HAL
3205 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3206 mInterface->getInflightBufferKeys(&inflightKeys);
3207
3208 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3209 for (auto& pair : inflightKeys) {
3210 int32_t frameNumber = pair.first;
3211 int32_t streamId = pair.second;
3212 buffer_handle_t* buffer;
3213 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3214 if (res != OK) {
3215 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3216 __FUNCTION__, frameNumber, streamId);
3217 continue;
3218 }
3219
3220 camera3_stream_buffer_t streamBuffer;
3221 streamBuffer.buffer = buffer;
3222 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3223 streamBuffer.acquire_fence = -1;
3224 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003225
3226 // First check if the buffer belongs to deleted stream
3227 bool streamDeleted = false;
3228 for (auto& stream : mDeletedStreams) {
3229 if (streamId == stream->getId()) {
3230 streamDeleted = true;
3231 // Return buffer to deleted stream
3232 camera3_stream* halStream = stream->asHalStream();
3233 streamBuffer.stream = halStream;
3234 switch (halStream->stream_type) {
3235 case CAMERA3_STREAM_OUTPUT:
3236 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
3237 if (res != OK) {
3238 ALOGE("%s: Can't return output buffer for frame %d to"
3239 " stream %d: %s (%d)", __FUNCTION__,
3240 frameNumber, streamId, strerror(-res), res);
3241 }
3242 break;
3243 case CAMERA3_STREAM_INPUT:
3244 res = stream->returnInputBuffer(streamBuffer);
3245 if (res != OK) {
3246 ALOGE("%s: Can't return input buffer for frame %d to"
3247 " stream %d: %s (%d)", __FUNCTION__,
3248 frameNumber, streamId, strerror(-res), res);
3249 }
3250 break;
3251 default: // Bi-direcitonal stream is deprecated
3252 ALOGE("%s: stream %d has unknown stream type %d",
3253 __FUNCTION__, streamId, halStream->stream_type);
3254 break;
3255 }
3256 break;
3257 }
3258 }
3259 if (streamDeleted) {
3260 continue;
3261 }
3262
3263 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003264 if (streamId == inputStreamId) {
3265 streamBuffer.stream = mInputStream->asHalStream();
3266 res = mInputStream->returnInputBuffer(streamBuffer);
3267 if (res != OK) {
3268 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003269 " stream %d: %s (%d)", __FUNCTION__,
3270 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003271 }
3272 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003273 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3274 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003275 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3276 continue;
3277 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003278 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003279 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3280 }
3281 }
3282}
3283
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003284void Camera3Device::insertResultLocked(CaptureResult *result,
3285 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003286 if (result == nullptr) return;
3287
Emilian Peev71c73a22017-03-21 16:35:51 +00003288 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3289 result->mMetadata.getAndLock());
3290 set_camera_metadata_vendor_id(meta, mVendorTagId);
3291 result->mMetadata.unlock(meta);
3292
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003293 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3294 (int32_t*)&frameNumber, 1) != OK) {
3295 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3296 return;
3297 }
3298
3299 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3300 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3301 return;
3302 }
3303
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003304 // Valid result, insert into queue
3305 List<CaptureResult>::iterator queuedResult =
3306 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3307 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3308 ", burstId = %" PRId32, __FUNCTION__,
3309 queuedResult->mResultExtras.requestId,
3310 queuedResult->mResultExtras.frameNumber,
3311 queuedResult->mResultExtras.burstId);
3312
3313 mResultSignal.signal();
3314}
3315
3316
3317void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003318 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003319 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003320 Mutex::Autolock l(mOutputLock);
3321
3322 CaptureResult captureResult;
3323 captureResult.mResultExtras = resultExtras;
3324 captureResult.mMetadata = partialResult;
3325
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003326 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003327}
3328
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003329
3330void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3331 CaptureResultExtras &resultExtras,
3332 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003333 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003334 bool reprocess,
3335 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003336 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003337 if (pendingMetadata.isEmpty())
3338 return;
3339
3340 Mutex::Autolock l(mOutputLock);
3341
3342 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003343 if (reprocess) {
3344 if (frameNumber < mNextReprocessResultFrameNumber) {
3345 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003346 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003347 frameNumber, mNextReprocessResultFrameNumber);
3348 return;
3349 }
3350 mNextReprocessResultFrameNumber = frameNumber + 1;
3351 } else {
3352 if (frameNumber < mNextResultFrameNumber) {
3353 SET_ERR("Out-of-order capture result metadata submitted! "
3354 "(got frame number %d, expecting %d)",
3355 frameNumber, mNextResultFrameNumber);
3356 return;
3357 }
3358 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003359 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003360
3361 CaptureResult captureResult;
3362 captureResult.mResultExtras = resultExtras;
3363 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003364 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003365
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003366 // Append any previous partials to form a complete result
3367 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3368 captureResult.mMetadata.append(collectedPartialResult);
3369 }
3370
3371 captureResult.mMetadata.sort();
3372
3373 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003374 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3375 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003376 SET_ERR("No timestamp provided by HAL for frame %d!",
3377 frameNumber);
3378 return;
3379 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003380 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3381 camera_metadata_entry timestamp =
3382 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3383 if (timestamp.count == 0) {
3384 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3385 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3386 return;
3387 }
3388 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003389
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003390 // Fix up some result metadata to account for HAL-level distortion correction
3391 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3392 if (res != OK) {
3393 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3394 frameNumber, strerror(res), res);
3395 return;
3396 }
3397
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003398 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3399 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3400
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003401 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003402}
3403
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003404/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003405 * Camera HAL device callback methods
3406 */
3407
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003408void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003409 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003410
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003411 status_t res;
3412
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003413 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003414 if (result->result == NULL && result->num_output_buffers == 0 &&
3415 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003416 SET_ERR("No result data provided by HAL for frame %d",
3417 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003418 return;
3419 }
Zhijun He204e3292014-07-14 17:09:23 -07003420
Zhijun He204e3292014-07-14 17:09:23 -07003421 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003422 result->result != NULL &&
3423 result->partial_result != 1) {
3424 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3425 " if partial result is not supported",
3426 frameNumber, result->partial_result);
3427 return;
3428 }
3429
3430 bool isPartialResult = false;
3431 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003432 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003433
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003434 // Get shutter timestamp and resultExtras from list of in-flight requests,
3435 // where it was added by the shutter notification for this frame. If the
3436 // shutter timestamp isn't received yet, append the output buffers to the
3437 // in-flight request and they will be returned when the shutter timestamp
3438 // arrives. Update the in-flight status and remove the in-flight entry if
3439 // all result data and shutter timestamp have been received.
3440 nsecs_t shutterTimestamp = 0;
3441
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003442 {
3443 Mutex::Autolock l(mInFlightLock);
3444 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3445 if (idx == NAME_NOT_FOUND) {
3446 SET_ERR("Unknown frame number for capture result: %d",
3447 frameNumber);
3448 return;
3449 }
3450 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003451 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3452 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003453 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003454 __FUNCTION__, request.resultExtras.requestId,
3455 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003456 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003457 // Always update the partial count to the latest one if it's not 0
3458 // (buffers only). When framework aggregates adjacent partial results
3459 // into one, the latest partial count will be used.
3460 if (result->partial_result != 0)
3461 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003462
3463 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003464 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003465 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3466 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3467 " the range of [1, %d] when metadata is included in the result",
3468 frameNumber, result->partial_result, mNumPartialResults);
3469 return;
3470 }
3471 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003472 if (isPartialResult && result->num_physcam_metadata) {
3473 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3474 " physical camera result", frameNumber);
3475 return;
3476 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003477 if (isPartialResult) {
3478 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003479 }
3480
Shuzhen Wang4a472662017-02-26 23:29:04 -08003481 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003482 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003483 sendPartialCaptureResult(result->result, request.resultExtras,
3484 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003485 }
3486 }
3487
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003488 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003489 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003490
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003491 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003492 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003493 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3494 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3495 request.physicalCameraIds.size(), result->num_physcam_metadata);
3496 return;
3497 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003498 if (request.haveResultMetadata) {
3499 SET_ERR("Called multiple times with metadata for frame %d",
3500 frameNumber);
3501 return;
3502 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003503 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3504 String8 physicalId(result->physcam_ids[i]);
3505 std::set<String8>::iterator cameraIdIter =
3506 request.physicalCameraIds.find(physicalId);
3507 if (cameraIdIter != request.physicalCameraIds.end()) {
3508 request.physicalCameraIds.erase(cameraIdIter);
3509 } else {
3510 SET_ERR("Total result for frame %d has already returned for camera %s",
3511 frameNumber, physicalId.c_str());
3512 return;
3513 }
3514 }
Zhijun He204e3292014-07-14 17:09:23 -07003515 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003516 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003517 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003518 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003519 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003520 request.haveResultMetadata = true;
3521 }
3522
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003523 uint32_t numBuffersReturned = result->num_output_buffers;
3524 if (result->input_buffer != NULL) {
3525 if (hasInputBufferInRequest) {
3526 numBuffersReturned += 1;
3527 } else {
3528 ALOGW("%s: Input buffer should be NULL if there is no input"
3529 " buffer sent in the request",
3530 __FUNCTION__);
3531 }
3532 }
3533 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003534 if (request.numBuffersLeft < 0) {
3535 SET_ERR("Too many buffers returned for frame %d",
3536 frameNumber);
3537 return;
3538 }
3539
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003540 camera_metadata_ro_entry_t entry;
3541 res = find_camera_metadata_ro_entry(result->result,
3542 ANDROID_SENSOR_TIMESTAMP, &entry);
3543 if (res == OK && entry.count == 1) {
3544 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003545 }
3546
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003547 // If shutter event isn't received yet, append the output buffers to
3548 // the in-flight request. Otherwise, return the output buffers to
3549 // streams.
3550 if (shutterTimestamp == 0) {
3551 request.pendingOutputBuffers.appendArray(result->output_buffers,
3552 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003553 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003554 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003555 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003556 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3557 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003558 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003559
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003560 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003561 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3562 CameraMetadata physicalMetadata;
3563 physicalMetadata.append(result->physcam_metadata[i]);
3564 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3565 physicalMetadata});
3566 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003567 if (shutterTimestamp == 0) {
3568 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003569 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003570 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003571 CameraMetadata metadata;
3572 metadata = result->result;
3573 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003574 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003575 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003576 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003577 }
3578
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003579 removeInFlightRequestIfReadyLocked(idx);
3580 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003581
Zhijun Hef0d962a2014-06-30 10:24:11 -07003582 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003583 if (hasInputBufferInRequest) {
3584 Camera3Stream *stream =
3585 Camera3Stream::cast(result->input_buffer->stream);
3586 res = stream->returnInputBuffer(*(result->input_buffer));
3587 // Note: stream may be deallocated at this point, if this buffer was the
3588 // last reference to it.
3589 if (res != OK) {
3590 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3591 " its stream:%s (%d)", __FUNCTION__,
3592 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003593 }
3594 } else {
3595 ALOGW("%s: Input buffer should be NULL if there is no input"
3596 " buffer sent in the request, skipping input buffer return.",
3597 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003598 }
3599 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003600}
3601
3602void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003603 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003604 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003605 {
3606 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003607 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003608 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003609
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003610 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003611 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003612 return;
3613 }
3614
3615 switch (msg->type) {
3616 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003617 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003618 break;
3619 }
3620 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003621 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003622 break;
3623 }
3624 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003625 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003626 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003627 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003628}
3629
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003630void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003631 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003632 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003633 // Map camera HAL error codes to ICameraDeviceCallback error codes
3634 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003635 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003636 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003637 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003638 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003639 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003640 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003641 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003642 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003643 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003644 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003645 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003646 };
3647
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003648 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003649 ((msg.error_code >= 0) &&
3650 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3651 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003652 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003653
3654 int streamId = 0;
3655 if (msg.error_stream != NULL) {
3656 Camera3Stream *stream =
3657 Camera3Stream::cast(msg.error_stream);
3658 streamId = stream->getId();
3659 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003660 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3661 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003662 streamId, msg.error_code);
3663
3664 CaptureResultExtras resultExtras;
3665 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003666 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003667 // SET_ERR calls notifyError
3668 SET_ERR("Camera HAL reported serious device error");
3669 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003670 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3671 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3672 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003673 {
3674 Mutex::Autolock l(mInFlightLock);
3675 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3676 if (idx >= 0) {
3677 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3678 r.requestStatus = msg.error_code;
3679 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003680 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3681 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3682 errorCode) {
3683 r.skipResultMetadata = true;
3684 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003685 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3686 errorCode) {
3687 // In case of missing result check whether the buffers
3688 // returned. If they returned, then remove inflight
3689 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003690 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3691 // otherwise we are depending on HAL to send the buffers back after
3692 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003693 removeInFlightRequestIfReadyLocked(idx);
3694 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003695 } else {
3696 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003697 ALOGE("Camera %s: %s: cannot find in-flight request on "
3698 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003699 resultExtras.frameNumber);
3700 }
3701 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003702 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003703 if (listener != NULL) {
3704 listener->notifyError(errorCode, resultExtras);
3705 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003706 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003707 }
3708 break;
3709 default:
3710 // SET_ERR calls notifyError
3711 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3712 break;
3713 }
3714}
3715
3716void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003717 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003718 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003719 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003720
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003721 // Set timestamp for the request in the in-flight tracking
3722 // and get the request ID to send upstream
3723 {
3724 Mutex::Autolock l(mInFlightLock);
3725 idx = mInFlightMap.indexOfKey(msg.frame_number);
3726 if (idx >= 0) {
3727 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003728
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003729 // Verify ordering of shutter notifications
3730 {
3731 Mutex::Autolock l(mOutputLock);
3732 // TODO: need to track errors for tighter bounds on expected frame number.
3733 if (r.hasInputBuffer) {
3734 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3735 SET_ERR("Shutter notification out-of-order. Expected "
3736 "notification for frame %d, got frame %d",
3737 mNextReprocessShutterFrameNumber, msg.frame_number);
3738 return;
3739 }
3740 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3741 } else {
3742 if (msg.frame_number < mNextShutterFrameNumber) {
3743 SET_ERR("Shutter notification out-of-order. Expected "
3744 "notification for frame %d, got frame %d",
3745 mNextShutterFrameNumber, msg.frame_number);
3746 return;
3747 }
3748 mNextShutterFrameNumber = msg.frame_number + 1;
3749 }
3750 }
3751
Shuzhen Wang4a472662017-02-26 23:29:04 -08003752 r.shutterTimestamp = msg.timestamp;
3753 if (r.hasCallback) {
3754 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003755 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003756 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003757 // Call listener, if any
3758 if (listener != NULL) {
3759 listener->notifyShutter(r.resultExtras, msg.timestamp);
3760 }
3761 // send pending result and buffers
3762 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3763 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003764 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003765 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003766 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003767 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003768 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3769 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003770 r.pendingOutputBuffers.clear();
3771
3772 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003773 }
3774 }
3775 if (idx < 0) {
3776 SET_ERR("Shutter notification for non-existent frame number %d",
3777 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003778 }
3779}
3780
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003781CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003782 ALOGV("%s", __FUNCTION__);
3783
Igor Murashkin1e479c02013-09-06 16:55:14 -07003784 CameraMetadata retVal;
3785
3786 if (mRequestThread != NULL) {
3787 retVal = mRequestThread->getLatestRequest();
3788 }
3789
Igor Murashkin1e479c02013-09-06 16:55:14 -07003790 return retVal;
3791}
3792
Jianing Weicb0652e2014-03-12 18:29:36 -07003793
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003794void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3795 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3796 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3797}
3798
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003799/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003800 * HalInterface inner class methods
3801 */
3802
Yifan Hongf79b5542017-04-11 14:44:25 -07003803Camera3Device::HalInterface::HalInterface(
3804 sp<ICameraDeviceSession> &session,
3805 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003806 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003807 mRequestMetadataQueue(queue) {
3808 // Check with hardware service manager if we can downcast these interfaces
3809 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003810 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3811 if (castResult_3_5.isOk()) {
3812 mHidlSession_3_5 = castResult_3_5;
3813 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003814 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3815 if (castResult_3_4.isOk()) {
3816 mHidlSession_3_4 = castResult_3_4;
3817 }
3818 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3819 if (castResult_3_3.isOk()) {
3820 mHidlSession_3_3 = castResult_3_3;
3821 }
3822}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003823
Emilian Peev31abd0a2017-05-11 18:37:46 +01003824Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003825
3826Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003827 mHidlSession(other.mHidlSession),
3828 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003829
3830bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003831 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003832}
3833
3834void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003835 mHidlSession_3_4.clear();
3836 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003837 mHidlSession.clear();
3838}
3839
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003840bool Camera3Device::HalInterface::supportBatchRequest() {
3841 return mHidlSession != nullptr;
3842}
3843
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003844status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3845 camera3_request_template_t templateId,
3846 /*out*/ camera_metadata_t **requestTemplate) {
3847 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3848 if (!valid()) return INVALID_OPERATION;
3849 status_t res = OK;
3850
Emilian Peev31abd0a2017-05-11 18:37:46 +01003851 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003852
3853 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003854 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003855 status = s;
3856 if (status == common::V1_0::Status::OK) {
3857 const camera_metadata *r =
3858 reinterpret_cast<const camera_metadata_t*>(request.data());
3859 size_t expectedSize = request.size();
3860 int ret = validate_camera_metadata_structure(r, &expectedSize);
3861 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3862 *requestTemplate = clone_camera_metadata(r);
3863 if (*requestTemplate == nullptr) {
3864 ALOGE("%s: Unable to clone camera metadata received from HAL",
3865 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003866 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003867 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003868 } else {
3869 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3870 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003871 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003872 }
3873 };
3874 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003875 RequestTemplate id;
3876 switch (templateId) {
3877 case CAMERA3_TEMPLATE_PREVIEW:
3878 id = RequestTemplate::PREVIEW;
3879 break;
3880 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3881 id = RequestTemplate::STILL_CAPTURE;
3882 break;
3883 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3884 id = RequestTemplate::VIDEO_RECORD;
3885 break;
3886 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3887 id = RequestTemplate::VIDEO_SNAPSHOT;
3888 break;
3889 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3890 id = RequestTemplate::ZERO_SHUTTER_LAG;
3891 break;
3892 case CAMERA3_TEMPLATE_MANUAL:
3893 id = RequestTemplate::MANUAL;
3894 break;
3895 default:
3896 // Unknown template ID, or this HAL is too old to support it
3897 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003898 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003899 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003900
Emilian Peev31abd0a2017-05-11 18:37:46 +01003901 if (!err.isOk()) {
3902 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3903 res = DEAD_OBJECT;
3904 } else {
3905 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003906 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003907
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003908 return res;
3909}
3910
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003911status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003912 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003913 ATRACE_NAME("CameraHal::configureStreams");
3914 if (!valid()) return INVALID_OPERATION;
3915 status_t res = OK;
3916
Emilian Peev31abd0a2017-05-11 18:37:46 +01003917 // Convert stream config to HIDL
3918 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003919 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3920 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3921 requestedConfiguration3_2.streams.resize(config->num_streams);
3922 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003923 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003924 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3925 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003926 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003927
Emilian Peev31abd0a2017-05-11 18:37:46 +01003928 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3929 cam3stream->setBufferFreedListener(this);
3930 int streamId = cam3stream->getId();
3931 StreamType streamType;
3932 switch (src->stream_type) {
3933 case CAMERA3_STREAM_OUTPUT:
3934 streamType = StreamType::OUTPUT;
3935 break;
3936 case CAMERA3_STREAM_INPUT:
3937 streamType = StreamType::INPUT;
3938 break;
3939 default:
3940 ALOGE("%s: Stream %d: Unsupported stream type %d",
3941 __FUNCTION__, streamId, config->streams[i]->stream_type);
3942 return BAD_VALUE;
3943 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003944 dst3_2.id = streamId;
3945 dst3_2.streamType = streamType;
3946 dst3_2.width = src->width;
3947 dst3_2.height = src->height;
3948 dst3_2.format = mapToPixelFormat(src->format);
3949 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3950 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3951 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3952 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003953 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003954 if (src->physical_camera_id != nullptr) {
3955 dst3_4.physicalCameraId = src->physical_camera_id;
3956 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003957
3958 activeStreams.insert(streamId);
3959 // Create Buffer ID map if necessary
3960 if (mBufferIdMaps.count(streamId) == 0) {
3961 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3962 }
3963 }
3964 // remove BufferIdMap for deleted streams
3965 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3966 int streamId = it->first;
3967 bool active = activeStreams.count(streamId) > 0;
3968 if (!active) {
3969 it = mBufferIdMaps.erase(it);
3970 } else {
3971 ++it;
3972 }
3973 }
3974
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003975 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003976 res = mapToStreamConfigurationMode(
3977 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003978 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003979 if (res != OK) {
3980 return res;
3981 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003982 requestedConfiguration3_2.operationMode = operationMode;
3983 requestedConfiguration3_4.operationMode = operationMode;
3984 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003985 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3986 get_camera_metadata_size(sessionParams));
3987
Emilian Peev31abd0a2017-05-11 18:37:46 +01003988 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003989 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003990 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003991 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003992
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003993 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003994 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3995 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003996 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003997 };
3998
3999 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4000 (hardware::Return<void>& err) -> status_t {
4001 if (!err.isOk()) {
4002 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4003 return DEAD_OBJECT;
4004 }
4005 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4006 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4007 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4008 }
4009 return OK;
4010 };
4011
4012 // See if we have v3.4 or v3.3 HAL
4013 if (mHidlSession_3_5 != nullptr) {
4014 ALOGV("%s: v3.5 device found", __FUNCTION__);
4015 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4016 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4017 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4018 auto err = mHidlSession_3_5->configureStreams_3_5(
4019 requestedConfiguration3_5, configStream34Cb);
4020 res = postprocConfigStream34(err);
4021 if (res != OK) {
4022 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004023 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004024 } else if (mHidlSession_3_4 != nullptr) {
4025 // We do; use v3.4 for the call
4026 ALOGV("%s: v3.4 device found", __FUNCTION__);
4027 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
4028 auto err = mHidlSession_3_4->configureStreams_3_4(
4029 requestedConfiguration3_4, configStream34Cb);
4030 res = postprocConfigStream34(err);
4031 if (res != OK) {
4032 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004033 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004034 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004035 // We do; use v3.3 for the call
4036 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004037 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004038 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004039 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004040 finalConfiguration = halConfiguration;
4041 status = s;
4042 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004043 if (!err.isOk()) {
4044 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4045 return DEAD_OBJECT;
4046 }
4047 } else {
4048 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4049 ALOGV("%s: v3.2 device found", __FUNCTION__);
4050 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004051 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004052 [&status, &finalConfiguration_3_2]
4053 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4054 finalConfiguration_3_2 = halConfiguration;
4055 status = s;
4056 });
4057 if (!err.isOk()) {
4058 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4059 return DEAD_OBJECT;
4060 }
4061 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4062 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4063 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4064 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004065 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004066 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004067 }
4068
4069 if (status != common::V1_0::Status::OK ) {
4070 return CameraProviderManager::mapToStatusT(status);
4071 }
4072
4073 // And convert output stream configuration from HIDL
4074
4075 for (size_t i = 0; i < config->num_streams; i++) {
4076 camera3_stream_t *dst = config->streams[i];
4077 int streamId = Camera3Stream::cast(dst)->getId();
4078
4079 // Start scan at i, with the assumption that the stream order matches
4080 size_t realIdx = i;
4081 bool found = false;
4082 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004083 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004084 found = true;
4085 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004086 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004087 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4088 }
4089 if (!found) {
4090 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4091 __FUNCTION__, streamId);
4092 return INVALID_OPERATION;
4093 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004094 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004095
Emilian Peev710c1422017-08-30 11:19:38 +01004096 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4097 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004098 dstStream->setDataSpaceOverride(false);
4099 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4100 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4101
Emilian Peev31abd0a2017-05-11 18:37:46 +01004102 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4103 if (dst->format != overrideFormat) {
4104 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4105 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004106 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004107 if (dst->data_space != overrideDataSpace) {
4108 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4109 streamId, dst->format);
4110 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004111 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004112 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004113 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4114
Emilian Peev31abd0a2017-05-11 18:37:46 +01004115 // Override allowed with IMPLEMENTATION_DEFINED
4116 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004117 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004118 }
4119
Emilian Peev31abd0a2017-05-11 18:37:46 +01004120 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004121 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004122 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004123 __FUNCTION__, streamId);
4124 return INVALID_OPERATION;
4125 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004126 dstStream->setUsage(
4127 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004128 } else {
4129 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004130 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004131 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4132 __FUNCTION__, streamId);
4133 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004134 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004135 dstStream->setUsage(
4136 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004137 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004138 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004139 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004140
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004141 return res;
4142}
4143
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004144void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
4145 /*out*/device::V3_2::CaptureRequest* captureRequest,
4146 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004147 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004148 if (captureRequest == nullptr || handlesCreated == nullptr) {
4149 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4150 __FUNCTION__, captureRequest, handlesCreated);
4151 return;
4152 }
4153
4154 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004155
4156 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004157
4158 {
4159 std::lock_guard<std::mutex> lock(mInflightLock);
4160 if (request->input_buffer != nullptr) {
4161 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4162 buffer_handle_t buf = *(request->input_buffer->buffer);
4163 auto pair = getBufferId(buf, streamId);
4164 bool isNewBuffer = pair.first;
4165 uint64_t bufferId = pair.second;
4166 captureRequest->inputBuffer.streamId = streamId;
4167 captureRequest->inputBuffer.bufferId = bufferId;
4168 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4169 captureRequest->inputBuffer.status = BufferStatus::OK;
4170 native_handle_t *acquireFence = nullptr;
4171 if (request->input_buffer->acquire_fence != -1) {
4172 acquireFence = native_handle_create(1,0);
4173 acquireFence->data[0] = request->input_buffer->acquire_fence;
4174 handlesCreated->push_back(acquireFence);
4175 }
4176 captureRequest->inputBuffer.acquireFence = acquireFence;
4177 captureRequest->inputBuffer.releaseFence = nullptr;
4178
4179 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4180 request->input_buffer->buffer,
4181 request->input_buffer->acquire_fence);
4182 } else {
4183 captureRequest->inputBuffer.streamId = -1;
4184 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4185 }
4186
4187 captureRequest->outputBuffers.resize(request->num_output_buffers);
4188 for (size_t i = 0; i < request->num_output_buffers; i++) {
4189 const camera3_stream_buffer_t *src = request->output_buffers + i;
4190 StreamBuffer &dst = captureRequest->outputBuffers[i];
4191 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
4192 buffer_handle_t buf = *(src->buffer);
4193 auto pair = getBufferId(buf, streamId);
4194 bool isNewBuffer = pair.first;
4195 dst.streamId = streamId;
4196 dst.bufferId = pair.second;
4197 dst.buffer = isNewBuffer ? buf : nullptr;
4198 dst.status = BufferStatus::OK;
4199 native_handle_t *acquireFence = nullptr;
4200 if (src->acquire_fence != -1) {
4201 acquireFence = native_handle_create(1,0);
4202 acquireFence->data[0] = src->acquire_fence;
4203 handlesCreated->push_back(acquireFence);
4204 }
4205 dst.acquireFence = acquireFence;
4206 dst.releaseFence = nullptr;
4207
4208 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4209 src->buffer, src->acquire_fence);
4210 }
4211 }
4212}
4213
4214status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4215 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4216 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4217 if (!valid()) return INVALID_OPERATION;
4218
Emilian Peevaebbe412018-01-15 13:53:24 +00004219 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4220 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4221 if (castResult_3_4.isOk()) {
4222 hidlSession_3_4 = castResult_3_4;
4223 }
4224
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004225 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004226 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004227 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004228 if (hidlSession_3_4 != nullptr) {
4229 captureRequests_3_4.resize(batchSize);
4230 } else {
4231 captureRequests.resize(batchSize);
4232 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004233 std::vector<native_handle_t*> handlesCreated;
4234
4235 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004236 if (hidlSession_3_4 != nullptr) {
4237 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
4238 /*out*/&handlesCreated);
4239 } else {
4240 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
4241 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004242 }
4243
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004244 std::vector<device::V3_2::BufferCache> cachesToRemove;
4245 {
4246 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4247 for (auto& pair : mFreedBuffers) {
4248 // The stream might have been removed since onBufferFreed
4249 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4250 cachesToRemove.push_back({pair.first, pair.second});
4251 }
4252 }
4253 mFreedBuffers.clear();
4254 }
4255
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004256 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4257 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004258
4259 // Write metadata to FMQ.
4260 for (size_t i = 0; i < batchSize; i++) {
4261 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004262 device::V3_2::CaptureRequest* captureRequest;
4263 if (hidlSession_3_4 != nullptr) {
4264 captureRequest = &captureRequests_3_4[i].v3_2;
4265 } else {
4266 captureRequest = &captureRequests[i];
4267 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004268
4269 if (request->settings != nullptr) {
4270 size_t settingsSize = get_camera_metadata_size(request->settings);
4271 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4272 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4273 captureRequest->settings.resize(0);
4274 captureRequest->fmqSettingsSize = settingsSize;
4275 } else {
4276 if (mRequestMetadataQueue != nullptr) {
4277 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4278 }
4279 captureRequest->settings.setToExternal(
4280 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4281 get_camera_metadata_size(request->settings));
4282 captureRequest->fmqSettingsSize = 0u;
4283 }
4284 } else {
4285 // A null request settings maps to a size-0 CameraMetadata
4286 captureRequest->settings.resize(0);
4287 captureRequest->fmqSettingsSize = 0u;
4288 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004289
4290 if (hidlSession_3_4 != nullptr) {
4291 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4292 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004293 if (request->physcam_settings != nullptr) {
4294 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4295 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4296 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4297 settingsSize)) {
4298 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4299 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4300 settingsSize;
4301 } else {
4302 if (mRequestMetadataQueue != nullptr) {
4303 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4304 }
4305 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4306 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4307 request->physcam_settings[j])),
4308 get_camera_metadata_size(request->physcam_settings[j]));
4309 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004310 }
Emilian Peev00420d22018-02-05 21:33:13 +00004311 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004312 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004313 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004314 }
4315 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4316 request->physcam_id[j];
4317 }
4318 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004319 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004320
4321 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004322 auto resultCallback =
4323 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4324 status = s;
4325 *numRequestProcessed = n;
4326 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004327 if (hidlSession_3_4 != nullptr) {
4328 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004329 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004330 } else {
4331 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004332 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004333 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004334 if (!err.isOk()) {
4335 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4336 return DEAD_OBJECT;
4337 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004338 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4339 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4340 __FUNCTION__, *numRequestProcessed, batchSize);
4341 status = common::V1_0::Status::INTERNAL_ERROR;
4342 }
4343
4344 for (auto& handle : handlesCreated) {
4345 native_handle_delete(handle);
4346 }
4347 return CameraProviderManager::mapToStatusT(status);
4348}
4349
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004350status_t Camera3Device::HalInterface::processCaptureRequest(
4351 camera3_capture_request_t *request) {
4352 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004353 if (!valid()) return INVALID_OPERATION;
4354 status_t res = OK;
4355
Emilian Peev31abd0a2017-05-11 18:37:46 +01004356 uint32_t numRequestProcessed = 0;
4357 std::vector<camera3_capture_request_t*> requests(1);
4358 requests[0] = request;
4359 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4360
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004361 return res;
4362}
4363
4364status_t Camera3Device::HalInterface::flush() {
4365 ATRACE_NAME("CameraHal::flush");
4366 if (!valid()) return INVALID_OPERATION;
4367 status_t res = OK;
4368
Emilian Peev31abd0a2017-05-11 18:37:46 +01004369 auto err = mHidlSession->flush();
4370 if (!err.isOk()) {
4371 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4372 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004373 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004374 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004375 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004376
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004377 return res;
4378}
4379
Emilian Peev31abd0a2017-05-11 18:37:46 +01004380status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004381 ATRACE_NAME("CameraHal::dump");
4382 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004383
Emilian Peev31abd0a2017-05-11 18:37:46 +01004384 // Handled by CameraProviderManager::dump
4385
4386 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004387}
4388
4389status_t Camera3Device::HalInterface::close() {
4390 ATRACE_NAME("CameraHal::close()");
4391 if (!valid()) return INVALID_OPERATION;
4392 status_t res = OK;
4393
Emilian Peev31abd0a2017-05-11 18:37:46 +01004394 auto err = mHidlSession->close();
4395 // Interface will be dead shortly anyway, so don't log errors
4396 if (!err.isOk()) {
4397 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004398 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004399
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004400 return res;
4401}
4402
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004403void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4404 ATRACE_NAME("CameraHal::signalPipelineDrain");
4405 if (!valid() || mHidlSession_3_5 == nullptr) {
4406 ALOGE("%s called on invalid camera!", __FUNCTION__);
4407 return;
4408 }
4409
4410 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter);
4411 if (!err.isOk()) {
4412 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4413 return;
4414 }
4415}
4416
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004417void Camera3Device::HalInterface::getInflightBufferKeys(
4418 std::vector<std::pair<int32_t, int32_t>>* out) {
4419 std::lock_guard<std::mutex> lock(mInflightLock);
4420 out->clear();
4421 out->reserve(mInflightBufferMap.size());
4422 for (auto& pair : mInflightBufferMap) {
4423 uint64_t key = pair.first;
4424 int32_t streamId = key & 0xFFFFFFFF;
4425 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4426 out->push_back(std::make_pair(frameNumber, streamId));
4427 }
4428 return;
4429}
4430
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004431status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004432 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004433 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004434 auto pair = std::make_pair(buffer, acquireFence);
4435 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004436 return OK;
4437}
4438
4439status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004440 int32_t frameNumber, int32_t streamId,
4441 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004442 std::lock_guard<std::mutex> lock(mInflightLock);
4443
4444 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4445 auto it = mInflightBufferMap.find(key);
4446 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004447 auto pair = it->second;
4448 *buffer = pair.first;
4449 int acquireFence = pair.second;
4450 if (acquireFence > 0) {
4451 ::close(acquireFence);
4452 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004453 mInflightBufferMap.erase(it);
4454 return OK;
4455}
4456
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004457status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4458 uint64_t bufferId, buffer_handle_t* buf) {
4459 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4460 auto pair = mRequestedBuffers.insert({bufferId, buf});
4461 if (!pair.second) {
4462 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4463 __FUNCTION__, bufferId);
4464 return BAD_VALUE;
4465 }
4466 return OK;
4467}
4468
4469// Find and pop a buffer_handle_t based on bufferId
4470status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4471 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4472 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4473 auto it = mRequestedBuffers.find(bufferId);
4474 if (it == mRequestedBuffers.end()) {
4475 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4476 __FUNCTION__, bufferId);
4477 return BAD_VALUE;
4478 }
4479 *buffer = it->second;
4480 mRequestedBuffers.erase(it);
4481 return OK;
4482}
4483
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004484std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4485 const buffer_handle_t& buf, int streamId) {
4486 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4487
4488 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4489 auto it = bIdMap.find(buf);
4490 if (it == bIdMap.end()) {
4491 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004492 ALOGV("stream %d now have %zu buffer caches, buf %p",
4493 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004494 return std::make_pair(true, mNextBufferId - 1);
4495 } else {
4496 return std::make_pair(false, it->second);
4497 }
4498}
4499
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004500void Camera3Device::HalInterface::onBufferFreed(
4501 int streamId, const native_handle_t* handle) {
4502 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4503 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4504 auto mapIt = mBufferIdMaps.find(streamId);
4505 if (mapIt == mBufferIdMaps.end()) {
4506 // streamId might be from a deleted stream here
4507 ALOGI("%s: stream %d has been removed",
4508 __FUNCTION__, streamId);
4509 return;
4510 }
4511 BufferIdMap& bIdMap = mapIt->second;
4512 auto it = bIdMap.find(handle);
4513 if (it == bIdMap.end()) {
4514 ALOGW("%s: cannot find buffer %p in stream %d",
4515 __FUNCTION__, handle, streamId);
4516 return;
4517 } else {
4518 bufferId = it->second;
4519 bIdMap.erase(it);
4520 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4521 __FUNCTION__, streamId, bIdMap.size(), handle);
4522 }
4523 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4524}
4525
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004526/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004527 * RequestThread inner class methods
4528 */
4529
4530Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004531 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004532 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4533 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004534 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004535 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004536 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004537 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004538 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004539 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004540 mReconfigured(false),
4541 mDoPause(false),
4542 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004543 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004544 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004545 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004546 mCurrentAfTriggerId(0),
4547 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004548 mRepeatingLastFrameNumber(
4549 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004550 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004551 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004552 mRequestLatency(kRequestLatencyBinSize),
4553 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004554 mLatestSessionParams(sessionParamKeys.size()),
4555 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004556 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004557}
4558
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004559Camera3Device::RequestThread::~RequestThread() {}
4560
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004561void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004562 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004563 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004564 Mutex::Autolock l(mRequestLock);
4565 mListener = listener;
4566}
4567
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004568void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4569 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004570 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004571 Mutex::Autolock l(mRequestLock);
4572 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004573 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004574 // Prepare video stream for high speed recording.
4575 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004576 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004577}
4578
Jianing Wei90e59c92014-03-12 18:29:36 -07004579status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004580 List<sp<CaptureRequest> > &requests,
4581 /*out*/
4582 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004583 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004584 Mutex::Autolock l(mRequestLock);
4585 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4586 ++it) {
4587 mRequestQueue.push_back(*it);
4588 }
4589
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004590 if (lastFrameNumber != NULL) {
4591 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4592 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4593 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4594 *lastFrameNumber);
4595 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004596
Jianing Wei90e59c92014-03-12 18:29:36 -07004597 unpauseForNewRequests();
4598
4599 return OK;
4600}
4601
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004602
4603status_t Camera3Device::RequestThread::queueTrigger(
4604 RequestTrigger trigger[],
4605 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004606 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004607 Mutex::Autolock l(mTriggerMutex);
4608 status_t ret;
4609
4610 for (size_t i = 0; i < count; ++i) {
4611 ret = queueTriggerLocked(trigger[i]);
4612
4613 if (ret != OK) {
4614 return ret;
4615 }
4616 }
4617
4618 return OK;
4619}
4620
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004621const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4622 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004623 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004624 if (d != nullptr) return d->mId;
4625 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004626}
4627
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004628status_t Camera3Device::RequestThread::queueTriggerLocked(
4629 RequestTrigger trigger) {
4630
4631 uint32_t tag = trigger.metadataTag;
4632 ssize_t index = mTriggerMap.indexOfKey(tag);
4633
4634 switch (trigger.getTagType()) {
4635 case TYPE_BYTE:
4636 // fall-through
4637 case TYPE_INT32:
4638 break;
4639 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004640 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4641 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004642 return INVALID_OPERATION;
4643 }
4644
4645 /**
4646 * Collect only the latest trigger, since we only have 1 field
4647 * in the request settings per trigger tag, and can't send more than 1
4648 * trigger per request.
4649 */
4650 if (index != NAME_NOT_FOUND) {
4651 mTriggerMap.editValueAt(index) = trigger;
4652 } else {
4653 mTriggerMap.add(tag, trigger);
4654 }
4655
4656 return OK;
4657}
4658
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004659status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004660 const RequestList &requests,
4661 /*out*/
4662 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004663 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004664 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004665 if (lastFrameNumber != NULL) {
4666 *lastFrameNumber = mRepeatingLastFrameNumber;
4667 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004668 mRepeatingRequests.clear();
4669 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4670 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004671
4672 unpauseForNewRequests();
4673
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004674 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004675 return OK;
4676}
4677
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004678bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004679 if (mRepeatingRequests.empty()) {
4680 return false;
4681 }
4682 int32_t requestId = requestIn->mResultExtras.requestId;
4683 const RequestList &repeatRequests = mRepeatingRequests;
4684 // All repeating requests are guaranteed to have same id so only check first quest
4685 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4686 return (firstRequest->mResultExtras.requestId == requestId);
4687}
4688
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004689status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004690 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004691 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004692 return clearRepeatingRequestsLocked(lastFrameNumber);
4693
4694}
4695
4696status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004697 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004698 if (lastFrameNumber != NULL) {
4699 *lastFrameNumber = mRepeatingLastFrameNumber;
4700 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004701 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004702 return OK;
4703}
4704
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004705status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004706 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004707 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004708 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004709 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004710
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004711 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004712
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004713 // Send errors for all requests pending in the request queue, including
4714 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004715 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004716 if (listener != NULL) {
4717 for (RequestList::iterator it = mRequestQueue.begin();
4718 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004719 // Abort the input buffers for reprocess requests.
4720 if ((*it)->mInputStream != NULL) {
4721 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004722 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4723 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004724 if (res != OK) {
4725 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4726 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4727 } else {
4728 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4729 if (res != OK) {
4730 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4731 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4732 }
4733 }
4734 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004735 // Set the frame number this request would have had, if it
4736 // had been submitted; this frame number will not be reused.
4737 // The requestId and burstId fields were set when the request was
4738 // submitted originally (in convertMetadataListToRequestListLocked)
4739 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004740 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004741 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004742 }
4743 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004744 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004745
4746 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004747 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004748 if (lastFrameNumber != NULL) {
4749 *lastFrameNumber = mRepeatingLastFrameNumber;
4750 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004751 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004752 return OK;
4753}
4754
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004755status_t Camera3Device::RequestThread::flush() {
4756 ATRACE_CALL();
4757 Mutex::Autolock l(mFlushLock);
4758
Emilian Peev08dd2452017-04-06 16:55:14 +01004759 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004760}
4761
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004762void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004763 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004764 Mutex::Autolock l(mPauseLock);
4765 mDoPause = paused;
4766 mDoPauseSignal.signal();
4767}
4768
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004769status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4770 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004771 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004772 Mutex::Autolock l(mLatestRequestMutex);
4773 status_t res;
4774 while (mLatestRequestId != requestId) {
4775 nsecs_t startTime = systemTime();
4776
4777 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4778 if (res != OK) return res;
4779
4780 timeout -= (systemTime() - startTime);
4781 }
4782
4783 return OK;
4784}
4785
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004786void Camera3Device::RequestThread::requestExit() {
4787 // Call parent to set up shutdown
4788 Thread::requestExit();
4789 // The exit from any possible waits
4790 mDoPauseSignal.signal();
4791 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004792
4793 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4794 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004795}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004796
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004797void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004798 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004799 bool surfaceAbandoned = false;
4800 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004801 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004802 {
4803 Mutex::Autolock l(mRequestLock);
4804 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4805 // repeating requests.
4806 for (const auto& request : mRepeatingRequests) {
4807 for (const auto& s : request->mOutputStreams) {
4808 if (s->isAbandoned()) {
4809 surfaceAbandoned = true;
4810 clearRepeatingRequestsLocked(&lastFrameNumber);
4811 break;
4812 }
4813 }
4814 if (surfaceAbandoned) {
4815 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004816 }
4817 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004818 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004819 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004820
4821 if (listener != NULL && surfaceAbandoned) {
4822 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004823 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004824}
4825
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004826bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004827 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004828 status_t res;
4829 size_t batchSize = mNextRequests.size();
4830 std::vector<camera3_capture_request_t*> requests(batchSize);
4831 uint32_t numRequestProcessed = 0;
4832 for (size_t i = 0; i < batchSize; i++) {
4833 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004834 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004835 }
4836
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004837 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4838
4839 bool triggerRemoveFailed = false;
4840 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4841 for (size_t i = 0; i < numRequestProcessed; i++) {
4842 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4843 nextRequest.submitted = true;
4844
4845
4846 // Update the latest request sent to HAL
4847 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4848 Mutex::Autolock al(mLatestRequestMutex);
4849
4850 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4851 mLatestRequest.acquire(cloned);
4852
4853 sp<Camera3Device> parent = mParent.promote();
4854 if (parent != NULL) {
4855 parent->monitorMetadata(TagMonitor::REQUEST,
4856 nextRequest.halRequest.frame_number,
4857 0, mLatestRequest);
4858 }
4859 }
4860
4861 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004862 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4863 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004864 }
4865
Emilian Peevaebbe412018-01-15 13:53:24 +00004866 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4867
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004868 if (!triggerRemoveFailed) {
4869 // Remove any previously queued triggers (after unlock)
4870 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4871 if (removeTriggerRes != OK) {
4872 triggerRemoveFailed = true;
4873 triggerFailedRequest = nextRequest;
4874 }
4875 }
4876 }
4877
4878 if (triggerRemoveFailed) {
4879 SET_ERR("RequestThread: Unable to remove triggers "
4880 "(capture request %d, HAL device: %s (%d)",
4881 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4882 cleanUpFailedRequests(/*sendRequestError*/ false);
4883 return false;
4884 }
4885
4886 if (res != OK) {
4887 // Should only get a failure here for malformed requests or device-level
4888 // errors, so consider all errors fatal. Bad metadata failures should
4889 // come through notify.
4890 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4891 mNextRequests[numRequestProcessed].halRequest.frame_number,
4892 strerror(-res), res);
4893 cleanUpFailedRequests(/*sendRequestError*/ false);
4894 return false;
4895 }
4896 return true;
4897}
4898
4899bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4900 status_t res;
4901
4902 for (auto& nextRequest : mNextRequests) {
4903 // Submit request and block until ready for next one
4904 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4905 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4906
4907 if (res != OK) {
4908 // Should only get a failure here for malformed requests or device-level
4909 // errors, so consider all errors fatal. Bad metadata failures should
4910 // come through notify.
4911 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4912 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4913 res);
4914 cleanUpFailedRequests(/*sendRequestError*/ false);
4915 return false;
4916 }
4917
4918 // Mark that the request has be submitted successfully.
4919 nextRequest.submitted = true;
4920
4921 // Update the latest request sent to HAL
4922 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4923 Mutex::Autolock al(mLatestRequestMutex);
4924
4925 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4926 mLatestRequest.acquire(cloned);
4927
4928 sp<Camera3Device> parent = mParent.promote();
4929 if (parent != NULL) {
4930 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4931 0, mLatestRequest);
4932 }
4933 }
4934
4935 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004936 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4937 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004938 }
4939
Emilian Peevaebbe412018-01-15 13:53:24 +00004940 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4941
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004942 // Remove any previously queued triggers (after unlock)
4943 res = removeTriggers(mPrevRequest);
4944 if (res != OK) {
4945 SET_ERR("RequestThread: Unable to remove triggers "
4946 "(capture request %d, HAL device: %s (%d)",
4947 nextRequest.halRequest.frame_number, strerror(-res), res);
4948 cleanUpFailedRequests(/*sendRequestError*/ false);
4949 return false;
4950 }
4951 }
4952 return true;
4953}
4954
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004955nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4956 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4957 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4958 find_camera_metadata_ro_entry(request,
4959 ANDROID_CONTROL_AE_MODE,
4960 &e);
4961 if (e.count == 0) return maxExpectedDuration;
4962
4963 switch (e.data.u8[0]) {
4964 case ANDROID_CONTROL_AE_MODE_OFF:
4965 find_camera_metadata_ro_entry(request,
4966 ANDROID_SENSOR_EXPOSURE_TIME,
4967 &e);
4968 if (e.count > 0) {
4969 maxExpectedDuration = e.data.i64[0];
4970 }
4971 find_camera_metadata_ro_entry(request,
4972 ANDROID_SENSOR_FRAME_DURATION,
4973 &e);
4974 if (e.count > 0) {
4975 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4976 }
4977 break;
4978 default:
4979 find_camera_metadata_ro_entry(request,
4980 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4981 &e);
4982 if (e.count > 1) {
4983 maxExpectedDuration = 1e9 / e.data.u8[0];
4984 }
4985 break;
4986 }
4987
4988 return maxExpectedDuration;
4989}
4990
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004991bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4992 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4993 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4994 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4995 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4996 return true;
4997 }
4998
4999 return false;
5000}
5001
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005002bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5003 ATRACE_CALL();
5004 bool updatesDetected = false;
5005
5006 for (auto tag : mSessionParamKeys) {
5007 camera_metadata_ro_entry entry = settings.find(tag);
5008 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
5009
5010 if (entry.count > 0) {
5011 bool isDifferent = false;
5012 if (lastEntry.count > 0) {
5013 // Have a last value, compare to see if changed
5014 if (lastEntry.type == entry.type &&
5015 lastEntry.count == entry.count) {
5016 // Same type and count, compare values
5017 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5018 size_t entryBytes = bytesPerValue * lastEntry.count;
5019 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5020 if (cmp != 0) {
5021 isDifferent = true;
5022 }
5023 } else {
5024 // Count or type has changed
5025 isDifferent = true;
5026 }
5027 } else {
5028 // No last entry, so always consider to be different
5029 isDifferent = true;
5030 }
5031
5032 if (isDifferent) {
5033 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005034 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5035 updatesDetected = true;
5036 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005037 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005038 }
5039 } else if (lastEntry.count > 0) {
5040 // Value has been removed
5041 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
5042 mLatestSessionParams.erase(tag);
5043 updatesDetected = true;
5044 }
5045 }
5046
5047 return updatesDetected;
5048}
5049
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005050bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005051 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005052 status_t res;
5053
5054 // Handle paused state.
5055 if (waitIfPaused()) {
5056 return true;
5057 }
5058
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005059 // Wait for the next batch of requests.
5060 waitForNextRequestBatch();
5061 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005062 return true;
5063 }
5064
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005065 // Get the latest request ID, if any
5066 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005067 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005068 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005069 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005070 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005071 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005072 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5073 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005074 }
5075
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005076 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5077 // or a single request from streaming or burst. In either case the first element
5078 // should contain the latest camera settings that we need to check for any session
5079 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005080 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005081 res = OK;
5082
5083 //Input stream buffers are already acquired at this point so an input stream
5084 //will not be able to move to idle state unless we force it.
5085 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5086 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5087 if (res != OK) {
5088 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5089 cleanUpFailedRequests(/*sendRequestError*/ false);
5090 return false;
5091 }
5092 }
5093
5094 if (res == OK) {
5095 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5096 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005097 sp<Camera3Device> parent = mParent.promote();
5098 if (parent != nullptr) {
5099 parent->pauseStateNotify(true);
5100 }
5101
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005102 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5103
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005104 if (parent != nullptr) {
5105 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5106 }
5107
5108 statusTracker->markComponentActive(mStatusId);
5109 setPaused(false);
5110 }
5111
5112 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5113 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5114 if (res != OK) {
5115 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5116 cleanUpFailedRequests(/*sendRequestError*/ false);
5117 return false;
5118 }
5119 }
5120 }
5121 }
5122
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005123 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005124 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005125 if (res == TIMED_OUT) {
5126 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005127 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005128 // Check if any stream is abandoned.
5129 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005130 return true;
5131 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005132 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005133 return false;
5134 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005135
Zhijun Hecc27e112013-10-03 16:12:43 -07005136 // Inform waitUntilRequestProcessed thread of a new request ID
5137 {
5138 Mutex::Autolock al(mLatestRequestMutex);
5139
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005140 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005141 mLatestRequestSignal.signal();
5142 }
5143
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005144 // Submit a batch of requests to HAL.
5145 // Use flush lock only when submitting multilple requests in a batch.
5146 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5147 // which may take a long time to finish so synchronizing flush() and
5148 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5149 // For now, only synchronize for high speed recording and we should figure something out for
5150 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005151 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005152
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005153 if (useFlushLock) {
5154 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005155 }
5156
Zhijun Hef0645c12016-08-02 00:58:11 -07005157 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005158 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005159
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005160 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005161 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005162 if (mInterface->supportBatchRequest()) {
5163 submitRequestSuccess = sendRequestsBatch();
5164 } else {
5165 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005166 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005167 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5168 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005169
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005170 if (submitRequestSuccess) {
5171 sp<Camera3Device> parent = mParent.promote();
5172 if (parent != nullptr) {
5173 parent->mRequestBufferSM.onRequestSubmitted();
5174 }
5175 }
5176
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005177 if (useFlushLock) {
5178 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005179 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005180
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005181 // Unset as current request
5182 {
5183 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005184 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005185 }
5186
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005187 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005188}
5189
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005190status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005191 ATRACE_CALL();
5192
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005193 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005194 for (size_t i = 0; i < mNextRequests.size(); i++) {
5195 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005196 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5197 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5198 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5199
5200 // Prepare a request to HAL
5201 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5202
5203 // Insert any queued triggers (before metadata is locked)
5204 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005205 if (res < 0) {
5206 SET_ERR("RequestThread: Unable to insert triggers "
5207 "(capture request %d, HAL device: %s (%d)",
5208 halRequest->frame_number, strerror(-res), res);
5209 return INVALID_OPERATION;
5210 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005211
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005212 int triggerCount = res;
5213 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5214 mPrevTriggers = triggerCount;
5215
5216 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005217 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5218 // Request settings are all the same within one batch, so only treat the first
5219 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005220 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005221 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005222 /**
5223 * HAL workaround:
5224 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5225 */
5226 res = addDummyTriggerIds(captureRequest);
5227 if (res != OK) {
5228 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5229 "(capture request %d, HAL device: %s (%d)",
5230 halRequest->frame_number, strerror(-res), res);
5231 return INVALID_OPERATION;
5232 }
5233
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005234 {
5235 // Correct metadata regions for distortion correction if enabled
5236 sp<Camera3Device> parent = mParent.promote();
5237 if (parent != nullptr) {
5238 res = parent->mDistortionMapper.correctCaptureRequest(
5239 &(captureRequest->mSettingsList.begin()->metadata));
5240 if (res != OK) {
5241 SET_ERR("RequestThread: Unable to correct capture requests "
5242 "for lens distortion for request %d: %s (%d)",
5243 halRequest->frame_number, strerror(-res), res);
5244 return INVALID_OPERATION;
5245 }
5246 }
5247 }
5248
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005249 /**
5250 * The request should be presorted so accesses in HAL
5251 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5252 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005253 captureRequest->mSettingsList.begin()->metadata.sort();
5254 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005255 mPrevRequest = captureRequest;
5256 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5257
5258 IF_ALOGV() {
5259 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5260 find_camera_metadata_ro_entry(
5261 halRequest->settings,
5262 ANDROID_CONTROL_AF_TRIGGER,
5263 &e
5264 );
5265 if (e.count > 0) {
5266 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5267 __FUNCTION__,
5268 halRequest->frame_number,
5269 e.data.u8[0]);
5270 }
5271 }
5272 } else {
5273 // leave request.settings NULL to indicate 'reuse latest given'
5274 ALOGVV("%s: Request settings are REUSED",
5275 __FUNCTION__);
5276 }
5277
Emilian Peevaebbe412018-01-15 13:53:24 +00005278 if (captureRequest->mSettingsList.size() > 1) {
5279 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5280 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005281 if (newRequest) {
5282 halRequest->physcam_settings =
5283 new const camera_metadata* [halRequest->num_physcam_settings];
5284 } else {
5285 halRequest->physcam_settings = nullptr;
5286 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005287 auto it = ++captureRequest->mSettingsList.begin();
5288 size_t i = 0;
5289 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5290 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005291 if (newRequest) {
5292 it->metadata.sort();
5293 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5294 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005295 }
5296 }
5297
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005298 uint32_t totalNumBuffers = 0;
5299
5300 // Fill in buffers
5301 if (captureRequest->mInputStream != NULL) {
5302 halRequest->input_buffer = &captureRequest->mInputBuffer;
5303 totalNumBuffers += 1;
5304 } else {
5305 halRequest->input_buffer = NULL;
5306 }
5307
5308 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5309 captureRequest->mOutputStreams.size());
5310 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005311 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005312
5313 sp<Camera3Device> parent = mParent.promote();
5314 if (parent == NULL) {
5315 // Should not happen, and nowhere to send errors to, so just log it
5316 CLOGE("RequestThread: Parent is gone");
5317 return INVALID_OPERATION;
5318 }
5319 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5320
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005321 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005322 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005323 sp<Camera3OutputStreamInterface> outputStream =
5324 captureRequest->mOutputStreams.editItemAt(j);
5325 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005326
5327 // Prepare video buffers for high speed recording on the first video request.
5328 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5329 // Only try to prepare video stream on the first video request.
5330 mPrepareVideoStream = false;
5331
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005332 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5333 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005334 while (res == NOT_ENOUGH_DATA) {
5335 res = outputStream->prepareNextBuffer();
5336 }
5337 if (res != OK) {
5338 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5339 __FUNCTION__, strerror(-res), res);
5340 outputStream->cancelPrepare();
5341 }
5342 }
5343
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005344 std::vector<size_t> uniqueSurfaceIds;
5345 res = outputStream->getUniqueSurfaceIds(
5346 captureRequest->mOutputSurfaces[streamId],
5347 &uniqueSurfaceIds);
5348 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5349 if (res != OK && res != INVALID_OPERATION) {
5350 ALOGE("%s: failed to query stream %d unique surface IDs",
5351 __FUNCTION__, streamId);
5352 return res;
5353 }
5354 if (res == OK) {
5355 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5356 }
5357
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005358 if (mUseHalBufManager) {
5359 // HAL will request buffer through requestStreamBuffer API
5360 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5361 buffer.stream = outputStream->asHalStream();
5362 buffer.buffer = nullptr;
5363 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5364 buffer.acquire_fence = -1;
5365 buffer.release_fence = -1;
5366 } else {
5367 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5368 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005369 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005370 if (res != OK) {
5371 // Can't get output buffer from gralloc queue - this could be due to
5372 // abandoned queue or other consumer misbehavior, so not a fatal
5373 // error
5374 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5375 " %s (%d)", strerror(-res), res);
5376
5377 return TIMED_OUT;
5378 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005379 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005380
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005381 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5382
5383 if (!physicalCameraId.isEmpty()) {
5384 // Physical stream isn't supported for input request.
5385 if (halRequest->input_buffer) {
5386 CLOGE("Physical stream is not supported for input request");
5387 return INVALID_OPERATION;
5388 }
5389 requestedPhysicalCameras.insert(physicalCameraId);
5390 }
5391 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005392 }
5393 totalNumBuffers += halRequest->num_output_buffers;
5394
5395 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005396 // If this request list is for constrained high speed recording (not
5397 // preview), and the current request is not the last one in the batch,
5398 // do not send callback to the app.
5399 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005400 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005401 hasCallback = false;
5402 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005403 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005404 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005405 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5406 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5407 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5408 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5409 isStillCapture = true;
5410 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5411 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005412
5413 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5414 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5415 isZslCapture = true;
5416 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005417 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005418 res = parent->registerInFlight(halRequest->frame_number,
5419 totalNumBuffers, captureRequest->mResultExtras,
5420 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005421 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005422 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005423 requestedPhysicalCameras, isStillCapture, isZslCapture,
5424 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5425 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005426 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5427 ", burstId = %" PRId32 ".",
5428 __FUNCTION__,
5429 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5430 captureRequest->mResultExtras.burstId);
5431 if (res != OK) {
5432 SET_ERR("RequestThread: Unable to register new in-flight request:"
5433 " %s (%d)", strerror(-res), res);
5434 return INVALID_OPERATION;
5435 }
5436 }
5437
5438 return OK;
5439}
5440
Igor Murashkin1e479c02013-09-06 16:55:14 -07005441CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005442 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005443 Mutex::Autolock al(mLatestRequestMutex);
5444
5445 ALOGV("RequestThread::%s", __FUNCTION__);
5446
5447 return mLatestRequest;
5448}
5449
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005450bool Camera3Device::RequestThread::isStreamPending(
5451 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005452 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005453 Mutex::Autolock l(mRequestLock);
5454
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005455 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005456 if (!nextRequest.submitted) {
5457 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5458 if (stream == s) return true;
5459 }
5460 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005461 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005462 }
5463
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005464 for (const auto& request : mRequestQueue) {
5465 for (const auto& s : request->mOutputStreams) {
5466 if (stream == s) return true;
5467 }
5468 if (stream == request->mInputStream) return true;
5469 }
5470
5471 for (const auto& request : mRepeatingRequests) {
5472 for (const auto& s : request->mOutputStreams) {
5473 if (stream == s) return true;
5474 }
5475 if (stream == request->mInputStream) return true;
5476 }
5477
5478 return false;
5479}
Jianing Weicb0652e2014-03-12 18:29:36 -07005480
Emilian Peev40ead602017-09-26 15:46:36 +01005481bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5482 ATRACE_CALL();
5483 Mutex::Autolock l(mRequestLock);
5484
5485 for (const auto& nextRequest : mNextRequests) {
5486 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5487 if (s.first == streamId) {
5488 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5489 if (it != s.second.end()) {
5490 return true;
5491 }
5492 }
5493 }
5494 }
5495
5496 for (const auto& request : mRequestQueue) {
5497 for (const auto& s : request->mOutputSurfaces) {
5498 if (s.first == streamId) {
5499 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5500 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005501 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005502 }
5503 }
5504 }
5505 }
5506
5507 for (const auto& request : mRepeatingRequests) {
5508 for (const auto& s : request->mOutputSurfaces) {
5509 if (s.first == streamId) {
5510 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5511 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005512 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005513 }
5514 }
5515 }
5516 }
5517
5518 return false;
5519}
5520
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005521void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5522 if (!mUseHalBufManager) {
5523 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5524 return;
5525 }
5526
5527 Mutex::Autolock pl(mPauseLock);
5528 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005529 mInterface->signalPipelineDrain(streamIds);
5530 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005531 }
5532 // If request thread is still busy, wait until paused then notify HAL
5533 mNotifyPipelineDrain = true;
5534 mStreamIdsToBeDrained = streamIds;
5535}
5536
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005537nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005538 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005539 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005540 return mExpectedInflightDuration > kMinInflightDuration ?
5541 mExpectedInflightDuration : kMinInflightDuration;
5542}
5543
Emilian Peevaebbe412018-01-15 13:53:24 +00005544void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5545 camera3_capture_request_t *halRequest) {
5546 if ((request == nullptr) || (halRequest == nullptr)) {
5547 ALOGE("%s: Invalid request!", __FUNCTION__);
5548 return;
5549 }
5550
5551 if (halRequest->num_physcam_settings > 0) {
5552 if (halRequest->physcam_id != nullptr) {
5553 delete [] halRequest->physcam_id;
5554 halRequest->physcam_id = nullptr;
5555 }
5556 if (halRequest->physcam_settings != nullptr) {
5557 auto it = ++(request->mSettingsList.begin());
5558 size_t i = 0;
5559 for (; it != request->mSettingsList.end(); it++, i++) {
5560 it->metadata.unlock(halRequest->physcam_settings[i]);
5561 }
5562 delete [] halRequest->physcam_settings;
5563 halRequest->physcam_settings = nullptr;
5564 }
5565 }
5566}
5567
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005568void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5569 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005570 return;
5571 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005572
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005573 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005574 // Skip the ones that have been submitted successfully.
5575 if (nextRequest.submitted) {
5576 continue;
5577 }
5578
5579 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5580 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5581 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5582
5583 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005584 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005585 }
5586
Emilian Peevaebbe412018-01-15 13:53:24 +00005587 cleanupPhysicalSettings(captureRequest, halRequest);
5588
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005589 if (captureRequest->mInputStream != NULL) {
5590 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5591 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5592 }
5593
5594 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005595 //Buffers that failed processing could still have
5596 //valid acquire fence.
5597 int acquireFence = (*outputBuffers)[i].acquire_fence;
5598 if (0 <= acquireFence) {
5599 close(acquireFence);
5600 outputBuffers->editItemAt(i).acquire_fence = -1;
5601 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005602 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5603 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5604 }
5605
5606 if (sendRequestError) {
5607 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005608 sp<NotificationListener> listener = mListener.promote();
5609 if (listener != NULL) {
5610 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005611 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005612 captureRequest->mResultExtras);
5613 }
5614 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005615
5616 // Remove yet-to-be submitted inflight request from inflightMap
5617 {
5618 sp<Camera3Device> parent = mParent.promote();
5619 if (parent != NULL) {
5620 Mutex::Autolock l(parent->mInFlightLock);
5621 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5622 if (idx >= 0) {
5623 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5624 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5625 parent->removeInFlightMapEntryLocked(idx);
5626 }
5627 }
5628 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005629 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005630
5631 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005632 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005633}
5634
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005635void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005636 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005637 // Optimized a bit for the simple steady-state case (single repeating
5638 // request), to avoid putting that request in the queue temporarily.
5639 Mutex::Autolock l(mRequestLock);
5640
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005641 assert(mNextRequests.empty());
5642
5643 NextRequest nextRequest;
5644 nextRequest.captureRequest = waitForNextRequestLocked();
5645 if (nextRequest.captureRequest == nullptr) {
5646 return;
5647 }
5648
5649 nextRequest.halRequest = camera3_capture_request_t();
5650 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005651 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005652
5653 // Wait for additional requests
5654 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5655
5656 for (size_t i = 1; i < batchSize; i++) {
5657 NextRequest additionalRequest;
5658 additionalRequest.captureRequest = waitForNextRequestLocked();
5659 if (additionalRequest.captureRequest == nullptr) {
5660 break;
5661 }
5662
5663 additionalRequest.halRequest = camera3_capture_request_t();
5664 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005665 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005666 }
5667
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005668 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005669 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005670 mNextRequests.size(), batchSize);
5671 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005672 }
5673
5674 return;
5675}
5676
5677sp<Camera3Device::CaptureRequest>
5678 Camera3Device::RequestThread::waitForNextRequestLocked() {
5679 status_t res;
5680 sp<CaptureRequest> nextRequest;
5681
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005682 while (mRequestQueue.empty()) {
5683 if (!mRepeatingRequests.empty()) {
5684 // Always atomically enqueue all requests in a repeating request
5685 // list. Guarantees a complete in-sequence set of captures to
5686 // application.
5687 const RequestList &requests = mRepeatingRequests;
5688 RequestList::const_iterator firstRequest =
5689 requests.begin();
5690 nextRequest = *firstRequest;
5691 mRequestQueue.insert(mRequestQueue.end(),
5692 ++firstRequest,
5693 requests.end());
5694 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005695
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005696 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005697
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005698 break;
5699 }
5700
5701 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5702
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005703 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5704 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005705 Mutex::Autolock pl(mPauseLock);
5706 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005707 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005708 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005709 // Let the tracker know
5710 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5711 if (statusTracker != 0) {
5712 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5713 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005714 if (mNotifyPipelineDrain) {
5715 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5716 mNotifyPipelineDrain = false;
5717 mStreamIdsToBeDrained.clear();
5718 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005719 sp<Camera3Device> parent = mParent.promote();
5720 if (parent != nullptr) {
5721 parent->mRequestBufferSM.onRequestThreadPaused();
5722 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005723 }
5724 // Stop waiting for now and let thread management happen
5725 return NULL;
5726 }
5727 }
5728
5729 if (nextRequest == NULL) {
5730 // Don't have a repeating request already in hand, so queue
5731 // must have an entry now.
5732 RequestList::iterator firstRequest =
5733 mRequestQueue.begin();
5734 nextRequest = *firstRequest;
5735 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005736 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5737 sp<NotificationListener> listener = mListener.promote();
5738 if (listener != NULL) {
5739 listener->notifyRequestQueueEmpty();
5740 }
5741 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005742 }
5743
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005744 // In case we've been unpaused by setPaused clearing mDoPause, need to
5745 // update internal pause state (capture/setRepeatingRequest unpause
5746 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005747 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005748 if (mPaused) {
5749 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5750 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5751 if (statusTracker != 0) {
5752 statusTracker->markComponentActive(mStatusId);
5753 }
5754 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005755 mPaused = false;
5756
5757 // Check if we've reconfigured since last time, and reset the preview
5758 // request if so. Can't use 'NULL request == repeat' across configure calls.
5759 if (mReconfigured) {
5760 mPrevRequest.clear();
5761 mReconfigured = false;
5762 }
5763
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005764 if (nextRequest != NULL) {
5765 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005766 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5767 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005768
5769 // Since RequestThread::clear() removes buffers from the input stream,
5770 // get the right buffer here before unlocking mRequestLock
5771 if (nextRequest->mInputStream != NULL) {
5772 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5773 if (res != OK) {
5774 // Can't get input buffer from gralloc queue - this could be due to
5775 // disconnected queue or other producer misbehavior, so not a fatal
5776 // error
5777 ALOGE("%s: Can't get input buffer, skipping request:"
5778 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005779
5780 sp<NotificationListener> listener = mListener.promote();
5781 if (listener != NULL) {
5782 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005783 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005784 nextRequest->mResultExtras);
5785 }
5786 return NULL;
5787 }
5788 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005789 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005790
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005791 return nextRequest;
5792}
5793
5794bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005795 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005796 status_t res;
5797 Mutex::Autolock l(mPauseLock);
5798 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005799 if (mPaused == false) {
5800 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005801 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5802 // Let the tracker know
5803 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5804 if (statusTracker != 0) {
5805 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5806 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005807 if (mNotifyPipelineDrain) {
5808 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5809 mNotifyPipelineDrain = false;
5810 mStreamIdsToBeDrained.clear();
5811 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005812 sp<Camera3Device> parent = mParent.promote();
5813 if (parent != nullptr) {
5814 parent->mRequestBufferSM.onRequestThreadPaused();
5815 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005816 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005817
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005818 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005819 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005820 return true;
5821 }
5822 }
5823 // We don't set mPaused to false here, because waitForNextRequest needs
5824 // to further manage the paused state in case of starvation.
5825 return false;
5826}
5827
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005828void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005829 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005830 // With work to do, mark thread as unpaused.
5831 // If paused by request (setPaused), don't resume, to avoid
5832 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005833 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005834 Mutex::Autolock p(mPauseLock);
5835 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005836 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5837 if (mPaused) {
5838 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5839 if (statusTracker != 0) {
5840 statusTracker->markComponentActive(mStatusId);
5841 }
5842 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005843 mPaused = false;
5844 }
5845}
5846
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005847void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5848 sp<Camera3Device> parent = mParent.promote();
5849 if (parent != NULL) {
5850 va_list args;
5851 va_start(args, fmt);
5852
5853 parent->setErrorStateV(fmt, args);
5854
5855 va_end(args);
5856 }
5857}
5858
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005859status_t Camera3Device::RequestThread::insertTriggers(
5860 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005861 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005862 Mutex::Autolock al(mTriggerMutex);
5863
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005864 sp<Camera3Device> parent = mParent.promote();
5865 if (parent == NULL) {
5866 CLOGE("RequestThread: Parent is gone");
5867 return DEAD_OBJECT;
5868 }
5869
Emilian Peevaebbe412018-01-15 13:53:24 +00005870 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005871 size_t count = mTriggerMap.size();
5872
5873 for (size_t i = 0; i < count; ++i) {
5874 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005875 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005876
5877 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5878 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5879 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005880 if (isAeTrigger) {
5881 request->mResultExtras.precaptureTriggerId = triggerId;
5882 mCurrentPreCaptureTriggerId = triggerId;
5883 } else {
5884 request->mResultExtras.afTriggerId = triggerId;
5885 mCurrentAfTriggerId = triggerId;
5886 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005887 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005888 }
5889
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005890 camera_metadata_entry entry = metadata.find(tag);
5891
5892 if (entry.count > 0) {
5893 /**
5894 * Already has an entry for this trigger in the request.
5895 * Rewrite it with our requested trigger value.
5896 */
5897 RequestTrigger oldTrigger = trigger;
5898
5899 oldTrigger.entryValue = entry.data.u8[0];
5900
5901 mTriggerReplacedMap.add(tag, oldTrigger);
5902 } else {
5903 /**
5904 * More typical, no trigger entry, so we just add it
5905 */
5906 mTriggerRemovedMap.add(tag, trigger);
5907 }
5908
5909 status_t res;
5910
5911 switch (trigger.getTagType()) {
5912 case TYPE_BYTE: {
5913 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5914 res = metadata.update(tag,
5915 &entryValue,
5916 /*count*/1);
5917 break;
5918 }
5919 case TYPE_INT32:
5920 res = metadata.update(tag,
5921 &trigger.entryValue,
5922 /*count*/1);
5923 break;
5924 default:
5925 ALOGE("%s: Type not supported: 0x%x",
5926 __FUNCTION__,
5927 trigger.getTagType());
5928 return INVALID_OPERATION;
5929 }
5930
5931 if (res != OK) {
5932 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5933 ", value %d", __FUNCTION__, trigger.getTagName(),
5934 trigger.entryValue);
5935 return res;
5936 }
5937
5938 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5939 trigger.getTagName(),
5940 trigger.entryValue);
5941 }
5942
5943 mTriggerMap.clear();
5944
5945 return count;
5946}
5947
5948status_t Camera3Device::RequestThread::removeTriggers(
5949 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005950 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005951 Mutex::Autolock al(mTriggerMutex);
5952
Emilian Peevaebbe412018-01-15 13:53:24 +00005953 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005954
5955 /**
5956 * Replace all old entries with their old values.
5957 */
5958 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5959 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5960
5961 status_t res;
5962
5963 uint32_t tag = trigger.metadataTag;
5964 switch (trigger.getTagType()) {
5965 case TYPE_BYTE: {
5966 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5967 res = metadata.update(tag,
5968 &entryValue,
5969 /*count*/1);
5970 break;
5971 }
5972 case TYPE_INT32:
5973 res = metadata.update(tag,
5974 &trigger.entryValue,
5975 /*count*/1);
5976 break;
5977 default:
5978 ALOGE("%s: Type not supported: 0x%x",
5979 __FUNCTION__,
5980 trigger.getTagType());
5981 return INVALID_OPERATION;
5982 }
5983
5984 if (res != OK) {
5985 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5986 ", trigger value %d", __FUNCTION__,
5987 trigger.getTagName(), trigger.entryValue);
5988 return res;
5989 }
5990 }
5991 mTriggerReplacedMap.clear();
5992
5993 /**
5994 * Remove all new entries.
5995 */
5996 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5997 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5998 status_t res = metadata.erase(trigger.metadataTag);
5999
6000 if (res != OK) {
6001 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6002 ", trigger value %d", __FUNCTION__,
6003 trigger.getTagName(), trigger.entryValue);
6004 return res;
6005 }
6006 }
6007 mTriggerRemovedMap.clear();
6008
6009 return OK;
6010}
6011
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006012status_t Camera3Device::RequestThread::addDummyTriggerIds(
6013 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006014 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006015 static const int32_t dummyTriggerId = 1;
6016 status_t res;
6017
Emilian Peevaebbe412018-01-15 13:53:24 +00006018 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006019
6020 // If AF trigger is active, insert a dummy AF trigger ID if none already
6021 // exists
6022 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6023 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6024 if (afTrigger.count > 0 &&
6025 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6026 afId.count == 0) {
6027 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6028 if (res != OK) return res;
6029 }
6030
6031 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6032 // if none already exists
6033 camera_metadata_entry pcTrigger =
6034 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6035 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6036 if (pcTrigger.count > 0 &&
6037 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6038 pcId.count == 0) {
6039 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6040 &dummyTriggerId, 1);
6041 if (res != OK) return res;
6042 }
6043
6044 return OK;
6045}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006046
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006047/**
6048 * PreparerThread inner class methods
6049 */
6050
6051Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006052 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006053 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006054}
6055
6056Camera3Device::PreparerThread::~PreparerThread() {
6057 Thread::requestExitAndWait();
6058 if (mCurrentStream != nullptr) {
6059 mCurrentStream->cancelPrepare();
6060 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6061 mCurrentStream.clear();
6062 }
6063 clear();
6064}
6065
Ruben Brunkc78ac262015-08-13 17:58:46 -07006066status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006067 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006068 status_t res;
6069
6070 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006071 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006072
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006073 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006074 if (res == OK) {
6075 // No preparation needed, fire listener right off
6076 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006077 if (listener != NULL) {
6078 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006079 }
6080 return OK;
6081 } else if (res != NOT_ENOUGH_DATA) {
6082 return res;
6083 }
6084
6085 // Need to prepare, start up thread if necessary
6086 if (!mActive) {
6087 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6088 // isn't running
6089 Thread::requestExitAndWait();
6090 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6091 if (res != OK) {
6092 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006093 if (listener != NULL) {
6094 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006095 }
6096 return res;
6097 }
6098 mCancelNow = false;
6099 mActive = true;
6100 ALOGV("%s: Preparer stream started", __FUNCTION__);
6101 }
6102
6103 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006104 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006105 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6106
6107 return OK;
6108}
6109
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006110void Camera3Device::PreparerThread::pause() {
6111 ATRACE_CALL();
6112
6113 Mutex::Autolock l(mLock);
6114
6115 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6116 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6117 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6118 int currentMaxCount = mCurrentMaxCount;
6119 mPendingStreams.clear();
6120 mCancelNow = true;
6121 while (mActive) {
6122 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6123 if (res == TIMED_OUT) {
6124 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6125 return;
6126 } else if (res != OK) {
6127 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6128 return;
6129 }
6130 }
6131
6132 //Check whether the prepare thread was able to complete the current
6133 //stream. In case work is still pending emplace it along with the rest
6134 //of the streams in the pending list.
6135 if (currentStream != nullptr) {
6136 if (!mCurrentPrepareComplete) {
6137 pendingStreams.emplace(currentMaxCount, currentStream);
6138 }
6139 }
6140
6141 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6142 for (const auto& it : mPendingStreams) {
6143 it.second->cancelPrepare();
6144 }
6145}
6146
6147status_t Camera3Device::PreparerThread::resume() {
6148 ATRACE_CALL();
6149 status_t res;
6150
6151 Mutex::Autolock l(mLock);
6152 sp<NotificationListener> listener = mListener.promote();
6153
6154 if (mActive) {
6155 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6156 return NO_INIT;
6157 }
6158
6159 auto it = mPendingStreams.begin();
6160 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006161 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006162 if (res == OK) {
6163 if (listener != NULL) {
6164 listener->notifyPrepared(it->second->getId());
6165 }
6166 it = mPendingStreams.erase(it);
6167 } else if (res != NOT_ENOUGH_DATA) {
6168 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6169 res, strerror(-res));
6170 it = mPendingStreams.erase(it);
6171 } else {
6172 it++;
6173 }
6174 }
6175
6176 if (mPendingStreams.empty()) {
6177 return OK;
6178 }
6179
6180 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6181 if (res != OK) {
6182 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6183 __FUNCTION__, res, strerror(-res));
6184 return res;
6185 }
6186 mCancelNow = false;
6187 mActive = true;
6188 ALOGV("%s: Preparer stream started", __FUNCTION__);
6189
6190 return OK;
6191}
6192
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006193status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006194 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006195 Mutex::Autolock l(mLock);
6196
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006197 for (const auto& it : mPendingStreams) {
6198 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006199 }
6200 mPendingStreams.clear();
6201 mCancelNow = true;
6202
6203 return OK;
6204}
6205
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006206void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006207 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006208 Mutex::Autolock l(mLock);
6209 mListener = listener;
6210}
6211
6212bool Camera3Device::PreparerThread::threadLoop() {
6213 status_t res;
6214 {
6215 Mutex::Autolock l(mLock);
6216 if (mCurrentStream == nullptr) {
6217 // End thread if done with work
6218 if (mPendingStreams.empty()) {
6219 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6220 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6221 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6222 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006223 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006224 return false;
6225 }
6226
6227 // Get next stream to prepare
6228 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006229 mCurrentStream = it->second;
6230 mCurrentMaxCount = it->first;
6231 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006232 mPendingStreams.erase(it);
6233 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6234 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6235 } else if (mCancelNow) {
6236 mCurrentStream->cancelPrepare();
6237 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6238 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6239 mCurrentStream.clear();
6240 mCancelNow = false;
6241 return true;
6242 }
6243 }
6244
6245 res = mCurrentStream->prepareNextBuffer();
6246 if (res == NOT_ENOUGH_DATA) return true;
6247 if (res != OK) {
6248 // Something bad happened; try to recover by cancelling prepare and
6249 // signalling listener anyway
6250 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6251 mCurrentStream->getId(), res, strerror(-res));
6252 mCurrentStream->cancelPrepare();
6253 }
6254
6255 // This stream has finished, notify listener
6256 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006257 sp<NotificationListener> listener = mListener.promote();
6258 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006259 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6260 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006261 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006262 }
6263
6264 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6265 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006266 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006267
6268 return true;
6269}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006270
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006271status_t Camera3Device::RequestBufferStateMachine::initialize(
6272 sp<camera3::StatusTracker> statusTracker) {
6273 if (statusTracker == nullptr) {
6274 ALOGE("%s: statusTracker is null", __FUNCTION__);
6275 return BAD_VALUE;
6276 }
6277
6278 std::lock_guard<std::mutex> lock(mLock);
6279 mStatusTracker = statusTracker;
6280 mRequestBufferStatusId = statusTracker->addComponent();
6281 return OK;
6282}
6283
6284bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6285 std::lock_guard<std::mutex> lock(mLock);
6286 if (mStatus == RB_STATUS_READY) {
6287 mRequestBufferOngoing = true;
6288 return true;
6289 }
6290 return false;
6291}
6292
6293void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6294 std::lock_guard<std::mutex> lock(mLock);
6295 if (!mRequestBufferOngoing) {
6296 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6297 return;
6298 }
6299 mRequestBufferOngoing = false;
6300 if (mStatus == RB_STATUS_PENDING_STOP) {
6301 checkSwitchToStopLocked();
6302 }
6303}
6304
6305void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6306 std::lock_guard<std::mutex> lock(mLock);
6307 RequestBufferState oldStatus = mStatus;
6308 mStatus = RB_STATUS_READY;
6309 if (oldStatus != RB_STATUS_READY) {
6310 notifyTrackerLocked(/*active*/true);
6311 }
6312 return;
6313}
6314
6315void Camera3Device::RequestBufferStateMachine::onRequestSubmitted() {
6316 std::lock_guard<std::mutex> lock(mLock);
6317 mRequestThreadPaused = false;
6318 mInflightMapEmpty = false;
6319 if (mStatus == RB_STATUS_STOPPED) {
6320 mStatus = RB_STATUS_READY;
6321 notifyTrackerLocked(/*active*/true);
6322 }
6323 return;
6324}
6325
6326void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6327 std::lock_guard<std::mutex> lock(mLock);
6328 mRequestThreadPaused = true;
6329 if (mStatus == RB_STATUS_PENDING_STOP) {
6330 checkSwitchToStopLocked();
6331 }
6332 return;
6333}
6334
6335void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6336 std::lock_guard<std::mutex> lock(mLock);
6337 mInflightMapEmpty = true;
6338 if (mStatus == RB_STATUS_PENDING_STOP) {
6339 checkSwitchToStopLocked();
6340 }
6341 return;
6342}
6343
6344void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6345 std::lock_guard<std::mutex> lock(mLock);
6346 if (!checkSwitchToStopLocked()) {
6347 mStatus = RB_STATUS_PENDING_STOP;
6348 }
6349 return;
6350}
6351
6352void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6353 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6354 if (statusTracker != nullptr) {
6355 if (active) {
6356 statusTracker->markComponentActive(mRequestBufferStatusId);
6357 } else {
6358 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6359 }
6360 }
6361}
6362
6363bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6364 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6365 mStatus = RB_STATUS_STOPPED;
6366 notifyTrackerLocked(/*active*/false);
6367 return true;
6368 }
6369 return false;
6370}
6371
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006372}; // namespace android