blob: bda35f3738a15deb30a54ae8be0d60afa7aab861 [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
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080052#include <android/hardware/camera2/ICameraDeviceUser.h>
53
Igor Murashkinff3e31d2013-10-23 16:40:06 -070054#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070055#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070056#include "device3/Camera3Device.h"
57#include "device3/Camera3OutputStream.h"
58#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070059#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070060#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070061#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070062#include "utils/CameraThreadState.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080063
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080064#include <tuple>
65
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080066using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080067using namespace android::hardware::camera;
68using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080069
70namespace android {
71
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080072Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080073 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080074 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070075 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070076 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070077 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070078 mUsePartialResult(false),
79 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080080 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070081 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070082 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070083 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070084 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070085 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070086 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000087 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010088 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070089 mLastTemplateId(-1),
90 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080091{
92 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080093 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080094}
95
96Camera3Device::~Camera3Device()
97{
98 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080099 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700100 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800101}
102
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800103const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800104 return mId;
105}
106
Emilian Peevbd8c5032018-02-14 23:05:40 +0000107status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800108 ATRACE_CALL();
109 Mutex::Autolock il(mInterfaceLock);
110 Mutex::Autolock l(mLock);
111
112 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
113 if (mStatus != STATUS_UNINITIALIZED) {
114 CLOGE("Already initialized!");
115 return INVALID_OPERATION;
116 }
117 if (manager == nullptr) return INVALID_OPERATION;
118
119 sp<ICameraDeviceSession> session;
120 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800121 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800122 /*out*/ &session);
123 ATRACE_END();
124 if (res != OK) {
125 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
126 return res;
127 }
128
Steven Moreland5ff9c912017-03-09 23:13:00 -0800129 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800130 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700131 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800132 session->close();
133 return res;
134 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800135
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700136 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700137 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700138 if (isLogical) {
139 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700140 res = manager->getCameraCharacteristics(
141 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700142 if (res != OK) {
143 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
144 physicalId.c_str(), strerror(-res), res);
145 session->close();
146 return res;
147 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700148
149 if (DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId])) {
150 mDistortionMappers[physicalId].setupStaticInfo(mPhysicalDeviceInfoMap[physicalId]);
151 if (res != OK) {
152 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
153 "correction", physicalId.c_str());
154 session->close();
155 return res;
156 }
157 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700158 }
159 }
160
Yifan Hongf79b5542017-04-11 14:44:25 -0700161 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700162 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
163 [&queue](const auto& descriptor) {
164 queue = std::make_shared<RequestMetadataQueue>(descriptor);
165 if (!queue->isValid() || queue->availableToWrite() <= 0) {
166 ALOGE("HAL returns empty request metadata fmq, not use it");
167 queue = nullptr;
168 // don't use the queue onwards.
169 }
170 });
171 if (!requestQueueRet.isOk()) {
172 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
173 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700174 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700175 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700176
177 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700178 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700179 [&resQueue](const auto& descriptor) {
180 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
181 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700182 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700183 resQueue = nullptr;
184 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700185 }
186 });
187 if (!resultQueueRet.isOk()) {
188 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
189 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700190 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700191 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700192 IF_ALOGV() {
193 session->interfaceChain([](
194 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
195 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800196 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700197 ALOGV(" %s", iface.c_str());
198 }
199 });
200 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700201
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800202 camera_metadata_entry bufMgrMode =
203 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
204 if (bufMgrMode.count > 0) {
205 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
206 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
207 }
208
209 mInterface = new HalInterface(session, queue, mUseHalBufManager);
Emilian Peev71c73a22017-03-21 16:35:51 +0000210 std::string providerType;
211 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000212 mTagMonitor.initialize(mVendorTagId);
213 if (!monitorTags.isEmpty()) {
214 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
215 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800216
Shuzhen Wang268a1362018-10-16 16:32:59 -0700217 // Metadata tags needs fixup for monochrome camera device version less
218 // than 3.5.
219 hardware::hidl_version maxVersion{0,0};
220 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
221 if (res != OK) {
222 ALOGE("%s: Error in getting camera device version id: %s (%d)",
223 __FUNCTION__, strerror(-res), res);
224 return res;
225 }
226 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
227 maxVersion.get_major(), maxVersion.get_minor());
228
229 bool isMonochrome = false;
230 camera_metadata_entry_t entry = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
231 for (size_t i = 0; i < entry.count; i++) {
232 uint8_t capability = entry.data.u8[i];
233 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
234 isMonochrome = true;
235 }
236 }
237 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
238
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800239 return initializeCommonLocked();
240}
241
242status_t Camera3Device::initializeCommonLocked() {
243
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700244 /** Start up status tracker thread */
245 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800246 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700247 if (res != OK) {
248 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
249 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800250 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700251 mStatusTracker.clear();
252 return res;
253 }
254
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700255 /** Register in-flight map to the status tracker */
256 mInFlightStatusId = mStatusTracker->addComponent();
257
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700258 if (mUseHalBufManager) {
259 res = mRequestBufferSM.initialize(mStatusTracker);
260 if (res != OK) {
261 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
262 strerror(-res), res);
263 mInterface->close();
264 mStatusTracker.clear();
265 return res;
266 }
267 }
268
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800269 /** Create buffer manager */
270 mBufferManager = new Camera3BufferManager();
271
272 Vector<int32_t> sessionParamKeys;
273 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
274 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
275 if (sessionKeysEntry.count > 0) {
276 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
277 }
278
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700279 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700280 mRequestThread = new RequestThread(
281 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800282 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800283 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700284 SET_ERR_L("Unable to start request queue thread: %s (%d)",
285 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800286 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800287 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800288 return res;
289 }
290
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700291 mPreparerThread = new PreparerThread();
292
Ruben Brunk183f0562015-08-12 12:55:02 -0700293 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800294 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700295 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700296 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700297 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800298
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800299 // Measure the clock domain offset between camera and video/hw_composer
300 camera_metadata_entry timestampSource =
301 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
302 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
303 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
304 mTimestampOffset = getMonoToBoottimeOffset();
305 }
306
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700307 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100308 camera_metadata_entry partialResultsCount =
309 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
310 if (partialResultsCount.count > 0) {
311 mNumPartialResults = partialResultsCount.data.i32[0];
312 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700313 }
314
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700315 camera_metadata_entry configs =
316 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
317 for (uint32_t i = 0; i < configs.count; i += 4) {
318 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
319 configs.data.i32[i + 3] ==
320 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
321 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
322 configs.data.i32[i + 2]));
323 }
324 }
325
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700326 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700327 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700328 if (res != OK) {
329 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
330 return res;
331 }
332 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800333 return OK;
334}
335
336status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700337 return disconnectImpl();
338}
339
340status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800341 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700342 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800343
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700344 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800345
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700346 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700347 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700348 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700349 {
350 Mutex::Autolock l(mLock);
351 if (mStatus == STATUS_UNINITIALIZED) return res;
352
353 if (mStatus == STATUS_ACTIVE ||
354 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
355 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700356 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700357 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700358 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700359 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700360 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700361 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700362 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
363 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700364 // Continue to close device even in case of error
365 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700366 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800367 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800368
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700369 if (mStatus == STATUS_ERROR) {
370 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700371 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700372
373 if (mStatusTracker != NULL) {
374 mStatusTracker->requestExit();
375 }
376
377 if (mRequestThread != NULL) {
378 mRequestThread->requestExit();
379 }
380
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700381 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
382 for (size_t i = 0; i < mOutputStreams.size(); i++) {
383 streams.push_back(mOutputStreams[i]);
384 }
385 if (mInputStream != nullptr) {
386 streams.push_back(mInputStream);
387 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700388 }
389
390 // Joining done without holding mLock, otherwise deadlocks may ensue
391 // as the threads try to access parent state
392 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
393 // HAL may be in a bad state, so waiting for request thread
394 // (which may be stuck in the HAL processCaptureRequest call)
395 // could be dangerous.
396 mRequestThread->join();
397 }
398
399 if (mStatusTracker != NULL) {
400 mStatusTracker->join();
401 }
402
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800403 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700404 {
405 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800406 mRequestThread.clear();
Emilian Peev2843c362018-09-26 08:49:40 +0100407 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700408 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800409 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700410 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800411
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700412 // Call close without internal mutex held, as the HAL close may need to
413 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800414 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700415
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700416 flushInflightRequests();
417
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700418 {
419 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800420 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700421 mOutputStreams.clear();
422 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700423 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700424 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700425 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700426 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800427
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700428 for (auto& weakStream : streams) {
429 sp<Camera3StreamInterface> stream = weakStream.promote();
430 if (stream != nullptr) {
431 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
432 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
433 }
434 }
435
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700436 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700437 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800438}
439
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700440// For dumping/debugging only -
441// try to acquire a lock a few times, eventually give up to proceed with
442// debug/dump operations
443bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
444 bool gotLock = false;
445 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
446 if (lock.tryLock() == NO_ERROR) {
447 gotLock = true;
448 break;
449 } else {
450 usleep(kDumpSleepDuration);
451 }
452 }
453 return gotLock;
454}
455
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700456Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
457 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100458 const int STREAM_CONFIGURATION_SIZE = 4;
459 const int STREAM_FORMAT_OFFSET = 0;
460 const int STREAM_WIDTH_OFFSET = 1;
461 const int STREAM_HEIGHT_OFFSET = 2;
462 const int STREAM_IS_INPUT_OFFSET = 3;
463 camera_metadata_ro_entry_t availableStreamConfigs =
464 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
465 if (availableStreamConfigs.count == 0 ||
466 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
467 return Size(0, 0);
468 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700469
Emilian Peev08dd2452017-04-06 16:55:14 +0100470 // Get max jpeg size (area-wise).
471 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
472 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
473 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
474 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
475 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
476 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
477 && format == HAL_PIXEL_FORMAT_BLOB &&
478 (width * height > maxJpegWidth * maxJpegHeight)) {
479 maxJpegWidth = width;
480 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700481 }
482 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100483
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700484 return Size(maxJpegWidth, maxJpegHeight);
485}
486
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800487nsecs_t Camera3Device::getMonoToBoottimeOffset() {
488 // try three times to get the clock offset, choose the one
489 // with the minimum gap in measurements.
490 const int tries = 3;
491 nsecs_t bestGap, measured;
492 for (int i = 0; i < tries; ++i) {
493 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
494 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
495 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
496 const nsecs_t gap = tmono2 - tmono;
497 if (i == 0 || gap < bestGap) {
498 bestGap = gap;
499 measured = tbase - ((tmono + tmono2) >> 1);
500 }
501 }
502 return measured;
503}
504
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800505hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
506 int frameworkFormat) {
507 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
508}
509
510DataspaceFlags Camera3Device::mapToHidlDataspace(
511 android_dataspace dataSpace) {
512 return dataSpace;
513}
514
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700515BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100516 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700517 return usage;
518}
519
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800520StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
521 switch (rotation) {
522 case CAMERA3_STREAM_ROTATION_0:
523 return StreamRotation::ROTATION_0;
524 case CAMERA3_STREAM_ROTATION_90:
525 return StreamRotation::ROTATION_90;
526 case CAMERA3_STREAM_ROTATION_180:
527 return StreamRotation::ROTATION_180;
528 case CAMERA3_STREAM_ROTATION_270:
529 return StreamRotation::ROTATION_270;
530 }
531 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
532 return StreamRotation::ROTATION_0;
533}
534
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800535status_t Camera3Device::mapToStreamConfigurationMode(
536 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
537 if (mode == nullptr) return BAD_VALUE;
538 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
539 switch(operationMode) {
540 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
541 *mode = StreamConfigurationMode::NORMAL_MODE;
542 break;
543 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
544 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
545 break;
546 default:
547 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
548 return BAD_VALUE;
549 }
550 } else {
551 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800552 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800553 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800554}
555
556camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
557 switch (status) {
558 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
559 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
560 }
561 return CAMERA3_BUFFER_STATUS_ERROR;
562}
563
564int Camera3Device::mapToFrameworkFormat(
565 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
566 return static_cast<uint32_t>(pixelFormat);
567}
568
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700569android_dataspace Camera3Device::mapToFrameworkDataspace(
570 DataspaceFlags dataSpace) {
571 return static_cast<android_dataspace>(dataSpace);
572}
573
Emilian Peev050f5dc2017-05-18 14:43:56 +0100574uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700575 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700576 return usage;
577}
578
Emilian Peev050f5dc2017-05-18 14:43:56 +0100579uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700580 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700581 return usage;
582}
583
Zhijun Hef7da0962014-04-24 13:27:56 -0700584ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700585 // Get max jpeg size (area-wise).
586 Size maxJpegResolution = getMaxJpegResolution();
587 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800588 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
589 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700590 return BAD_VALUE;
591 }
592
Zhijun Hef7da0962014-04-24 13:27:56 -0700593 // Get max jpeg buffer size
594 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700595 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
596 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800597 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
598 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700599 return BAD_VALUE;
600 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700601 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800602 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700603
604 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700605 float scaleFactor = ((float) (width * height)) /
606 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800607 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
608 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700609 if (jpegBufferSize > maxJpegBufferSize) {
610 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700611 }
612
613 return jpegBufferSize;
614}
615
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700616ssize_t Camera3Device::getPointCloudBufferSize() const {
617 const int FLOATS_PER_POINT=4;
618 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
619 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800620 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
621 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700622 return BAD_VALUE;
623 }
624 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
625 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
626 return maxBytesForPointCloud;
627}
628
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800629ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800630 const int PER_CONFIGURATION_SIZE = 3;
631 const int WIDTH_OFFSET = 0;
632 const int HEIGHT_OFFSET = 1;
633 const int SIZE_OFFSET = 2;
634 camera_metadata_ro_entry rawOpaqueSizes =
635 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800636 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800637 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800638 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
639 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800640 return BAD_VALUE;
641 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700642
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800643 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
644 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
645 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
646 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
647 }
648 }
649
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800650 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
651 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800652 return BAD_VALUE;
653}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700654
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800655status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
656 ATRACE_CALL();
657 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700658
659 // Try to lock, but continue in case of failure (to avoid blocking in
660 // deadlocks)
661 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
662 bool gotLock = tryLockSpinRightRound(mLock);
663
664 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800665 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
666 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700667 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800668 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
669 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700670
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800671 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700672
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800673 String16 templatesOption("-t");
674 int n = args.size();
675 for (int i = 0; i < n; i++) {
676 if (args[i] == templatesOption) {
677 dumpTemplates = true;
678 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000679 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700680 if (i + 1 < n) {
681 String8 monitorTags = String8(args[i + 1]);
682 if (monitorTags == "off") {
683 mTagMonitor.disableMonitoring();
684 } else {
685 mTagMonitor.parseTagsToMonitor(monitorTags);
686 }
687 } else {
688 mTagMonitor.disableMonitoring();
689 }
690 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800691 }
692
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800693 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800694
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800695 const char *status =
696 mStatus == STATUS_ERROR ? "ERROR" :
697 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700698 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
699 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800700 mStatus == STATUS_ACTIVE ? "ACTIVE" :
701 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700702
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800703 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700704 if (mStatus == STATUS_ERROR) {
705 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
706 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800707 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800708 const char *mode =
709 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
710 mOperatingMode == static_cast<int>(
711 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
712 "CUSTOM";
713 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800714
715 if (mInputStream != NULL) {
716 write(fd, lines.string(), lines.size());
717 mInputStream->dump(fd, args);
718 } else {
719 lines.appendFormat(" No input stream.\n");
720 write(fd, lines.string(), lines.size());
721 }
722 for (size_t i = 0; i < mOutputStreams.size(); i++) {
723 mOutputStreams[i]->dump(fd,args);
724 }
725
Zhijun He431503c2016-03-07 17:30:16 -0800726 if (mBufferManager != NULL) {
727 lines = String8(" Camera3 Buffer Manager:\n");
728 write(fd, lines.string(), lines.size());
729 mBufferManager->dump(fd, args);
730 }
Zhijun He125684a2015-12-26 15:07:30 -0800731
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700732 lines = String8(" In-flight requests:\n");
733 if (mInFlightMap.size() == 0) {
734 lines.append(" None\n");
735 } else {
736 for (size_t i = 0; i < mInFlightMap.size(); i++) {
737 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700738 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700739 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800740 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700741 r.numBuffersLeft);
742 }
743 }
744 write(fd, lines.string(), lines.size());
745
Shuzhen Wang686f6442017-06-20 16:16:04 -0700746 if (mRequestThread != NULL) {
747 mRequestThread->dumpCaptureRequestLatency(fd,
748 " ProcessCaptureRequest latency histogram:");
749 }
750
Igor Murashkin1e479c02013-09-06 16:55:14 -0700751 {
752 lines = String8(" Last request sent:\n");
753 write(fd, lines.string(), lines.size());
754
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700755 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700756 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
757 }
758
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800759 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800760 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800761 "TEMPLATE_PREVIEW",
762 "TEMPLATE_STILL_CAPTURE",
763 "TEMPLATE_VIDEO_RECORD",
764 "TEMPLATE_VIDEO_SNAPSHOT",
765 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800766 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800767 };
768
769 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800770 camera_metadata_t *templateRequest = nullptr;
771 mInterface->constructDefaultRequestSettings(
772 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800773 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800774 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800775 lines.append(" Not supported\n");
776 write(fd, lines.string(), lines.size());
777 } else {
778 write(fd, lines.string(), lines.size());
779 dump_indented_camera_metadata(templateRequest,
780 fd, /*verbosity*/2, /*indentation*/8);
781 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800782 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800783 }
784 }
785
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700786 mTagMonitor.dumpMonitoredMetadata(fd);
787
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800788 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800789 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800790 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800791 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800792 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800793
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700794 if (gotLock) mLock.unlock();
795 if (gotInterfaceLock) mInterfaceLock.unlock();
796
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800797 return OK;
798}
799
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700800const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800801 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800802 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
803 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700804 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800805 mStatus == STATUS_ERROR ?
806 "when in error state" : "before init");
807 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700808 if (physicalId.isEmpty()) {
809 return mDeviceInfo;
810 } else {
811 std::string id(physicalId.c_str());
812 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
813 return mPhysicalDeviceInfoMap.at(id);
814 } else {
815 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
816 return mDeviceInfo;
817 }
818 }
819}
820
821const CameraMetadata& Camera3Device::info() const {
822 String8 emptyId;
823 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800824}
825
Jianing Wei90e59c92014-03-12 18:29:36 -0700826status_t Camera3Device::checkStatusOkToCaptureLocked() {
827 switch (mStatus) {
828 case STATUS_ERROR:
829 CLOGE("Device has encountered a serious error");
830 return INVALID_OPERATION;
831 case STATUS_UNINITIALIZED:
832 CLOGE("Device not initialized");
833 return INVALID_OPERATION;
834 case STATUS_UNCONFIGURED:
835 case STATUS_CONFIGURED:
836 case STATUS_ACTIVE:
837 // OK
838 break;
839 default:
840 SET_ERR_L("Unexpected status: %d", mStatus);
841 return INVALID_OPERATION;
842 }
843 return OK;
844}
845
846status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000847 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700848 const std::list<const SurfaceMap> &surfaceMaps,
849 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700850 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700851 if (requestList == NULL) {
852 CLOGE("requestList cannot be NULL.");
853 return BAD_VALUE;
854 }
855
Jianing Weicb0652e2014-03-12 18:29:36 -0700856 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000857 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
859 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
860 ++metadataIt, ++surfaceMapIt) {
861 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700862 if (newRequest == 0) {
863 CLOGE("Can't create capture request");
864 return BAD_VALUE;
865 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700866
Shuzhen Wang9d066012016-09-30 11:30:20 -0700867 newRequest->mRepeating = repeating;
868
Jianing Weicb0652e2014-03-12 18:29:36 -0700869 // Setup burst Id and request Id
870 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000871 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
872 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700873 CLOGE("RequestID entry exists; but must not be empty in metadata");
874 return BAD_VALUE;
875 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000876 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
877 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700878 } else {
879 CLOGE("RequestID does not exist in metadata");
880 return BAD_VALUE;
881 }
882
Jianing Wei90e59c92014-03-12 18:29:36 -0700883 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700884
885 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700886 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700887 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
888 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
889 return BAD_VALUE;
890 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700891
892 // Setup batch size if this is a high speed video recording request.
893 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
894 auto firstRequest = requestList->begin();
895 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
896 if (outputStream->isVideoStream()) {
897 (*firstRequest)->mBatchSize = requestList->size();
898 break;
899 }
900 }
901 }
902
Jianing Wei90e59c92014-03-12 18:29:36 -0700903 return OK;
904}
905
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800906status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800907 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800908
Emilian Peevaebbe412018-01-15 13:53:24 +0000909 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700910 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000911 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700912
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800913 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700914}
915
Emilian Peevaebbe412018-01-15 13:53:24 +0000916void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700917 std::list<const SurfaceMap>& surfaceMaps,
918 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000919 PhysicalCameraSettingsList requestList;
920 requestList.push_back({std::string(getId().string()), request});
921 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700922
923 SurfaceMap surfaceMap;
924 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
925 // With no surface list passed in, stream and surface will have 1-to-1
926 // mapping. So the surface index is 0 for each stream in the surfaceMap.
927 for (size_t i = 0; i < streams.count; i++) {
928 surfaceMap[streams.data.i32[i]].push_back(0);
929 }
930 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800931}
932
Jianing Wei90e59c92014-03-12 18:29:36 -0700933status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000934 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700935 const std::list<const SurfaceMap> &surfaceMaps,
936 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700937 /*out*/
938 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700939 ATRACE_CALL();
940 Mutex::Autolock il(mInterfaceLock);
941 Mutex::Autolock l(mLock);
942
943 status_t res = checkStatusOkToCaptureLocked();
944 if (res != OK) {
945 // error logged by previous call
946 return res;
947 }
948
949 RequestList requestList;
950
Shuzhen Wang0129d522016-10-30 22:43:41 -0700951 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
952 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700953 if (res != OK) {
954 // error logged by previous call
955 return res;
956 }
957
958 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700959 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700960 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700961 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700962 }
963
964 if (res == OK) {
965 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
966 if (res != OK) {
967 SET_ERR_L("Can't transition to active in %f seconds!",
968 kActiveTimeout/1e9);
969 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800970 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700971 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700972 } else {
973 CLOGE("Cannot queue request. Impossible.");
974 return BAD_VALUE;
975 }
976
977 return res;
978}
979
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700980hardware::Return<void> Camera3Device::requestStreamBuffers(
981 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
982 requestStreamBuffers_cb _hidl_cb) {
983 using hardware::camera::device::V3_5::BufferRequestStatus;
984 using hardware::camera::device::V3_5::StreamBufferRet;
985 using hardware::camera::device::V3_5::StreamBufferRequestError;
986
987 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
988
989 hardware::hidl_vec<StreamBufferRet> bufRets;
990 if (!mUseHalBufManager) {
991 ALOGE("%s: Camera %s does not support HAL buffer management",
992 __FUNCTION__, mId.string());
993 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
994 return hardware::Void();
995 }
996
997 SortedVector<int32_t> streamIds;
998 ssize_t sz = streamIds.setCapacity(bufReqs.size());
999 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
1000 ALOGE("%s: failed to allocate memory for %zu buffer requests",
1001 __FUNCTION__, bufReqs.size());
1002 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1003 return hardware::Void();
1004 }
1005
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001006 if (bufReqs.size() > mOutputStreams.size()) {
1007 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
1008 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
1009 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1010 return hardware::Void();
1011 }
1012
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001013 // Check for repeated streamId
1014 for (const auto& bufReq : bufReqs) {
1015 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
1016 ALOGE("%s: Stream %d appear multiple times in buffer requests",
1017 __FUNCTION__, bufReq.streamId);
1018 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1019 return hardware::Void();
1020 }
1021 streamIds.add(bufReq.streamId);
1022 }
1023
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001024 if (!mRequestBufferSM.startRequestBuffer()) {
1025 ALOGE("%s: request buffer disallowed while camera service is configuring",
1026 __FUNCTION__);
1027 _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001028 return hardware::Void();
1029 }
1030
1031 bufRets.resize(bufReqs.size());
1032
1033 bool allReqsSucceeds = true;
1034 bool oneReqSucceeds = false;
1035 for (size_t i = 0; i < bufReqs.size(); i++) {
1036 const auto& bufReq = bufReqs[i];
1037 auto& bufRet = bufRets[i];
1038 int32_t streamId = bufReq.streamId;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001039 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
1040 if (outputStream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001041 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
1042 hardware::hidl_vec<StreamBufferRet> emptyBufRets;
1043 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001044 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001045 return hardware::Void();
1046 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001047
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001048 if (outputStream->isAbandoned()) {
1049 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1050 allReqsSucceeds = false;
1051 continue;
1052 }
1053
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001054 bufRet.streamId = streamId;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001055 size_t handOutBufferCount = outputStream->getOutstandingBuffersCount();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001056 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001057 size_t totalHandout = handOutBufferCount + numBuffersRequested;
1058 uint32_t maxBuffers = outputStream->asHalStream()->max_buffers;
1059 if (totalHandout > maxBuffers) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001060 // Not able to allocate enough buffer. Exit early for this stream
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001061 ALOGE("%s: request too much buffers for stream %d: at HAL: %zu + requesting: %d"
1062 " > max: %d", __FUNCTION__, streamId, handOutBufferCount,
1063 numBuffersRequested, maxBuffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001064 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1065 allReqsSucceeds = false;
1066 continue;
1067 }
1068
1069 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1070 bool currentReqSucceeds = true;
1071 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1072 size_t numAllocatedBuffers = 0;
1073 size_t numPushedInflightBuffers = 0;
1074 for (size_t b = 0; b < numBuffersRequested; b++) {
1075 camera3_stream_buffer_t& sb = streamBuffers[b];
1076 // Since this method can run concurrently with request thread
1077 // We need to update the wait duration everytime we call getbuffer
1078 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1079 status_t res = outputStream->getBuffer(&sb, waitDuration);
1080 if (res != OK) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001081 if (res == NO_INIT || res == DEAD_OBJECT) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001082 ALOGV("%s: Can't get output buffer for stream %d: %s (%d)",
1083 __FUNCTION__, streamId, strerror(-res), res);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001084 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001085 } else {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001086 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1087 __FUNCTION__, streamId, strerror(-res), res);
1088 if (res == TIMED_OUT || res == NO_MEMORY) {
1089 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1090 } else {
1091 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1092 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001093 }
1094 currentReqSucceeds = false;
1095 break;
1096 }
1097 numAllocatedBuffers++;
1098
1099 buffer_handle_t *buffer = sb.buffer;
1100 auto pair = mInterface->getBufferId(*buffer, streamId);
1101 bool isNewBuffer = pair.first;
1102 uint64_t bufferId = pair.second;
1103 StreamBuffer& hBuf = tmpRetBuffers[b];
1104
1105 hBuf.streamId = streamId;
1106 hBuf.bufferId = bufferId;
1107 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1108 hBuf.status = BufferStatus::OK;
1109 hBuf.releaseFence = nullptr;
1110
1111 native_handle_t *acquireFence = nullptr;
1112 if (sb.acquire_fence != -1) {
1113 acquireFence = native_handle_create(1,0);
1114 acquireFence->data[0] = sb.acquire_fence;
1115 }
1116 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1117 hBuf.releaseFence = nullptr;
1118
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08001119 res = mInterface->pushInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001120 if (res != OK) {
1121 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1122 __FUNCTION__, streamId, strerror(-res), res);
1123 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1124 currentReqSucceeds = false;
1125 break;
1126 }
1127 numPushedInflightBuffers++;
1128 }
1129 if (currentReqSucceeds) {
1130 bufRet.val.buffers(std::move(tmpRetBuffers));
1131 oneReqSucceeds = true;
1132 } else {
1133 allReqsSucceeds = false;
1134 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1135 StreamBuffer& hBuf = tmpRetBuffers[b];
1136 buffer_handle_t* buffer;
1137 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1138 if (res != OK) {
1139 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1140 __FUNCTION__, streamId, strerror(-res), res);
1141 }
1142 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001143 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1144 camera3_stream_buffer_t& sb = streamBuffers[b];
1145 sb.acquire_fence = -1;
1146 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1147 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001148 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1149 }
1150 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001151
1152 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1153 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1154 BufferRequestStatus::FAILED_UNKNOWN,
1155 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001156 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001157 return hardware::Void();
1158}
1159
1160hardware::Return<void> Camera3Device::returnStreamBuffers(
1161 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1162 if (!mUseHalBufManager) {
1163 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1164 __FUNCTION__, mId.string());
1165 return hardware::Void();
1166 }
1167
1168 for (const auto& buf : buffers) {
1169 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1170 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1171 continue;
1172 }
1173
1174 buffer_handle_t* buffer;
1175 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1176
1177 if (res != OK) {
1178 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1179 __FUNCTION__, buf.bufferId, buf.streamId);
1180 continue;
1181 }
1182
1183 camera3_stream_buffer_t streamBuffer;
1184 streamBuffer.buffer = buffer;
1185 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1186 streamBuffer.acquire_fence = -1;
1187 streamBuffer.release_fence = -1;
1188
1189 if (buf.releaseFence == nullptr) {
1190 streamBuffer.release_fence = -1;
1191 } else if (buf.releaseFence->numFds == 1) {
1192 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1193 } else {
1194 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1195 __FUNCTION__, buf.releaseFence->numFds);
1196 continue;
1197 }
1198
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001199 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1200 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001201 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1202 continue;
1203 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001204 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001205 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1206 }
1207 return hardware::Void();
1208}
1209
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001210hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001211 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001212 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001213 // Ideally we should grab mLock, but that can lead to deadlock, and
1214 // it's not super important to get up to date value of mStatus for this
1215 // warning print, hence skipping the lock here
1216 if (mStatus == STATUS_ERROR) {
1217 // Per API contract, HAL should act as closed after device error
1218 // But mStatus can be set to error by framework as well, so just log
1219 // a warning here.
1220 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001221 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001222
1223 if (mProcessCaptureResultLock.tryLock() != OK) {
1224 // This should never happen; it indicates a wrong client implementation
1225 // that doesn't follow the contract. But, we can be tolerant here.
1226 ALOGE("%s: callback overlapped! waiting 1s...",
1227 __FUNCTION__);
1228 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1229 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1230 __FUNCTION__);
1231 // really don't know what to do, so bail out.
1232 return hardware::Void();
1233 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001234 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001235 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001236 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001237 }
1238 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001239 return hardware::Void();
1240}
1241
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001242// Only one processCaptureResult should be called at a time, so
1243// the locks won't block. The locks are present here simply to enforce this.
1244hardware::Return<void> Camera3Device::processCaptureResult(
1245 const hardware::hidl_vec<
1246 hardware::camera::device::V3_2::CaptureResult>& results) {
1247 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1248
1249 // Ideally we should grab mLock, but that can lead to deadlock, and
1250 // it's not super important to get up to date value of mStatus for this
1251 // warning print, hence skipping the lock here
1252 if (mStatus == STATUS_ERROR) {
1253 // Per API contract, HAL should act as closed after device error
1254 // But mStatus can be set to error by framework as well, so just log
1255 // a warning here.
1256 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1257 }
1258
1259 if (mProcessCaptureResultLock.tryLock() != OK) {
1260 // This should never happen; it indicates a wrong client implementation
1261 // that doesn't follow the contract. But, we can be tolerant here.
1262 ALOGE("%s: callback overlapped! waiting 1s...",
1263 __FUNCTION__);
1264 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1265 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1266 __FUNCTION__);
1267 // really don't know what to do, so bail out.
1268 return hardware::Void();
1269 }
1270 }
1271 for (const auto& result : results) {
1272 processOneCaptureResultLocked(result, noPhysMetadata);
1273 }
1274 mProcessCaptureResultLock.unlock();
1275 return hardware::Void();
1276}
1277
1278status_t Camera3Device::readOneCameraMetadataLocked(
1279 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1280 const hardware::camera::device::V3_2::CameraMetadata& result) {
1281 if (fmqResultSize > 0) {
1282 resultMetadata.resize(fmqResultSize);
1283 if (mResultMetadataQueue == nullptr) {
1284 return NO_MEMORY; // logged in initialize()
1285 }
1286 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1287 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1288 __FUNCTION__, fmqResultSize);
1289 return INVALID_OPERATION;
1290 }
1291 } else {
1292 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1293 result.size());
1294 }
1295
1296 if (resultMetadata.size() != 0) {
1297 status_t res;
1298 const camera_metadata_t* metadata =
1299 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1300 size_t expected_metadata_size = resultMetadata.size();
1301 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1302 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1303 __FUNCTION__, strerror(-res), res);
1304 return INVALID_OPERATION;
1305 }
1306 }
1307
1308 return OK;
1309}
1310
Yifan Honga640c5a2017-04-12 16:30:31 -07001311void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001312 const hardware::camera::device::V3_2::CaptureResult& result,
1313 const hardware::hidl_vec<
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001314 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadata) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001315 camera3_capture_result r;
1316 status_t res;
1317 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001318
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001319 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001320 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001321 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1322 if (res != OK) {
1323 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1324 __FUNCTION__, result.frameNumber);
1325 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001326 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001327 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001328
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001329 // Read and validate physical camera metadata
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001330 size_t physResultCount = physicalCameraMetadata.size();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001331 std::vector<const char*> physCamIds(physResultCount);
1332 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1333 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1334 physResultMetadata.resize(physResultCount);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001335 for (size_t i = 0; i < physicalCameraMetadata.size(); i++) {
1336 res = readOneCameraMetadataLocked(physicalCameraMetadata[i].fmqMetadataSize,
1337 physResultMetadata[i], physicalCameraMetadata[i].metadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001338 if (res != OK) {
1339 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1340 __FUNCTION__, result.frameNumber,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001341 physicalCameraMetadata[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001342 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001343 }
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001344 physCamIds[i] = physicalCameraMetadata[i].physicalCameraId.c_str();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001345 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1346 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001347 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001348 r.num_physcam_metadata = physResultCount;
1349 r.physcam_ids = physCamIds.data();
1350 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001351
1352 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1353 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1354 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1355 auto& bDst = outputBuffers[i];
1356 const StreamBuffer &bSrc = result.outputBuffers[i];
1357
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001358 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1359 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001360 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1361 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001362 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001363 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001364 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001365
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001366 bool noBufferReturned = false;
1367 buffer_handle_t *buffer = nullptr;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001368 if (mUseHalBufManager) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001369 // This is suspicious most of the time but can be correct during flush where HAL
1370 // has to return capture result before a buffer is requested
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001371 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001372 if (bSrc.status == BufferStatus::OK) {
1373 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1374 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1375 // Still proceeds so other buffers can be returned
1376 }
1377 noBufferReturned = true;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001378 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001379 if (noBufferReturned) {
1380 res = OK;
1381 } else {
1382 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1383 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001384 } else {
1385 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1386 }
1387
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001388 if (res != OK) {
1389 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1390 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001391 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001392 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001393
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001394 bDst.buffer = buffer;
1395 bDst.status = mapHidlBufferStatus(bSrc.status);
1396 bDst.acquire_fence = -1;
1397 if (bSrc.releaseFence == nullptr) {
1398 bDst.release_fence = -1;
1399 } else if (bSrc.releaseFence->numFds == 1) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001400 if (noBufferReturned) {
1401 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
1402 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001403 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1404 } else {
1405 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1406 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001407 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001408 }
1409 }
1410 r.num_output_buffers = outputBuffers.size();
1411 r.output_buffers = outputBuffers.data();
1412
1413 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001414 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001415 r.input_buffer = nullptr;
1416 } else {
1417 if (mInputStream->getId() != result.inputBuffer.streamId) {
1418 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1419 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001420 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001421 }
1422 inputBuffer.stream = mInputStream->asHalStream();
1423 buffer_handle_t *buffer;
1424 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1425 &buffer);
1426 if (res != OK) {
1427 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1428 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001429 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001430 }
1431 inputBuffer.buffer = buffer;
1432 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1433 inputBuffer.acquire_fence = -1;
1434 if (result.inputBuffer.releaseFence == nullptr) {
1435 inputBuffer.release_fence = -1;
1436 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1437 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1438 } else {
1439 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1440 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001441 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001442 }
1443 r.input_buffer = &inputBuffer;
1444 }
1445
1446 r.partial_result = result.partialResult;
1447
1448 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001449}
1450
1451hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001452 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001453 // Ideally we should grab mLock, but that can lead to deadlock, and
1454 // it's not super important to get up to date value of mStatus for this
1455 // warning print, hence skipping the lock here
1456 if (mStatus == STATUS_ERROR) {
1457 // Per API contract, HAL should act as closed after device error
1458 // But mStatus can be set to error by framework as well, so just log
1459 // a warning here.
1460 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001461 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001462
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001463 for (const auto& msg : msgs) {
1464 notify(msg);
1465 }
1466 return hardware::Void();
1467}
1468
1469void Camera3Device::notify(
1470 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1471
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001472 camera3_notify_msg m;
1473 switch (msg.type) {
1474 case MsgType::ERROR:
1475 m.type = CAMERA3_MSG_ERROR;
1476 m.message.error.frame_number = msg.msg.error.frameNumber;
1477 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001478 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1479 if (stream == nullptr) {
1480 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1481 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001482 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001483 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001484 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001485 } else {
1486 m.message.error.error_stream = nullptr;
1487 }
1488 switch (msg.msg.error.errorCode) {
1489 case ErrorCode::ERROR_DEVICE:
1490 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1491 break;
1492 case ErrorCode::ERROR_REQUEST:
1493 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1494 break;
1495 case ErrorCode::ERROR_RESULT:
1496 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1497 break;
1498 case ErrorCode::ERROR_BUFFER:
1499 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1500 break;
1501 }
1502 break;
1503 case MsgType::SHUTTER:
1504 m.type = CAMERA3_MSG_SHUTTER;
1505 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1506 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1507 break;
1508 }
1509 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001510}
1511
Emilian Peevaebbe412018-01-15 13:53:24 +00001512status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001513 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001514 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001515 ATRACE_CALL();
1516
Emilian Peevaebbe412018-01-15 13:53:24 +00001517 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001518}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001519
Jianing Weicb0652e2014-03-12 18:29:36 -07001520status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1521 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001522 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001523
Emilian Peevaebbe412018-01-15 13:53:24 +00001524 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001525 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001526 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001527
Emilian Peevaebbe412018-01-15 13:53:24 +00001528 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001529 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530}
1531
Emilian Peevaebbe412018-01-15 13:53:24 +00001532status_t Camera3Device::setStreamingRequestList(
1533 const List<const PhysicalCameraSettingsList> &requestsList,
1534 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001535 ATRACE_CALL();
1536
Emilian Peevaebbe412018-01-15 13:53:24 +00001537 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001538}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539
1540sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001541 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 status_t res;
1543
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001545 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1546 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001547 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1548 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001549 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001551 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001553 } else if (mStatus == STATUS_UNCONFIGURED) {
1554 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001555 CLOGE("No streams configured");
1556 return NULL;
1557 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 }
1559
Shuzhen Wang0129d522016-10-30 22:43:41 -07001560 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001561 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001562}
1563
Jianing Weicb0652e2014-03-12 18:29:36 -07001564status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001565 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001566 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001567 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001568
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 switch (mStatus) {
1570 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001571 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 return INVALID_OPERATION;
1573 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001574 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001576 case STATUS_UNCONFIGURED:
1577 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001578 case STATUS_ACTIVE:
1579 // OK
1580 break;
1581 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001582 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583 return INVALID_OPERATION;
1584 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001585 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001586
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001587 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001588}
1589
1590status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1591 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001593
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001594 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001595}
1596
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001597status_t Camera3Device::createInputStream(
1598 uint32_t width, uint32_t height, int format, int *id) {
1599 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001600 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001601 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001602 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001603 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1604 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001605
1606 status_t res;
1607 bool wasActive = false;
1608
1609 switch (mStatus) {
1610 case STATUS_ERROR:
1611 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1612 return INVALID_OPERATION;
1613 case STATUS_UNINITIALIZED:
1614 ALOGE("%s: Device not initialized", __FUNCTION__);
1615 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001616 case STATUS_UNCONFIGURED:
1617 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001618 // OK
1619 break;
1620 case STATUS_ACTIVE:
1621 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001622 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001623 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001624 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001625 return res;
1626 }
1627 wasActive = true;
1628 break;
1629 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001630 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001631 return INVALID_OPERATION;
1632 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001633 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001634
1635 if (mInputStream != 0) {
1636 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1637 return INVALID_OPERATION;
1638 }
1639
1640 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1641 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001642 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001643
1644 mInputStream = newStream;
1645
1646 *id = mNextStreamId++;
1647
1648 // Continue captures if active at start
1649 if (wasActive) {
1650 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001651 // Reuse current operating mode and session parameters for new stream config
1652 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001653 if (res != OK) {
1654 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1655 __FUNCTION__, mNextStreamId, strerror(-res), res);
1656 return res;
1657 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001658 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001659 }
1660
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001661 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001662 return OK;
1663}
1664
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001665status_t Camera3Device::StreamSet::add(
1666 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1667 if (stream == nullptr) {
1668 ALOGE("%s: cannot add null stream", __FUNCTION__);
1669 return BAD_VALUE;
1670 }
1671 std::lock_guard<std::mutex> lock(mLock);
1672 return mData.add(streamId, stream);
1673}
1674
1675ssize_t Camera3Device::StreamSet::remove(int streamId) {
1676 std::lock_guard<std::mutex> lock(mLock);
1677 return mData.removeItem(streamId);
1678}
1679
1680sp<camera3::Camera3OutputStreamInterface>
1681Camera3Device::StreamSet::get(int streamId) {
1682 std::lock_guard<std::mutex> lock(mLock);
1683 ssize_t idx = mData.indexOfKey(streamId);
1684 if (idx == NAME_NOT_FOUND) {
1685 return nullptr;
1686 }
1687 return mData.editValueAt(idx);
1688}
1689
1690sp<camera3::Camera3OutputStreamInterface>
1691Camera3Device::StreamSet::operator[] (size_t index) {
1692 std::lock_guard<std::mutex> lock(mLock);
1693 return mData.editValueAt(index);
1694}
1695
1696size_t Camera3Device::StreamSet::size() const {
1697 std::lock_guard<std::mutex> lock(mLock);
1698 return mData.size();
1699}
1700
1701void Camera3Device::StreamSet::clear() {
1702 std::lock_guard<std::mutex> lock(mLock);
1703 return mData.clear();
1704}
1705
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001706std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1707 std::lock_guard<std::mutex> lock(mLock);
1708 std::vector<int> streamIds(mData.size());
1709 for (size_t i = 0; i < mData.size(); i++) {
1710 streamIds[i] = mData.keyAt(i);
1711 }
1712 return streamIds;
1713}
1714
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001715status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001716 uint32_t width, uint32_t height, int format,
1717 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001718 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001719 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001720 ATRACE_CALL();
1721
1722 if (consumer == nullptr) {
1723 ALOGE("%s: consumer must not be null", __FUNCTION__);
1724 return BAD_VALUE;
1725 }
1726
1727 std::vector<sp<Surface>> consumers;
1728 consumers.push_back(consumer);
1729
1730 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001731 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1732 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001733}
1734
1735status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1736 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1737 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001738 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001739 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001740 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001741
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001742 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001743 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001744 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001745 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001746 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1747 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1748 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001749
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001750 status_t res;
1751 bool wasActive = false;
1752
1753 switch (mStatus) {
1754 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001755 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001756 return INVALID_OPERATION;
1757 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001758 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001759 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001760 case STATUS_UNCONFIGURED:
1761 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001762 // OK
1763 break;
1764 case STATUS_ACTIVE:
1765 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001766 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001767 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001768 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001769 return res;
1770 }
1771 wasActive = true;
1772 break;
1773 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001774 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001775 return INVALID_OPERATION;
1776 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001777 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001778
1779 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001780
Shuzhen Wang0129d522016-10-30 22:43:41 -07001781 if (consumers.size() == 0 && !hasDeferredConsumer) {
1782 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1783 return BAD_VALUE;
1784 }
Zhijun He5d677d12016-05-29 16:52:39 -07001785
Shuzhen Wang0129d522016-10-30 22:43:41 -07001786 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001787 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1788 return BAD_VALUE;
1789 }
1790
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001791 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001792 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001793 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001794 blobBufferSize = getPointCloudBufferSize();
1795 if (blobBufferSize <= 0) {
1796 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1797 return BAD_VALUE;
1798 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001799 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1800 blobBufferSize = width * height;
1801 } else {
1802 blobBufferSize = getJpegBufferSize(width, height);
1803 if (blobBufferSize <= 0) {
1804 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1805 return BAD_VALUE;
1806 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001807 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001808 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001809 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001810 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001811 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1812 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1813 if (rawOpaqueBufferSize <= 0) {
1814 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1815 return BAD_VALUE;
1816 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001817 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001818 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001819 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001820 } else if (isShared) {
1821 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1822 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001823 mTimestampOffset, physicalCameraId, streamSetId,
1824 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001825 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001826 newStream = new Camera3OutputStream(mNextStreamId,
1827 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001828 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001829 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001830 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001831 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001832 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001833 }
Emilian Peev40ead602017-09-26 15:46:36 +01001834
1835 size_t consumerCount = consumers.size();
1836 for (size_t i = 0; i < consumerCount; i++) {
1837 int id = newStream->getSurfaceId(consumers[i]);
1838 if (id < 0) {
1839 SET_ERR_L("Invalid surface id");
1840 return BAD_VALUE;
1841 }
1842 if (surfaceIds != nullptr) {
1843 surfaceIds->push_back(id);
1844 }
1845 }
1846
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001847 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001848
Emilian Peev08dd2452017-04-06 16:55:14 +01001849 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001850
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001851 res = mOutputStreams.add(mNextStreamId, newStream);
1852 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001853 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001854 return res;
1855 }
1856
1857 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001858 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001859
1860 // Continue captures if active at start
1861 if (wasActive) {
1862 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001863 // Reuse current operating mode and session parameters for new stream config
1864 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001865 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001866 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1867 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001868 return res;
1869 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001870 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001871 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001872 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001873 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001874}
1875
Emilian Peev710c1422017-08-30 11:19:38 +01001876status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001877 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001878 if (nullptr == streamInfo) {
1879 return BAD_VALUE;
1880 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001881 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001882 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001883
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001884 switch (mStatus) {
1885 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001886 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001887 return INVALID_OPERATION;
1888 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001889 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001890 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001891 case STATUS_UNCONFIGURED:
1892 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001893 case STATUS_ACTIVE:
1894 // OK
1895 break;
1896 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001897 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001898 return INVALID_OPERATION;
1899 }
1900
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001901 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1902 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001903 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001904 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001905 }
1906
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001907 streamInfo->width = stream->getWidth();
1908 streamInfo->height = stream->getHeight();
1909 streamInfo->format = stream->getFormat();
1910 streamInfo->dataSpace = stream->getDataSpace();
1911 streamInfo->formatOverridden = stream->isFormatOverridden();
1912 streamInfo->originalFormat = stream->getOriginalFormat();
1913 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1914 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001915 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001916}
1917
1918status_t Camera3Device::setStreamTransform(int id,
1919 int transform) {
1920 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001921 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001922 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001923
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001924 switch (mStatus) {
1925 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001926 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001927 return INVALID_OPERATION;
1928 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001929 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001930 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001931 case STATUS_UNCONFIGURED:
1932 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001933 case STATUS_ACTIVE:
1934 // OK
1935 break;
1936 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001937 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001938 return INVALID_OPERATION;
1939 }
1940
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001941 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1942 if (stream == nullptr) {
1943 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001944 return BAD_VALUE;
1945 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001946 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001947}
1948
1949status_t Camera3Device::deleteStream(int id) {
1950 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001951 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001952 Mutex::Autolock l(mLock);
1953 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001954
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001955 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001956
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001957 // CameraDevice semantics require device to already be idle before
1958 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001959 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001960 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001961 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001962 }
1963
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001964 if (mStatus == STATUS_ERROR) {
1965 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1966 __FUNCTION__, mId.string());
1967 return -EBUSY;
1968 }
1969
Igor Murashkin2fba5842013-04-22 14:03:54 -07001970 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001971 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001972 if (mInputStream != NULL && id == mInputStream->getId()) {
1973 deletedStream = mInputStream;
1974 mInputStream.clear();
1975 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001976 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001977 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001978 return BAD_VALUE;
1979 }
Zhijun He5f446352014-01-22 09:49:33 -08001980 }
1981
1982 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001983 if (stream != nullptr) {
1984 deletedStream = stream;
1985 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001986 }
1987
1988 // Free up the stream endpoint so that it can be used by some other stream
1989 res = deletedStream->disconnect();
1990 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001991 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001992 // fall through since we want to still list the stream as deleted.
1993 }
1994 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001995 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001996
1997 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001998}
1999
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002000status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07002001 ATRACE_CALL();
2002 ALOGV("%s: E", __FUNCTION__);
2003
2004 Mutex::Autolock il(mInterfaceLock);
2005 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07002006
Emilian Peev811d2952018-05-25 11:08:40 +01002007 // In case the client doesn't include any session parameter, try a
2008 // speculative configuration using the values from the last cached
2009 // default request.
2010 if (sessionParams.isEmpty() &&
2011 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
2012 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
2013 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
2014 mLastTemplateId);
2015 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
2016 operatingMode);
2017 }
2018
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002019 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
2020}
2021
2022status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
2023 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002024 //Filter out any incoming session parameters
2025 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002026 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
2027 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002028 CameraMetadata filteredParams(availableSessionKeys.count);
2029 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2030 filteredParams.getAndLock());
2031 set_camera_metadata_vendor_id(meta, mVendorTagId);
2032 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002033 if (availableSessionKeys.count > 0) {
2034 for (size_t i = 0; i < availableSessionKeys.count; i++) {
2035 camera_metadata_ro_entry entry = params.find(
2036 availableSessionKeys.data.i32[i]);
2037 if (entry.count > 0) {
2038 filteredParams.update(entry);
2039 }
2040 }
2041 }
2042
2043 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07002044}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002045
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002046status_t Camera3Device::getInputBufferProducer(
2047 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002048 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002049 Mutex::Autolock il(mInterfaceLock);
2050 Mutex::Autolock l(mLock);
2051
2052 if (producer == NULL) {
2053 return BAD_VALUE;
2054 } else if (mInputStream == NULL) {
2055 return INVALID_OPERATION;
2056 }
2057
2058 return mInputStream->getInputBufferProducer(producer);
2059}
2060
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002061status_t Camera3Device::createDefaultRequest(int templateId,
2062 CameraMetadata *request) {
2063 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002064 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002065
2066 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2067 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002068 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002069 return BAD_VALUE;
2070 }
2071
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002072 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002073
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002074 {
2075 Mutex::Autolock l(mLock);
2076 switch (mStatus) {
2077 case STATUS_ERROR:
2078 CLOGE("Device has encountered a serious error");
2079 return INVALID_OPERATION;
2080 case STATUS_UNINITIALIZED:
2081 CLOGE("Device is not initialized!");
2082 return INVALID_OPERATION;
2083 case STATUS_UNCONFIGURED:
2084 case STATUS_CONFIGURED:
2085 case STATUS_ACTIVE:
2086 // OK
2087 break;
2088 default:
2089 SET_ERR_L("Unexpected status: %d", mStatus);
2090 return INVALID_OPERATION;
2091 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002092
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002093 if (!mRequestTemplateCache[templateId].isEmpty()) {
2094 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002095 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002096 return OK;
2097 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002098 }
2099
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002100 camera_metadata_t *rawRequest;
2101 status_t res = mInterface->constructDefaultRequestSettings(
2102 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002103
2104 {
2105 Mutex::Autolock l(mLock);
2106 if (res == BAD_VALUE) {
2107 ALOGI("%s: template %d is not supported on this camera device",
2108 __FUNCTION__, templateId);
2109 return res;
2110 } else if (res != OK) {
2111 CLOGE("Unable to construct request template %d: %s (%d)",
2112 templateId, strerror(-res), res);
2113 return res;
2114 }
2115
2116 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2117 mRequestTemplateCache[templateId].acquire(rawRequest);
2118
2119 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002120 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002121 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002122 return OK;
2123}
2124
2125status_t Camera3Device::waitUntilDrained() {
2126 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002127 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002128 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002129 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002130
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002131 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002132}
2133
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002134status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002135 switch (mStatus) {
2136 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002137 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002138 ALOGV("%s: Already idle", __FUNCTION__);
2139 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002140 case STATUS_CONFIGURED:
2141 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002142 case STATUS_ERROR:
2143 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002144 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002145 break;
2146 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002147 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002148 return INVALID_OPERATION;
2149 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002150 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2151 maxExpectedDuration);
2152 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002153 if (res != OK) {
2154 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2155 res);
2156 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002157 return res;
2158}
2159
Ruben Brunk183f0562015-08-12 12:55:02 -07002160
2161void Camera3Device::internalUpdateStatusLocked(Status status) {
2162 mStatus = status;
2163 mRecentStatusUpdates.add(mStatus);
2164 mStatusChanged.broadcast();
2165}
2166
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002167void Camera3Device::pauseStateNotify(bool enable) {
Jayant Chowdhary37eca242019-11-18 08:55:56 -08002168 // We must not hold mInterfaceLock here since this function is called from
2169 // RequestThread::threadLoop and holding mInterfaceLock could lead to
2170 // deadlocks (http://b/143513518)
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002171 Mutex::Autolock l(mLock);
2172
2173 mPauseStateNotify = enable;
2174}
2175
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002176// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002177status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08002178 if (mRequestThread.get() != nullptr) {
2179 mRequestThread->setPaused(true);
2180 } else {
2181 return NO_INIT;
2182 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002183
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002184 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2185 maxExpectedDuration);
2186 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002187 if (res != OK) {
2188 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002189 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002190 }
2191
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002192 return res;
2193}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002194
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002195// Resume after internalPauseAndWaitLocked
2196status_t Camera3Device::internalResumeLocked() {
2197 status_t res;
2198
2199 mRequestThread->setPaused(false);
2200
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002201 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2202 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002203 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2204 if (res != OK) {
2205 SET_ERR_L("Can't transition to active in %f seconds!",
2206 kActiveTimeout/1e9);
2207 }
2208 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002209 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002210}
2211
Ruben Brunk183f0562015-08-12 12:55:02 -07002212status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002213 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002214
2215 size_t startIndex = 0;
2216 if (mStatusWaiters == 0) {
2217 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2218 // this status list
2219 mRecentStatusUpdates.clear();
2220 } else {
2221 // If other threads are waiting on updates to this status list, set the position of the
2222 // first element that this list will check rather than clearing the list.
2223 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002224 }
2225
Ruben Brunk183f0562015-08-12 12:55:02 -07002226 mStatusWaiters++;
2227
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002228 if (!active && mUseHalBufManager) {
2229 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08002230 if (mStatus == STATUS_ACTIVE) {
2231 mRequestThread->signalPipelineDrain(streamIds);
2232 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002233 mRequestBufferSM.onWaitUntilIdle();
2234 }
2235
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002236 bool stateSeen = false;
2237 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002238 if (active == (mStatus == STATUS_ACTIVE)) {
2239 // Desired state is current
2240 break;
2241 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002242
2243 res = mStatusChanged.waitRelative(mLock, timeout);
2244 if (res != OK) break;
2245
Ruben Brunk183f0562015-08-12 12:55:02 -07002246 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2247 // transitions.
2248 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2249 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2250 __FUNCTION__);
2251
2252 // Encountered desired state since we began waiting
2253 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002254 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2255 stateSeen = true;
2256 break;
2257 }
2258 }
2259 } while (!stateSeen);
2260
Ruben Brunk183f0562015-08-12 12:55:02 -07002261 mStatusWaiters--;
2262
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002263 return res;
2264}
2265
2266
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002267status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002268 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002269 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002270
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002271 if (listener != NULL && mListener != NULL) {
2272 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2273 }
2274 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002275 mRequestThread->setNotificationListener(listener);
2276 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002277
2278 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002279}
2280
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002281bool Camera3Device::willNotify3A() {
2282 return false;
2283}
2284
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002285status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002286 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002287 status_t res;
2288 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002289
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002290 while (mResultQueue.empty()) {
2291 res = mResultSignal.waitRelative(mOutputLock, timeout);
2292 if (res == TIMED_OUT) {
2293 return res;
2294 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002295 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2296 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002297 return res;
2298 }
2299 }
2300 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002301}
2302
Jianing Weicb0652e2014-03-12 18:29:36 -07002303status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002304 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002305 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002306
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002307 if (mResultQueue.empty()) {
2308 return NOT_ENOUGH_DATA;
2309 }
2310
Jianing Weicb0652e2014-03-12 18:29:36 -07002311 if (frame == NULL) {
2312 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2313 return BAD_VALUE;
2314 }
2315
2316 CaptureResult &result = *(mResultQueue.begin());
2317 frame->mResultExtras = result.mResultExtras;
2318 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002319 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002320 mResultQueue.erase(mResultQueue.begin());
2321
2322 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002323}
2324
2325status_t Camera3Device::triggerAutofocus(uint32_t id) {
2326 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002327 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002328
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002329 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2330 // Mix-in this trigger into the next request and only the next request.
2331 RequestTrigger trigger[] = {
2332 {
2333 ANDROID_CONTROL_AF_TRIGGER,
2334 ANDROID_CONTROL_AF_TRIGGER_START
2335 },
2336 {
2337 ANDROID_CONTROL_AF_TRIGGER_ID,
2338 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002339 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002340 };
2341
2342 return mRequestThread->queueTrigger(trigger,
2343 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002344}
2345
2346status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2347 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002348 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002349
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002350 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2351 // Mix-in this trigger into the next request and only the next request.
2352 RequestTrigger trigger[] = {
2353 {
2354 ANDROID_CONTROL_AF_TRIGGER,
2355 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2356 },
2357 {
2358 ANDROID_CONTROL_AF_TRIGGER_ID,
2359 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002360 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002361 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002362
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002363 return mRequestThread->queueTrigger(trigger,
2364 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002365}
2366
2367status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2368 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002369 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002370
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002371 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2372 // Mix-in this trigger into the next request and only the next request.
2373 RequestTrigger trigger[] = {
2374 {
2375 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2376 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2377 },
2378 {
2379 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2380 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002381 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002382 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002383
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002384 return mRequestThread->queueTrigger(trigger,
2385 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002386}
2387
Jianing Weicb0652e2014-03-12 18:29:36 -07002388status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002389 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002390 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002391 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002392
Zhijun He7ef20392014-04-21 16:04:17 -07002393 {
2394 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002395
2396 // b/116514106 "disconnect()" can get called twice for the same device. The
2397 // camera device will not be initialized during the second run.
2398 if (mStatus == STATUS_UNINITIALIZED) {
2399 return OK;
2400 }
2401
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002402 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002403 }
2404
Emilian Peev08dd2452017-04-06 16:55:14 +01002405 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002406}
2407
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002408status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002409 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2410}
2411
2412status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002413 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002414 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002415 Mutex::Autolock il(mInterfaceLock);
2416 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002417
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002418 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2419 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002420 CLOGE("Stream %d does not exist", streamId);
2421 return BAD_VALUE;
2422 }
2423
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002424 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002425 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002426 return BAD_VALUE;
2427 }
2428
2429 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002430 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002431 return BAD_VALUE;
2432 }
2433
Ruben Brunkc78ac262015-08-13 17:58:46 -07002434 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002435}
2436
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002437status_t Camera3Device::tearDown(int streamId) {
2438 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002439 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002440 Mutex::Autolock il(mInterfaceLock);
2441 Mutex::Autolock l(mLock);
2442
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002443 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2444 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002445 CLOGE("Stream %d does not exist", streamId);
2446 return BAD_VALUE;
2447 }
2448
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002449 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2450 CLOGE("Stream %d is a target of a in-progress request", streamId);
2451 return BAD_VALUE;
2452 }
2453
2454 return stream->tearDown();
2455}
2456
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002457status_t Camera3Device::addBufferListenerForStream(int streamId,
2458 wp<Camera3StreamBufferListener> listener) {
2459 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002460 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002461 Mutex::Autolock il(mInterfaceLock);
2462 Mutex::Autolock l(mLock);
2463
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002464 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2465 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002466 CLOGE("Stream %d does not exist", streamId);
2467 return BAD_VALUE;
2468 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002469 stream->addBufferListener(listener);
2470
2471 return OK;
2472}
2473
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002474/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002475 * Methods called by subclasses
2476 */
2477
2478void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002479 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002480 {
2481 // Need mLock to safely update state and synchronize to current
2482 // state of methods in flight.
2483 Mutex::Autolock l(mLock);
2484 // We can get various system-idle notices from the status tracker
2485 // while starting up. Only care about them if we've actually sent
2486 // in some requests recently.
2487 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2488 return;
2489 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002490 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2491 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002492 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002493
2494 // Skip notifying listener if we're doing some user-transparent
2495 // state changes
2496 if (mPauseStateNotify) return;
2497 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002498
2499 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002500 {
2501 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002502 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002503 }
2504 if (idle && listener != NULL) {
2505 listener->notifyIdle();
2506 }
2507}
2508
Shuzhen Wang758c2152017-01-10 18:26:18 -08002509status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002510 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002511 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002512 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2513 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002514
2515 if (surfaceIds == nullptr) {
2516 return BAD_VALUE;
2517 }
2518
Zhijun He5d677d12016-05-29 16:52:39 -07002519 Mutex::Autolock il(mInterfaceLock);
2520 Mutex::Autolock l(mLock);
2521
Shuzhen Wang758c2152017-01-10 18:26:18 -08002522 if (consumers.size() == 0) {
2523 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002524 return BAD_VALUE;
2525 }
2526
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002527 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2528 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002529 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002530 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002531 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002532
2533 // isConsumerConfigurationDeferred will be off after setConsumers
2534 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002535 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002536 if (res != OK) {
2537 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2538 return res;
2539 }
2540
Emilian Peev40ead602017-09-26 15:46:36 +01002541 for (auto &consumer : consumers) {
2542 int id = stream->getSurfaceId(consumer);
2543 if (id < 0) {
2544 CLOGE("Invalid surface id!");
2545 return BAD_VALUE;
2546 }
2547 surfaceIds->push_back(id);
2548 }
2549
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002550 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002551 if (!stream->isConfiguring()) {
2552 CLOGE("Stream %d was already fully configured.", streamId);
2553 return INVALID_OPERATION;
2554 }
Zhijun He5d677d12016-05-29 16:52:39 -07002555
Shuzhen Wang0129d522016-10-30 22:43:41 -07002556 res = stream->finishConfiguration();
2557 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002558 // If finishConfiguration fails due to abandoned surface, do not set
2559 // device to error state.
2560 bool isSurfaceAbandoned =
2561 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2562 if (!isSurfaceAbandoned) {
2563 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2564 stream->getId(), strerror(-res), res);
2565 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002566 return res;
2567 }
Zhijun He5d677d12016-05-29 16:52:39 -07002568 }
2569
2570 return OK;
2571}
2572
Emilian Peev40ead602017-09-26 15:46:36 +01002573status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2574 const std::vector<OutputStreamInfo> &outputInfo,
2575 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2576 Mutex::Autolock il(mInterfaceLock);
2577 Mutex::Autolock l(mLock);
2578
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002579 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2580 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002581 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002582 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002583 }
2584
2585 for (const auto &it : removedSurfaceIds) {
2586 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2587 CLOGE("Shared surface still part of a pending request!");
2588 return -EBUSY;
2589 }
2590 }
2591
Emilian Peev40ead602017-09-26 15:46:36 +01002592 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2593 if (res != OK) {
2594 CLOGE("Stream %d failed to update stream (error %d %s) ",
2595 streamId, res, strerror(-res));
2596 if (res == UNKNOWN_ERROR) {
2597 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2598 __FUNCTION__);
2599 }
2600 return res;
2601 }
2602
2603 return res;
2604}
2605
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002606status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2607 Mutex::Autolock il(mInterfaceLock);
2608 Mutex::Autolock l(mLock);
2609
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002610 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2611 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002612 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2613 return BAD_VALUE;
2614 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002615 return stream->dropBuffers(dropping);
2616}
2617
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002618/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002619 * Camera3Device private methods
2620 */
2621
2622sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002623 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002624 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002625
2626 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002627 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002628
2629 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002630 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002631 if (inputStreams.count > 0) {
2632 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002633 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002634 CLOGE("Request references unknown input stream %d",
2635 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002636 return NULL;
2637 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002638
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002639 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002640 SET_ERR_L("%s: input stream %d is not configured!",
2641 __FUNCTION__, mInputStream->getId());
2642 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002643 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002644 // Check if stream prepare is blocking requests.
2645 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002646 CLOGE("Request references an input stream that's being prepared!");
2647 return NULL;
2648 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002649
2650 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002651 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002652 }
2653
2654 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002655 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002656 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002657 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002658 return NULL;
2659 }
2660
2661 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002662 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2663 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002664 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002665 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002666 return NULL;
2667 }
Zhijun He5d677d12016-05-29 16:52:39 -07002668 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002669 auto iter = surfaceMap.find(streams.data.i32[i]);
2670 if (iter != surfaceMap.end()) {
2671 const std::vector<size_t>& surfaces = iter->second;
2672 for (const auto& surface : surfaces) {
2673 if (stream->isConsumerConfigurationDeferred(surface)) {
2674 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2675 "due to deferred consumer", stream->getId(), surface);
2676 return NULL;
2677 }
2678 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002679 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002680 }
2681
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002682 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002683 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2684 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002685 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002686 // Check if stream prepare is blocking requests.
2687 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002688 CLOGE("Request references an output stream that's being prepared!");
2689 return NULL;
2690 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002691
2692 newRequest->mOutputStreams.push(stream);
2693 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002694 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002695 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002696
2697 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002698}
2699
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002700bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2701 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2702 Size size = mSupportedOpaqueInputSizes[i];
2703 if (size.width == width && size.height == height) {
2704 return true;
2705 }
2706 }
2707
2708 return false;
2709}
2710
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002711void Camera3Device::cancelStreamsConfigurationLocked() {
2712 int res = OK;
2713 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2714 res = mInputStream->cancelConfiguration();
2715 if (res != OK) {
2716 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2717 mInputStream->getId(), strerror(-res), res);
2718 }
2719 }
2720
2721 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002722 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002723 if (outputStream->isConfiguring()) {
2724 res = outputStream->cancelConfiguration();
2725 if (res != OK) {
2726 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2727 outputStream->getId(), strerror(-res), res);
2728 }
2729 }
2730 }
2731
2732 // Return state to that at start of call, so that future configures
2733 // properly clean things up
2734 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2735 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002736
2737 res = mPreparerThread->resume();
2738 if (res != OK) {
2739 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2740 }
2741}
2742
2743bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2744 ATRACE_CALL();
2745 bool ret = false;
2746
Jayant Chowdhary37eca242019-11-18 08:55:56 -08002747 // We must not hold mInterfaceLock here since this function is called from
2748 // RequestThread::threadLoop and holding mInterfaceLock could lead to
2749 // deadlocks (http://b/143513518)
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002750 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2751
2752 Mutex::Autolock l(mLock);
2753 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2754 if (rc == NO_ERROR) {
2755 mNeedConfig = true;
2756 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2757 if (rc == NO_ERROR) {
2758 ret = true;
2759 mPauseStateNotify = false;
2760 //Moving to active state while holding 'mLock' is important.
2761 //There could be pending calls to 'create-/deleteStream' which
2762 //will trigger another stream configuration while the already
2763 //present streams end up with outstanding buffers that will
2764 //not get drained.
2765 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002766 } else if (rc == DEAD_OBJECT) {
2767 // DEAD_OBJECT can be returned if either the consumer surface is
2768 // abandoned, or the HAL has died.
2769 // - If the HAL has died, configureStreamsLocked call will set
2770 // device to error state,
2771 // - If surface is abandoned, we should not set device to error
2772 // state.
2773 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002774 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002775 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002776 }
2777 } else {
2778 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2779 }
2780
2781 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002782}
2783
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002784status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002785 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002786 ATRACE_CALL();
2787 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002788
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002789 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002790 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002791 return INVALID_OPERATION;
2792 }
2793
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002794 if (operatingMode < 0) {
2795 CLOGE("Invalid operating mode: %d", operatingMode);
2796 return BAD_VALUE;
2797 }
2798
2799 bool isConstrainedHighSpeed =
2800 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2801 operatingMode;
2802
2803 if (mOperatingMode != operatingMode) {
2804 mNeedConfig = true;
2805 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2806 mOperatingMode = operatingMode;
2807 }
2808
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002809 if (!mNeedConfig) {
2810 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2811 return OK;
2812 }
2813
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002814 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2815 // adding a dummy stream instead.
2816 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2817 if (mOutputStreams.size() == 0) {
2818 addDummyStreamLocked();
2819 } else {
2820 tryRemoveDummyStreamLocked();
2821 }
2822
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002823 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002824 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002825
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002826 mPreparerThread->pause();
2827
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002828 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002829 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002830 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2831
2832 Vector<camera3_stream_t*> streams;
2833 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002834 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002835
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002836
2837 if (mInputStream != NULL) {
2838 camera3_stream_t *inputStream;
2839 inputStream = mInputStream->startConfiguration();
2840 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002841 CLOGE("Can't start input stream configuration");
2842 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002843 return INVALID_OPERATION;
2844 }
2845 streams.add(inputStream);
2846 }
2847
2848 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002849
2850 // Don't configure bidi streams twice, nor add them twice to the list
2851 if (mOutputStreams[i].get() ==
2852 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2853
2854 config.num_streams--;
2855 continue;
2856 }
2857
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002858 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002859 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002860 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002861 CLOGE("Can't start output stream configuration");
2862 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002863 return INVALID_OPERATION;
2864 }
2865 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002866
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002867 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002868 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2869 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002870 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2871 bufferSizes[k] = static_cast<uint32_t>(
2872 getJpegBufferSize(outputStream->width, outputStream->height));
2873 } else if (outputStream->data_space ==
2874 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2875 bufferSizes[k] = outputStream->width * outputStream->height;
2876 } else {
2877 ALOGW("%s: Blob dataSpace %d not supported",
2878 __FUNCTION__, outputStream->data_space);
2879 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002880 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002881 }
2882
2883 config.streams = streams.editArray();
2884
2885 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002886 // max_buffers, usage, and priv fields, as well as data_space and format
2887 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002888
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002889 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002890 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002891 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002892
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002893 if (res == BAD_VALUE) {
2894 // HAL rejected this set of streams as unsupported, clean up config
2895 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002896 CLOGE("Set of requested inputs/outputs not supported by HAL");
2897 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002898 return BAD_VALUE;
2899 } else if (res != OK) {
2900 // Some other kind of error from configure_streams - this is not
2901 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002902 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2903 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002904 return res;
2905 }
2906
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002907 // Finish all stream configuration immediately.
2908 // TODO: Try to relax this later back to lazy completion, which should be
2909 // faster
2910
Igor Murashkin073f8572013-05-02 14:59:28 -07002911 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002912 bool streamReConfigured = false;
2913 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002914 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002915 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002916 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002917 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002918 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2919 return DEAD_OBJECT;
2920 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002921 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002922 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002923 if (streamReConfigured) {
2924 mInterface->onStreamReConfigured(mInputStream->getId());
2925 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002926 }
2927
2928 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002929 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002930 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002931 bool streamReConfigured = false;
2932 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002933 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002934 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002935 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002936 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002937 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2938 return DEAD_OBJECT;
2939 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002940 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002941 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002942 if (streamReConfigured) {
2943 mInterface->onStreamReConfigured(outputStream->getId());
2944 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002945 }
2946 }
2947
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002948 // Request thread needs to know to avoid using repeat-last-settings protocol
2949 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002950 if (notifyRequestThread) {
2951 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2952 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002953
Zhijun He90f7c372016-08-16 16:19:43 -07002954 char value[PROPERTY_VALUE_MAX];
2955 property_get("camera.fifo.disable", value, "0");
2956 int32_t disableFifo = atoi(value);
2957 if (disableFifo != 1) {
2958 // Boost priority of request thread to SCHED_FIFO.
2959 pid_t requestThreadTid = mRequestThread->getTid();
2960 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002961 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002962 if (res != OK) {
2963 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2964 strerror(-res), res);
2965 } else {
2966 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2967 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002968 }
2969
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002970 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002971 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2972 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2973 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2974 sessionParams.unlock(newSessionParams);
2975 mSessionParams.unlock(currentSessionParams);
2976 if (updateSessionParams) {
2977 mSessionParams = sessionParams;
2978 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002979
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002980 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002981
Ruben Brunk183f0562015-08-12 12:55:02 -07002982 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2983 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002984
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002985 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002986
Zhijun He0a210512014-07-24 13:45:15 -07002987 // tear down the deleted streams after configure streams.
2988 mDeletedStreams.clear();
2989
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002990 auto rc = mPreparerThread->resume();
2991 if (rc != OK) {
2992 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2993 return rc;
2994 }
2995
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002996 if (mDummyStreamId == NO_STREAM) {
2997 mRequestBufferSM.onStreamsConfigured();
2998 }
2999
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003000 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003001}
3002
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003003status_t Camera3Device::addDummyStreamLocked() {
3004 ATRACE_CALL();
3005 status_t res;
3006
3007 if (mDummyStreamId != NO_STREAM) {
3008 // Should never be adding a second dummy stream when one is already
3009 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003010 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
3011 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003012 return INVALID_OPERATION;
3013 }
3014
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003015 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003016
3017 sp<Camera3OutputStreamInterface> dummyStream =
3018 new Camera3DummyStream(mNextStreamId);
3019
3020 res = mOutputStreams.add(mNextStreamId, dummyStream);
3021 if (res < 0) {
3022 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
3023 return res;
3024 }
3025
3026 mDummyStreamId = mNextStreamId;
3027 mNextStreamId++;
3028
3029 return OK;
3030}
3031
3032status_t Camera3Device::tryRemoveDummyStreamLocked() {
3033 ATRACE_CALL();
3034 status_t res;
3035
3036 if (mDummyStreamId == NO_STREAM) return OK;
3037 if (mOutputStreams.size() == 1) return OK;
3038
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003039 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003040
3041 // Ok, have a dummy stream and there's at least one other output stream,
3042 // so remove the dummy
3043
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003044 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
3045 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003046 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3047 return INVALID_OPERATION;
3048 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003049 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003050
3051 // Free up the stream endpoint so that it can be used by some other stream
3052 res = deletedStream->disconnect();
3053 if (res != OK) {
3054 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3055 // fall through since we want to still list the stream as deleted.
3056 }
3057 mDeletedStreams.add(deletedStream);
3058 mDummyStreamId = NO_STREAM;
3059
3060 return res;
3061}
3062
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003063void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003064 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003065 Mutex::Autolock l(mLock);
3066 va_list args;
3067 va_start(args, fmt);
3068
3069 setErrorStateLockedV(fmt, args);
3070
3071 va_end(args);
3072}
3073
3074void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003075 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003076 Mutex::Autolock l(mLock);
3077 setErrorStateLockedV(fmt, args);
3078}
3079
3080void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3081 va_list args;
3082 va_start(args, fmt);
3083
3084 setErrorStateLockedV(fmt, args);
3085
3086 va_end(args);
3087}
3088
3089void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003090 // Print out all error messages to log
3091 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003092 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003093
3094 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003095 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003096
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003097 mErrorCause = errorCause;
3098
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003099 if (mRequestThread != nullptr) {
3100 mRequestThread->setPaused(true);
3101 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003102 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003103
3104 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003105 sp<NotificationListener> listener = mListener.promote();
3106 if (listener != NULL) {
3107 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003108 CaptureResultExtras());
3109 }
3110
3111 // Save stack trace. View by dumping it later.
3112 CameraTraces::saveTrace();
3113 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003114}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003115
3116/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003117 * In-flight request management
3118 */
3119
Jianing Weicb0652e2014-03-12 18:29:36 -07003120status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003121 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003122 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003123 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003124 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003125 ATRACE_CALL();
3126 Mutex::Autolock l(mInFlightLock);
3127
3128 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003129 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003130 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3131 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003132 if (res < 0) return res;
3133
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003134 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003135 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3136 // avoid a deadlock during reprocess requests.
3137 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003138 if (mStatusTracker != nullptr) {
3139 mStatusTracker->markComponentActive(mInFlightStatusId);
3140 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003141 }
3142
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003143 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003144 return OK;
3145}
3146
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003147void Camera3Device::returnOutputBuffers(
3148 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003149 nsecs_t timestamp, bool timestampIncreasing,
3150 const SurfaceMap& outputSurfaces,
3151 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003152
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003153 for (size_t i = 0; i < numBuffers; i++)
3154 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003155 if (outputBuffers[i].buffer == nullptr) {
3156 if (!mUseHalBufManager) {
3157 // With HAL buffer management API, HAL sometimes will have to return buffers that
3158 // has not got a output buffer handle filled yet. This is though illegal if HAL
3159 // buffer management API is not being used.
3160 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3161 }
3162 continue;
3163 }
3164
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003165 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3166 int streamId = stream->getId();
3167 const auto& it = outputSurfaces.find(streamId);
3168 status_t res = OK;
3169 if (it != outputSurfaces.end()) {
3170 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003171 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3172 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003173 } else {
3174 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003175 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3176 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003177 }
3178
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003179 // Note: stream may be deallocated at this point, if this buffer was
3180 // the last reference to it.
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003181 if (res == NO_INIT || res == DEAD_OBJECT) {
3182 ALOGV("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
3183 } else if (res != OK) {
3184 ALOGE("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003185 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003186
3187 // Long processing consumers can cause returnBuffer timeout for shared stream
3188 // If that happens, cancel the buffer and send a buffer error to client
3189 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3190 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3191 // cancel the buffer
3192 camera3_stream_buffer_t sb = outputBuffers[i];
3193 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003194 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3195 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003196
3197 // notify client buffer error
3198 sp<NotificationListener> listener;
3199 {
3200 Mutex::Autolock l(mOutputLock);
3201 listener = mListener.promote();
3202 }
3203
3204 if (listener != nullptr) {
3205 CaptureResultExtras extras = inResultExtras;
3206 extras.errorStreamId = streamId;
3207 listener->notifyError(
3208 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3209 extras);
3210 }
3211 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003212 }
3213}
3214
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003215void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003216 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003217 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003218 mInFlightMap.removeItemsAt(idx, 1);
3219
3220 // Indicate idle inFlightMap to the status tracker
3221 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003222 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003223 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3224 // avoid a deadlock during reprocess requests.
3225 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003226 if (mStatusTracker != nullptr) {
3227 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3228 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003229 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003230 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003231}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003232
3233void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3234
3235 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3236 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3237
3238 nsecs_t sensorTimestamp = request.sensorTimestamp;
3239 nsecs_t shutterTimestamp = request.shutterTimestamp;
3240
3241 // Check if it's okay to remove the request from InFlightMap:
3242 // In the case of a successful request:
3243 // all input and output buffers, all result metadata, shutter callback
3244 // arrived.
3245 // In the case of a unsuccessful request:
3246 // all input and output buffers arrived.
3247 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003248 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003249 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003250 if (request.stillCapture) {
3251 ATRACE_ASYNC_END("still capture", frameNumber);
3252 }
3253
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003254 ATRACE_ASYNC_END("frame capture", frameNumber);
3255
Shuzhen Wang403044a2017-02-26 23:29:04 -08003256 // Sanity check - if sensor timestamp matches shutter timestamp in the
3257 // case of request having callback.
3258 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003259 sensorTimestamp != shutterTimestamp) {
3260 SET_ERR("sensor timestamp (%" PRId64
3261 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3262 sensorTimestamp, frameNumber, shutterTimestamp);
3263 }
3264
3265 // for an unsuccessful request, it may have pending output buffers to
3266 // return.
3267 assert(request.requestStatus != OK ||
3268 request.pendingOutputBuffers.size() == 0);
3269 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003270 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3271 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003272
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003273 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003274 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3275 }
3276
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003277 // Sanity check - if we have too many in-flight frames with long total inflight duration,
3278 // something has likely gone wrong. This might still be legit only if application send in
3279 // a long burst of long exposure requests.
3280 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3281 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3282 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3283 mInFlightMap.size(), mExpectedInflightDuration);
3284 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3285 kInFlightWarnLimitHighSpeed) {
3286 CLOGW("In-flight list too large for high speed configuration: %zu,"
3287 "total inflight duration %" PRIu64,
3288 mInFlightMap.size(), mExpectedInflightDuration);
3289 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003290 }
3291}
3292
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003293void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003294 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003295 { // First return buffers cached in mInFlightMap
3296 Mutex::Autolock l(mInFlightLock);
3297 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3298 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3299 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003300 request.pendingOutputBuffers.size(), 0,
3301 /*timestampIncreasing*/true, request.outputSurfaces,
3302 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003303 }
3304 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003305 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003306 }
3307
3308 // Then return all inflight buffers not returned by HAL
3309 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3310 mInterface->getInflightBufferKeys(&inflightKeys);
3311
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003312 // Inflight buffers for HAL buffer manager
3313 std::vector<uint64_t> inflightRequestBufferKeys;
3314 mInterface->getInflightRequestBufferKeys(&inflightRequestBufferKeys);
3315
3316 // (streamId, frameNumber, buffer_handle_t*) tuple for all inflight buffers.
3317 // frameNumber will be -1 for buffers from HAL buffer manager
3318 std::vector<std::tuple<int32_t, int32_t, buffer_handle_t*>> inflightBuffers;
3319 inflightBuffers.reserve(inflightKeys.size() + inflightRequestBufferKeys.size());
3320
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003321 for (auto& pair : inflightKeys) {
3322 int32_t frameNumber = pair.first;
3323 int32_t streamId = pair.second;
3324 buffer_handle_t* buffer;
3325 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3326 if (res != OK) {
3327 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3328 __FUNCTION__, frameNumber, streamId);
3329 continue;
3330 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003331 inflightBuffers.push_back(std::make_tuple(streamId, frameNumber, buffer));
3332 }
3333
3334 for (auto& bufferId : inflightRequestBufferKeys) {
3335 int32_t streamId = -1;
3336 buffer_handle_t* buffer = nullptr;
3337 status_t res = mInterface->popInflightRequestBuffer(bufferId, &buffer, &streamId);
3338 if (res != OK) {
3339 ALOGE("%s: cannot find in-flight buffer %" PRIu64, __FUNCTION__, bufferId);
3340 continue;
3341 }
3342 inflightBuffers.push_back(std::make_tuple(streamId, /*frameNumber*/-1, buffer));
3343 }
3344
3345 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3346 for (auto& tuple : inflightBuffers) {
3347 status_t res = OK;
3348 int32_t streamId = std::get<0>(tuple);
3349 int32_t frameNumber = std::get<1>(tuple);
3350 buffer_handle_t* buffer = std::get<2>(tuple);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003351
3352 camera3_stream_buffer_t streamBuffer;
3353 streamBuffer.buffer = buffer;
3354 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3355 streamBuffer.acquire_fence = -1;
3356 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003357
3358 // First check if the buffer belongs to deleted stream
3359 bool streamDeleted = false;
3360 for (auto& stream : mDeletedStreams) {
3361 if (streamId == stream->getId()) {
3362 streamDeleted = true;
3363 // Return buffer to deleted stream
3364 camera3_stream* halStream = stream->asHalStream();
3365 streamBuffer.stream = halStream;
3366 switch (halStream->stream_type) {
3367 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003368 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3369 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003370 if (res != OK) {
3371 ALOGE("%s: Can't return output buffer for frame %d to"
3372 " stream %d: %s (%d)", __FUNCTION__,
3373 frameNumber, streamId, strerror(-res), res);
3374 }
3375 break;
3376 case CAMERA3_STREAM_INPUT:
3377 res = stream->returnInputBuffer(streamBuffer);
3378 if (res != OK) {
3379 ALOGE("%s: Can't return input buffer for frame %d to"
3380 " stream %d: %s (%d)", __FUNCTION__,
3381 frameNumber, streamId, strerror(-res), res);
3382 }
3383 break;
3384 default: // Bi-direcitonal stream is deprecated
3385 ALOGE("%s: stream %d has unknown stream type %d",
3386 __FUNCTION__, streamId, halStream->stream_type);
3387 break;
3388 }
3389 break;
3390 }
3391 }
3392 if (streamDeleted) {
3393 continue;
3394 }
3395
3396 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003397 if (streamId == inputStreamId) {
3398 streamBuffer.stream = mInputStream->asHalStream();
3399 res = mInputStream->returnInputBuffer(streamBuffer);
3400 if (res != OK) {
3401 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003402 " stream %d: %s (%d)", __FUNCTION__,
3403 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003404 }
3405 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003406 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3407 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003408 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3409 continue;
3410 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003411 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003412 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3413 }
3414 }
3415}
3416
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003417void Camera3Device::insertResultLocked(CaptureResult *result,
3418 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003419 if (result == nullptr) return;
3420
Emilian Peev71c73a22017-03-21 16:35:51 +00003421 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3422 result->mMetadata.getAndLock());
3423 set_camera_metadata_vendor_id(meta, mVendorTagId);
3424 result->mMetadata.unlock(meta);
3425
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003426 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3427 (int32_t*)&frameNumber, 1) != OK) {
3428 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3429 return;
3430 }
3431
3432 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3433 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3434 return;
3435 }
3436
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003437 // Update vendor tag id for physical metadata
3438 for (auto& physicalMetadata : result->mPhysicalMetadatas) {
3439 camera_metadata_t *pmeta = const_cast<camera_metadata_t *>(
3440 physicalMetadata.mPhysicalCameraMetadata.getAndLock());
3441 set_camera_metadata_vendor_id(pmeta, mVendorTagId);
3442 physicalMetadata.mPhysicalCameraMetadata.unlock(pmeta);
3443 }
3444
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003445 // Valid result, insert into queue
3446 List<CaptureResult>::iterator queuedResult =
3447 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3448 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3449 ", burstId = %" PRId32, __FUNCTION__,
3450 queuedResult->mResultExtras.requestId,
3451 queuedResult->mResultExtras.frameNumber,
3452 queuedResult->mResultExtras.burstId);
3453
3454 mResultSignal.signal();
3455}
3456
3457
3458void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003459 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003460 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003461 Mutex::Autolock l(mOutputLock);
3462
3463 CaptureResult captureResult;
3464 captureResult.mResultExtras = resultExtras;
3465 captureResult.mMetadata = partialResult;
3466
Shuzhen Wang268a1362018-10-16 16:32:59 -07003467 // Fix up result metadata for monochrome camera.
3468 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3469 if (res != OK) {
3470 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3471 return;
3472 }
3473
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003474 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003475}
3476
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003477
3478void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3479 CaptureResultExtras &resultExtras,
3480 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003481 uint32_t frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003482 bool reprocess, bool zslStillCapture,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003483 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003484 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003485 if (pendingMetadata.isEmpty())
3486 return;
3487
3488 Mutex::Autolock l(mOutputLock);
3489
3490 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003491 if (reprocess) {
3492 if (frameNumber < mNextReprocessResultFrameNumber) {
3493 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003494 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003495 frameNumber, mNextReprocessResultFrameNumber);
3496 return;
3497 }
3498 mNextReprocessResultFrameNumber = frameNumber + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003499 } else if (zslStillCapture) {
3500 if (frameNumber < mNextZslStillResultFrameNumber) {
3501 SET_ERR("Out-of-order ZSL still capture result metadata submitted! "
3502 "(got frame number %d, expecting %d)",
3503 frameNumber, mNextZslStillResultFrameNumber);
3504 return;
3505 }
3506 mNextZslStillResultFrameNumber = frameNumber + 1;
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003507 } else {
3508 if (frameNumber < mNextResultFrameNumber) {
3509 SET_ERR("Out-of-order capture result metadata submitted! "
3510 "(got frame number %d, expecting %d)",
3511 frameNumber, mNextResultFrameNumber);
3512 return;
3513 }
3514 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003515 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003516
3517 CaptureResult captureResult;
3518 captureResult.mResultExtras = resultExtras;
3519 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003520 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003521
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003522 // Append any previous partials to form a complete result
3523 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3524 captureResult.mMetadata.append(collectedPartialResult);
3525 }
3526
3527 captureResult.mMetadata.sort();
3528
3529 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003530 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3531 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003532 SET_ERR("No timestamp provided by HAL for frame %d!",
3533 frameNumber);
3534 return;
3535 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003536 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3537 camera_metadata_entry timestamp =
3538 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3539 if (timestamp.count == 0) {
3540 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3541 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3542 return;
3543 }
3544 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003545
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003546 // Fix up some result metadata to account for HAL-level distortion correction
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003547 status_t res =
3548 mDistortionMappers[mId.c_str()].correctCaptureResult(&captureResult.mMetadata);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003549 if (res != OK) {
3550 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3551 frameNumber, strerror(res), res);
3552 return;
3553 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003554 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3555 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3556 if (mDistortionMappers.find(cameraId8.c_str()) == mDistortionMappers.end()) {
3557 continue;
3558 }
3559 res = mDistortionMappers[cameraId8.c_str()].correctCaptureResult(
3560 &physicalMetadata.mPhysicalCameraMetadata);
3561 if (res != OK) {
3562 SET_ERR("Unable to correct physical capture result metadata for frame %d: %s (%d)",
3563 frameNumber, strerror(res), res);
3564 return;
3565 }
3566 }
3567
Shuzhen Wang268a1362018-10-16 16:32:59 -07003568 // Fix up result metadata for monochrome camera.
3569 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3570 if (res != OK) {
3571 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3572 return;
3573 }
3574 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3575 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3576 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3577 physicalMetadata.mPhysicalCameraMetadata);
3578 if (res != OK) {
3579 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3580 return;
3581 }
3582 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003583
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003584 std::unordered_map<std::string, CameraMetadata> monitoredPhysicalMetadata;
3585 for (auto& m : physicalMetadatas) {
3586 monitoredPhysicalMetadata.emplace(String8(m.mPhysicalCameraId).string(),
3587 CameraMetadata(m.mPhysicalCameraMetadata));
3588 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003589 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003590 frameNumber, timestamp.data.i64[0], captureResult.mMetadata,
3591 monitoredPhysicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003592
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003593 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003594}
3595
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003596/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003597 * Camera HAL device callback methods
3598 */
3599
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003600void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003601 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003602
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003603 status_t res;
3604
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003605 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003606 if (result->result == NULL && result->num_output_buffers == 0 &&
3607 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003608 SET_ERR("No result data provided by HAL for frame %d",
3609 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003610 return;
3611 }
Zhijun He204e3292014-07-14 17:09:23 -07003612
Zhijun He204e3292014-07-14 17:09:23 -07003613 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003614 result->result != NULL &&
3615 result->partial_result != 1) {
3616 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3617 " if partial result is not supported",
3618 frameNumber, result->partial_result);
3619 return;
3620 }
3621
3622 bool isPartialResult = false;
3623 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003624 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003625
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003626 // Get shutter timestamp and resultExtras from list of in-flight requests,
3627 // where it was added by the shutter notification for this frame. If the
3628 // shutter timestamp isn't received yet, append the output buffers to the
3629 // in-flight request and they will be returned when the shutter timestamp
3630 // arrives. Update the in-flight status and remove the in-flight entry if
3631 // all result data and shutter timestamp have been received.
3632 nsecs_t shutterTimestamp = 0;
3633
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003634 {
3635 Mutex::Autolock l(mInFlightLock);
3636 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3637 if (idx == NAME_NOT_FOUND) {
3638 SET_ERR("Unknown frame number for capture result: %d",
3639 frameNumber);
3640 return;
3641 }
3642 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003643 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3644 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003645 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003646 __FUNCTION__, request.resultExtras.requestId,
3647 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003648 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003649 // Always update the partial count to the latest one if it's not 0
3650 // (buffers only). When framework aggregates adjacent partial results
3651 // into one, the latest partial count will be used.
3652 if (result->partial_result != 0)
3653 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003654
3655 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003656 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003657 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3658 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3659 " the range of [1, %d] when metadata is included in the result",
3660 frameNumber, result->partial_result, mNumPartialResults);
3661 return;
3662 }
3663 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003664 if (isPartialResult && result->num_physcam_metadata) {
3665 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3666 " physical camera result", frameNumber);
3667 return;
3668 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003669 if (isPartialResult) {
3670 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003671 }
3672
Shuzhen Wang4a472662017-02-26 23:29:04 -08003673 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003674 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003675 sendPartialCaptureResult(result->result, request.resultExtras,
3676 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003677 }
3678 }
3679
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003680 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003681 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003682
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003683 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003684 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003685 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3686 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3687 request.physicalCameraIds.size(), result->num_physcam_metadata);
3688 return;
3689 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003690 if (request.haveResultMetadata) {
3691 SET_ERR("Called multiple times with metadata for frame %d",
3692 frameNumber);
3693 return;
3694 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003695 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3696 String8 physicalId(result->physcam_ids[i]);
3697 std::set<String8>::iterator cameraIdIter =
3698 request.physicalCameraIds.find(physicalId);
3699 if (cameraIdIter != request.physicalCameraIds.end()) {
3700 request.physicalCameraIds.erase(cameraIdIter);
3701 } else {
3702 SET_ERR("Total result for frame %d has already returned for camera %s",
3703 frameNumber, physicalId.c_str());
3704 return;
3705 }
3706 }
Zhijun He204e3292014-07-14 17:09:23 -07003707 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003708 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003709 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003710 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003711 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003712 request.haveResultMetadata = true;
3713 }
3714
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003715 uint32_t numBuffersReturned = result->num_output_buffers;
3716 if (result->input_buffer != NULL) {
3717 if (hasInputBufferInRequest) {
3718 numBuffersReturned += 1;
3719 } else {
3720 ALOGW("%s: Input buffer should be NULL if there is no input"
3721 " buffer sent in the request",
3722 __FUNCTION__);
3723 }
3724 }
3725 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003726 if (request.numBuffersLeft < 0) {
3727 SET_ERR("Too many buffers returned for frame %d",
3728 frameNumber);
3729 return;
3730 }
3731
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003732 camera_metadata_ro_entry_t entry;
3733 res = find_camera_metadata_ro_entry(result->result,
3734 ANDROID_SENSOR_TIMESTAMP, &entry);
3735 if (res == OK && entry.count == 1) {
3736 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003737 }
3738
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003739 // If shutter event isn't received yet, append the output buffers to
3740 // the in-flight request. Otherwise, return the output buffers to
3741 // streams.
3742 if (shutterTimestamp == 0) {
3743 request.pendingOutputBuffers.appendArray(result->output_buffers,
3744 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003745 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003746 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003747 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003748 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3749 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003750 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003751
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003752 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003753 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3754 CameraMetadata physicalMetadata;
3755 physicalMetadata.append(result->physcam_metadata[i]);
3756 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3757 physicalMetadata});
3758 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003759 if (shutterTimestamp == 0) {
3760 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003761 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003762 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003763 CameraMetadata metadata;
3764 metadata = result->result;
3765 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003766 collectedPartialResult, frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003767 hasInputBufferInRequest, request.zslCapture && request.stillCapture,
3768 request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003769 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003770 }
3771
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003772 removeInFlightRequestIfReadyLocked(idx);
3773 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003774
Zhijun Hef0d962a2014-06-30 10:24:11 -07003775 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003776 if (hasInputBufferInRequest) {
3777 Camera3Stream *stream =
3778 Camera3Stream::cast(result->input_buffer->stream);
3779 res = stream->returnInputBuffer(*(result->input_buffer));
3780 // Note: stream may be deallocated at this point, if this buffer was the
3781 // last reference to it.
3782 if (res != OK) {
3783 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3784 " its stream:%s (%d)", __FUNCTION__,
3785 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003786 }
3787 } else {
3788 ALOGW("%s: Input buffer should be NULL if there is no input"
3789 " buffer sent in the request, skipping input buffer return.",
3790 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003791 }
3792 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003793}
3794
3795void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003796 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003797 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003798 {
3799 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003800 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003801 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003802
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003803 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003804 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003805 return;
3806 }
3807
3808 switch (msg->type) {
3809 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003810 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003811 break;
3812 }
3813 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003814 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003815 break;
3816 }
3817 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003818 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003819 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003820 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003821}
3822
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003823void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003824 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003825 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003826 // Map camera HAL error codes to ICameraDeviceCallback error codes
3827 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003828 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003829 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003830 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003831 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003832 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003833 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003834 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003835 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003836 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003837 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003838 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003839 };
3840
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003841 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003842 ((msg.error_code >= 0) &&
3843 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3844 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003845 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003846
3847 int streamId = 0;
Emilian Peevedec62d2019-03-19 17:59:24 -07003848 String16 physicalCameraId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003849 if (msg.error_stream != NULL) {
3850 Camera3Stream *stream =
3851 Camera3Stream::cast(msg.error_stream);
3852 streamId = stream->getId();
Emilian Peevedec62d2019-03-19 17:59:24 -07003853 physicalCameraId = String16(stream->physicalCameraId());
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003854 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003855 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3856 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003857 streamId, msg.error_code);
3858
3859 CaptureResultExtras resultExtras;
3860 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003861 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003862 // SET_ERR calls notifyError
3863 SET_ERR("Camera HAL reported serious device error");
3864 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003865 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3866 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3867 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003868 {
3869 Mutex::Autolock l(mInFlightLock);
3870 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3871 if (idx >= 0) {
3872 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3873 r.requestStatus = msg.error_code;
3874 resultExtras = r.resultExtras;
Emilian Peevedec62d2019-03-19 17:59:24 -07003875 bool logicalDeviceResultError = false;
3876 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3877 errorCode) {
3878 if (physicalCameraId.size() > 0) {
3879 String8 cameraId(physicalCameraId);
3880 if (r.physicalCameraIds.find(cameraId) == r.physicalCameraIds.end()) {
3881 ALOGE("%s: Reported result failure for physical camera device: %s "
3882 " which is not part of the respective request!",
3883 __FUNCTION__, cameraId.string());
3884 break;
3885 }
3886 resultExtras.errorPhysicalCameraId = physicalCameraId;
3887 } else {
3888 logicalDeviceResultError = true;
3889 }
3890 }
3891
3892 if (logicalDeviceResultError
Shuzhen Wang20f57342017-08-24 15:39:05 -07003893 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3894 errorCode) {
3895 r.skipResultMetadata = true;
3896 }
Emilian Peevedec62d2019-03-19 17:59:24 -07003897 if (logicalDeviceResultError) {
Emilian Peevba0fac32017-03-30 09:05:34 +01003898 // In case of missing result check whether the buffers
3899 // returned. If they returned, then remove inflight
3900 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003901 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3902 // otherwise we are depending on HAL to send the buffers back after
3903 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003904 removeInFlightRequestIfReadyLocked(idx);
3905 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003906 } else {
3907 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003908 ALOGE("Camera %s: %s: cannot find in-flight request on "
3909 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003910 resultExtras.frameNumber);
3911 }
3912 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003913 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003914 if (listener != NULL) {
3915 listener->notifyError(errorCode, resultExtras);
3916 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003917 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003918 }
3919 break;
3920 default:
3921 // SET_ERR calls notifyError
3922 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3923 break;
3924 }
3925}
3926
3927void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003928 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003929 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003930 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003931
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003932 // Set timestamp for the request in the in-flight tracking
3933 // and get the request ID to send upstream
3934 {
3935 Mutex::Autolock l(mInFlightLock);
3936 idx = mInFlightMap.indexOfKey(msg.frame_number);
3937 if (idx >= 0) {
3938 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003939
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003940 // Verify ordering of shutter notifications
3941 {
3942 Mutex::Autolock l(mOutputLock);
3943 // TODO: need to track errors for tighter bounds on expected frame number.
3944 if (r.hasInputBuffer) {
3945 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003946 SET_ERR("Reprocess shutter notification out-of-order. Expected "
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003947 "notification for frame %d, got frame %d",
3948 mNextReprocessShutterFrameNumber, msg.frame_number);
3949 return;
3950 }
3951 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003952 } else if (r.zslCapture && r.stillCapture) {
3953 if (msg.frame_number < mNextZslStillShutterFrameNumber) {
3954 SET_ERR("ZSL still capture shutter notification out-of-order. Expected "
3955 "notification for frame %d, got frame %d",
3956 mNextZslStillShutterFrameNumber, msg.frame_number);
3957 return;
3958 }
3959 mNextZslStillShutterFrameNumber = msg.frame_number + 1;
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003960 } else {
3961 if (msg.frame_number < mNextShutterFrameNumber) {
3962 SET_ERR("Shutter notification out-of-order. Expected "
3963 "notification for frame %d, got frame %d",
3964 mNextShutterFrameNumber, msg.frame_number);
3965 return;
3966 }
3967 mNextShutterFrameNumber = msg.frame_number + 1;
3968 }
3969 }
3970
Shuzhen Wang4a472662017-02-26 23:29:04 -08003971 r.shutterTimestamp = msg.timestamp;
3972 if (r.hasCallback) {
3973 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003974 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003975 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003976 // Call listener, if any
3977 if (listener != NULL) {
3978 listener->notifyShutter(r.resultExtras, msg.timestamp);
3979 }
3980 // send pending result and buffers
3981 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3982 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003983 r.hasInputBuffer, r.zslCapture && r.stillCapture,
3984 r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003985 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003986 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003987 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003988 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3989 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003990 r.pendingOutputBuffers.clear();
3991
3992 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003993 }
3994 }
3995 if (idx < 0) {
3996 SET_ERR("Shutter notification for non-existent frame number %d",
3997 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003998 }
3999}
4000
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004001CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07004002 ALOGV("%s", __FUNCTION__);
4003
Igor Murashkin1e479c02013-09-06 16:55:14 -07004004 CameraMetadata retVal;
4005
4006 if (mRequestThread != NULL) {
4007 retVal = mRequestThread->getLatestRequest();
4008 }
4009
Igor Murashkin1e479c02013-09-06 16:55:14 -07004010 return retVal;
4011}
4012
Jianing Weicb0652e2014-03-12 18:29:36 -07004013
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004014void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004015 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
4016 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
4017
4018 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
4019 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004020}
4021
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004022/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004023 * HalInterface inner class methods
4024 */
4025
Yifan Hongf79b5542017-04-11 14:44:25 -07004026Camera3Device::HalInterface::HalInterface(
4027 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004028 std::shared_ptr<RequestMetadataQueue> queue,
4029 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004030 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004031 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08004032 mUseHalBufManager(useHalBufManager),
4033 mIsReconfigurationQuerySupported(true) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004034 // Check with hardware service manager if we can downcast these interfaces
4035 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004036 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
4037 if (castResult_3_5.isOk()) {
4038 mHidlSession_3_5 = castResult_3_5;
4039 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004040 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4041 if (castResult_3_4.isOk()) {
4042 mHidlSession_3_4 = castResult_3_4;
4043 }
4044 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
4045 if (castResult_3_3.isOk()) {
4046 mHidlSession_3_3 = castResult_3_3;
4047 }
4048}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004049
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004050Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004051
4052Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004053 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004054 mRequestMetadataQueue(other.mRequestMetadataQueue),
4055 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004056
4057bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004058 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004059}
4060
4061void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00004062 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00004063 mHidlSession_3_4.clear();
4064 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004065 mHidlSession.clear();
4066}
4067
4068status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
4069 camera3_request_template_t templateId,
4070 /*out*/ camera_metadata_t **requestTemplate) {
4071 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
4072 if (!valid()) return INVALID_OPERATION;
4073 status_t res = OK;
4074
Emilian Peev31abd0a2017-05-11 18:37:46 +01004075 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004076
4077 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01004078 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004079 status = s;
4080 if (status == common::V1_0::Status::OK) {
4081 const camera_metadata *r =
4082 reinterpret_cast<const camera_metadata_t*>(request.data());
4083 size_t expectedSize = request.size();
4084 int ret = validate_camera_metadata_structure(r, &expectedSize);
4085 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
4086 *requestTemplate = clone_camera_metadata(r);
4087 if (*requestTemplate == nullptr) {
4088 ALOGE("%s: Unable to clone camera metadata received from HAL",
4089 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004090 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004091 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004092 } else {
4093 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
4094 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004095 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004096 }
4097 };
4098 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004099 RequestTemplate id;
4100 switch (templateId) {
4101 case CAMERA3_TEMPLATE_PREVIEW:
4102 id = RequestTemplate::PREVIEW;
4103 break;
4104 case CAMERA3_TEMPLATE_STILL_CAPTURE:
4105 id = RequestTemplate::STILL_CAPTURE;
4106 break;
4107 case CAMERA3_TEMPLATE_VIDEO_RECORD:
4108 id = RequestTemplate::VIDEO_RECORD;
4109 break;
4110 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
4111 id = RequestTemplate::VIDEO_SNAPSHOT;
4112 break;
4113 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
4114 id = RequestTemplate::ZERO_SHUTTER_LAG;
4115 break;
4116 case CAMERA3_TEMPLATE_MANUAL:
4117 id = RequestTemplate::MANUAL;
4118 break;
4119 default:
4120 // Unknown template ID, or this HAL is too old to support it
4121 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004122 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004123 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004124
Emilian Peev31abd0a2017-05-11 18:37:46 +01004125 if (!err.isOk()) {
4126 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4127 res = DEAD_OBJECT;
4128 } else {
4129 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004130 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004131
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004132 return res;
4133}
4134
Emilian Peev4ec17882019-01-24 17:16:58 -08004135bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4136 CameraMetadata& newSessionParams) {
4137 // We do reconfiguration by default;
4138 bool ret = true;
4139 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4140 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4141 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4142 oldSessionParams.getAndLock());
4143 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4144 newSessionParams.getAndLock());
4145 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4146 get_camera_metadata_size(oldSessioMeta));
4147 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4148 get_camera_metadata_size(newSessioMeta));
4149 hardware::camera::common::V1_0::Status callStatus;
4150 bool required;
4151 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4152 bool requiredFlag) {
4153 callStatus = s;
4154 required = requiredFlag;
4155 };
4156 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4157 oldSessionParams.unlock(oldSessioMeta);
4158 newSessionParams.unlock(newSessioMeta);
4159 if (err.isOk()) {
4160 switch (callStatus) {
4161 case hardware::camera::common::V1_0::Status::OK:
4162 ret = required;
4163 break;
4164 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4165 mIsReconfigurationQuerySupported = false;
4166 ret = true;
4167 break;
4168 default:
4169 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4170 ret = true;
4171 }
4172 } else {
4173 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4174 ret = true;
4175 }
4176 }
4177
4178 return ret;
4179}
4180
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004181status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004182 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004183 ATRACE_NAME("CameraHal::configureStreams");
4184 if (!valid()) return INVALID_OPERATION;
4185 status_t res = OK;
4186
Emilian Peev31abd0a2017-05-11 18:37:46 +01004187 // Convert stream config to HIDL
4188 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004189 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4190 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4191 requestedConfiguration3_2.streams.resize(config->num_streams);
4192 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004193 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004194 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4195 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004196 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004197
Emilian Peev31abd0a2017-05-11 18:37:46 +01004198 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4199 cam3stream->setBufferFreedListener(this);
4200 int streamId = cam3stream->getId();
4201 StreamType streamType;
4202 switch (src->stream_type) {
4203 case CAMERA3_STREAM_OUTPUT:
4204 streamType = StreamType::OUTPUT;
4205 break;
4206 case CAMERA3_STREAM_INPUT:
4207 streamType = StreamType::INPUT;
4208 break;
4209 default:
4210 ALOGE("%s: Stream %d: Unsupported stream type %d",
4211 __FUNCTION__, streamId, config->streams[i]->stream_type);
4212 return BAD_VALUE;
4213 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004214 dst3_2.id = streamId;
4215 dst3_2.streamType = streamType;
4216 dst3_2.width = src->width;
4217 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004218 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004219 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07004220 // For HidlSession version 3.5 or newer, the format and dataSpace sent
4221 // to HAL are original, not the overriden ones.
4222 if (mHidlSession_3_5 != nullptr) {
4223 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
4224 cam3stream->getOriginalFormat() : src->format);
4225 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
4226 cam3stream->getOriginalDataSpace() : src->data_space);
4227 } else {
4228 dst3_2.format = mapToPixelFormat(src->format);
4229 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4230 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004231 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004232 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004233 if (src->physical_camera_id != nullptr) {
4234 dst3_4.physicalCameraId = src->physical_camera_id;
4235 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004236
4237 activeStreams.insert(streamId);
4238 // Create Buffer ID map if necessary
4239 if (mBufferIdMaps.count(streamId) == 0) {
4240 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4241 }
4242 }
4243 // remove BufferIdMap for deleted streams
4244 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4245 int streamId = it->first;
4246 bool active = activeStreams.count(streamId) > 0;
4247 if (!active) {
4248 it = mBufferIdMaps.erase(it);
4249 } else {
4250 ++it;
4251 }
4252 }
4253
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004254 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004255 res = mapToStreamConfigurationMode(
4256 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004257 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004258 if (res != OK) {
4259 return res;
4260 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004261 requestedConfiguration3_2.operationMode = operationMode;
4262 requestedConfiguration3_4.operationMode = operationMode;
4263 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004264 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4265 get_camera_metadata_size(sessionParams));
4266
Emilian Peev31abd0a2017-05-11 18:37:46 +01004267 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004268 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004269 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004270 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004271
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004272 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004273 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4274 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004275 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004276 };
4277
4278 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4279 (hardware::Return<void>& err) -> status_t {
4280 if (!err.isOk()) {
4281 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4282 return DEAD_OBJECT;
4283 }
4284 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4285 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4286 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4287 }
4288 return OK;
4289 };
4290
Shuzhen Wang92653952019-05-07 15:11:43 -07004291 // See which version of HAL we have
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004292 if (mHidlSession_3_5 != nullptr) {
4293 ALOGV("%s: v3.5 device found", __FUNCTION__);
4294 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4295 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4296 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4297 auto err = mHidlSession_3_5->configureStreams_3_5(
4298 requestedConfiguration3_5, configStream34Cb);
4299 res = postprocConfigStream34(err);
4300 if (res != OK) {
4301 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004302 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004303 } else if (mHidlSession_3_4 != nullptr) {
4304 // We do; use v3.4 for the call
4305 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004306 auto err = mHidlSession_3_4->configureStreams_3_4(
4307 requestedConfiguration3_4, configStream34Cb);
4308 res = postprocConfigStream34(err);
4309 if (res != OK) {
4310 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004311 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004312 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004313 // We do; use v3.3 for the call
4314 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004315 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004316 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004317 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004318 finalConfiguration = halConfiguration;
4319 status = s;
4320 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004321 if (!err.isOk()) {
4322 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4323 return DEAD_OBJECT;
4324 }
4325 } else {
4326 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4327 ALOGV("%s: v3.2 device found", __FUNCTION__);
4328 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004329 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004330 [&status, &finalConfiguration_3_2]
4331 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4332 finalConfiguration_3_2 = halConfiguration;
4333 status = s;
4334 });
4335 if (!err.isOk()) {
4336 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4337 return DEAD_OBJECT;
4338 }
4339 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4340 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4341 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4342 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004343 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004344 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004345 }
4346
4347 if (status != common::V1_0::Status::OK ) {
4348 return CameraProviderManager::mapToStatusT(status);
4349 }
4350
4351 // And convert output stream configuration from HIDL
4352
4353 for (size_t i = 0; i < config->num_streams; i++) {
4354 camera3_stream_t *dst = config->streams[i];
4355 int streamId = Camera3Stream::cast(dst)->getId();
4356
4357 // Start scan at i, with the assumption that the stream order matches
4358 size_t realIdx = i;
4359 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004360 size_t halStreamCount = finalConfiguration.streams.size();
4361 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004362 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004363 found = true;
4364 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004365 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004366 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004367 }
4368 if (!found) {
4369 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4370 __FUNCTION__, streamId);
4371 return INVALID_OPERATION;
4372 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004373 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004374
Emilian Peev710c1422017-08-30 11:19:38 +01004375 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004376 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4377 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4378
Yin-Chia Yeh90667662019-07-01 15:45:00 -07004379 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07004380 dstStream->setFormatOverride(false);
4381 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004382 if (dst->format != overrideFormat) {
4383 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4384 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004385 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004386 if (dst->data_space != overrideDataSpace) {
4387 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4388 streamId, dst->format);
4389 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004390 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07004391 bool needFormatOverride =
4392 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
4393 bool needDataspaceOverride =
4394 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004395 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07004396 dstStream->setFormatOverride(needFormatOverride);
4397 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004398 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004399 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004400 }
4401
Emilian Peev31abd0a2017-05-11 18:37:46 +01004402 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004403 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004404 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004405 __FUNCTION__, streamId);
4406 return INVALID_OPERATION;
4407 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004408 dstStream->setUsage(
4409 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004410 } else {
4411 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004412 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004413 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4414 __FUNCTION__, streamId);
4415 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004416 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004417 dstStream->setUsage(
4418 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004419 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004420 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004421 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004422
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004423 return res;
4424}
4425
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004426status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004427 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004428 /*out*/std::vector<native_handle_t*>* handlesCreated,
4429 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004430 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004431 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
4432 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
4433 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004434 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004435 }
4436
4437 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004438
4439 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004440
4441 {
4442 std::lock_guard<std::mutex> lock(mInflightLock);
4443 if (request->input_buffer != nullptr) {
4444 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4445 buffer_handle_t buf = *(request->input_buffer->buffer);
4446 auto pair = getBufferId(buf, streamId);
4447 bool isNewBuffer = pair.first;
4448 uint64_t bufferId = pair.second;
4449 captureRequest->inputBuffer.streamId = streamId;
4450 captureRequest->inputBuffer.bufferId = bufferId;
4451 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4452 captureRequest->inputBuffer.status = BufferStatus::OK;
4453 native_handle_t *acquireFence = nullptr;
4454 if (request->input_buffer->acquire_fence != -1) {
4455 acquireFence = native_handle_create(1,0);
4456 acquireFence->data[0] = request->input_buffer->acquire_fence;
4457 handlesCreated->push_back(acquireFence);
4458 }
4459 captureRequest->inputBuffer.acquireFence = acquireFence;
4460 captureRequest->inputBuffer.releaseFence = nullptr;
4461
4462 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004463 request->input_buffer->buffer);
4464 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004465 } else {
4466 captureRequest->inputBuffer.streamId = -1;
4467 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4468 }
4469
4470 captureRequest->outputBuffers.resize(request->num_output_buffers);
4471 for (size_t i = 0; i < request->num_output_buffers; i++) {
4472 const camera3_stream_buffer_t *src = request->output_buffers + i;
4473 StreamBuffer &dst = captureRequest->outputBuffers[i];
4474 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004475 if (src->buffer != nullptr) {
4476 buffer_handle_t buf = *(src->buffer);
4477 auto pair = getBufferId(buf, streamId);
4478 bool isNewBuffer = pair.first;
4479 dst.bufferId = pair.second;
4480 dst.buffer = isNewBuffer ? buf : nullptr;
4481 native_handle_t *acquireFence = nullptr;
4482 if (src->acquire_fence != -1) {
4483 acquireFence = native_handle_create(1,0);
4484 acquireFence->data[0] = src->acquire_fence;
4485 handlesCreated->push_back(acquireFence);
4486 }
4487 dst.acquireFence = acquireFence;
4488 } else if (mUseHalBufManager) {
4489 // HAL buffer management path
4490 dst.bufferId = BUFFER_ID_NO_BUFFER;
4491 dst.buffer = nullptr;
4492 dst.acquireFence = nullptr;
4493 } else {
4494 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4495 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004496 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004497 dst.streamId = streamId;
4498 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004499 dst.releaseFence = nullptr;
4500
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004501 // Output buffers are empty when using HAL buffer manager
4502 if (!mUseHalBufManager) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004503 pushInflightBufferLocked(captureRequest->frameNumber, streamId, src->buffer);
4504 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004505 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004506 }
4507 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004508 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004509}
4510
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004511void Camera3Device::HalInterface::cleanupNativeHandles(
4512 std::vector<native_handle_t*> *handles, bool closeFd) {
4513 if (handles == nullptr) {
4514 return;
4515 }
4516 if (closeFd) {
4517 for (auto& handle : *handles) {
4518 native_handle_close(handle);
4519 }
4520 }
4521 for (auto& handle : *handles) {
4522 native_handle_delete(handle);
4523 }
4524 handles->clear();
4525 return;
4526}
4527
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004528status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4529 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4530 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4531 if (!valid()) return INVALID_OPERATION;
4532
Emilian Peevaebbe412018-01-15 13:53:24 +00004533 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4534 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4535 if (castResult_3_4.isOk()) {
4536 hidlSession_3_4 = castResult_3_4;
4537 }
4538
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004539 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004540 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004541 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004542 if (hidlSession_3_4 != nullptr) {
4543 captureRequests_3_4.resize(batchSize);
4544 } else {
4545 captureRequests.resize(batchSize);
4546 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004547 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004548 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004549
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004550 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004551 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004552 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004553 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004554 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00004555 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004556 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
4557 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004558 }
4559 if (res != OK) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004560 popInflightBuffers(inflightBuffers);
4561 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004562 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004563 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004564 }
4565
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004566 std::vector<device::V3_2::BufferCache> cachesToRemove;
4567 {
4568 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4569 for (auto& pair : mFreedBuffers) {
4570 // The stream might have been removed since onBufferFreed
4571 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4572 cachesToRemove.push_back({pair.first, pair.second});
4573 }
4574 }
4575 mFreedBuffers.clear();
4576 }
4577
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004578 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4579 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004580
4581 // Write metadata to FMQ.
4582 for (size_t i = 0; i < batchSize; i++) {
4583 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004584 device::V3_2::CaptureRequest* captureRequest;
4585 if (hidlSession_3_4 != nullptr) {
4586 captureRequest = &captureRequests_3_4[i].v3_2;
4587 } else {
4588 captureRequest = &captureRequests[i];
4589 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004590
4591 if (request->settings != nullptr) {
4592 size_t settingsSize = get_camera_metadata_size(request->settings);
4593 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4594 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4595 captureRequest->settings.resize(0);
4596 captureRequest->fmqSettingsSize = settingsSize;
4597 } else {
4598 if (mRequestMetadataQueue != nullptr) {
4599 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4600 }
4601 captureRequest->settings.setToExternal(
4602 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4603 get_camera_metadata_size(request->settings));
4604 captureRequest->fmqSettingsSize = 0u;
4605 }
4606 } else {
4607 // A null request settings maps to a size-0 CameraMetadata
4608 captureRequest->settings.resize(0);
4609 captureRequest->fmqSettingsSize = 0u;
4610 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004611
4612 if (hidlSession_3_4 != nullptr) {
4613 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4614 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004615 if (request->physcam_settings != nullptr) {
4616 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4617 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4618 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4619 settingsSize)) {
4620 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4621 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4622 settingsSize;
4623 } else {
4624 if (mRequestMetadataQueue != nullptr) {
4625 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4626 }
4627 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4628 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4629 request->physcam_settings[j])),
4630 get_camera_metadata_size(request->physcam_settings[j]));
4631 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004632 }
Emilian Peev00420d22018-02-05 21:33:13 +00004633 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004634 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004635 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004636 }
4637 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4638 request->physcam_id[j];
4639 }
4640 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004641 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004642
4643 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004644 auto resultCallback =
4645 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4646 status = s;
4647 *numRequestProcessed = n;
4648 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004649 if (hidlSession_3_4 != nullptr) {
4650 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004651 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004652 } else {
4653 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004654 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004655 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004656 if (!err.isOk()) {
4657 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004658 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004659 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004660
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004661 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4662 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4663 __FUNCTION__, *numRequestProcessed, batchSize);
4664 status = common::V1_0::Status::INTERNAL_ERROR;
4665 }
4666
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004667 res = CameraProviderManager::mapToStatusT(status);
4668 if (res == OK) {
4669 if (mHidlSession->isRemote()) {
4670 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
4671 // sent to camera HAL processes)
4672 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
4673 } else {
4674 // In passthrough mode the FDs are now owned by HAL
4675 cleanupNativeHandles(&handlesCreated);
4676 }
4677 } else {
4678 popInflightBuffers(inflightBuffers);
4679 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004680 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004681 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004682}
4683
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004684status_t Camera3Device::HalInterface::flush() {
4685 ATRACE_NAME("CameraHal::flush");
4686 if (!valid()) return INVALID_OPERATION;
4687 status_t res = OK;
4688
Emilian Peev31abd0a2017-05-11 18:37:46 +01004689 auto err = mHidlSession->flush();
4690 if (!err.isOk()) {
4691 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4692 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004693 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004694 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004695 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004696
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004697 return res;
4698}
4699
Emilian Peev31abd0a2017-05-11 18:37:46 +01004700status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004701 ATRACE_NAME("CameraHal::dump");
4702 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004703
Emilian Peev31abd0a2017-05-11 18:37:46 +01004704 // Handled by CameraProviderManager::dump
4705
4706 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004707}
4708
4709status_t Camera3Device::HalInterface::close() {
4710 ATRACE_NAME("CameraHal::close()");
4711 if (!valid()) return INVALID_OPERATION;
4712 status_t res = OK;
4713
Emilian Peev31abd0a2017-05-11 18:37:46 +01004714 auto err = mHidlSession->close();
4715 // Interface will be dead shortly anyway, so don't log errors
4716 if (!err.isOk()) {
4717 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004718 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004719
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004720 return res;
4721}
4722
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004723void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4724 ATRACE_NAME("CameraHal::signalPipelineDrain");
4725 if (!valid() || mHidlSession_3_5 == nullptr) {
4726 ALOGE("%s called on invalid camera!", __FUNCTION__);
4727 return;
4728 }
4729
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004730 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004731 if (!err.isOk()) {
4732 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4733 return;
4734 }
4735}
4736
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004737void Camera3Device::HalInterface::getInflightBufferKeys(
4738 std::vector<std::pair<int32_t, int32_t>>* out) {
4739 std::lock_guard<std::mutex> lock(mInflightLock);
4740 out->clear();
4741 out->reserve(mInflightBufferMap.size());
4742 for (auto& pair : mInflightBufferMap) {
4743 uint64_t key = pair.first;
4744 int32_t streamId = key & 0xFFFFFFFF;
4745 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4746 out->push_back(std::make_pair(frameNumber, streamId));
4747 }
4748 return;
4749}
4750
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004751void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4752 std::vector<uint64_t>* out) {
4753 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4754 out->clear();
4755 out->reserve(mRequestedBuffers.size());
4756 for (auto& pair : mRequestedBuffers) {
4757 out->push_back(pair.first);
4758 }
4759 return;
4760}
4761
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004762status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004763 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004764 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004765 mInflightBufferMap[key] = buffer;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004766 return OK;
4767}
4768
4769status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004770 int32_t frameNumber, int32_t streamId,
4771 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004772 std::lock_guard<std::mutex> lock(mInflightLock);
4773
4774 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4775 auto it = mInflightBufferMap.find(key);
4776 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004777 if (buffer != nullptr) {
4778 *buffer = it->second;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004779 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004780 mInflightBufferMap.erase(it);
4781 return OK;
4782}
4783
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004784void Camera3Device::HalInterface::popInflightBuffers(
4785 const std::vector<std::pair<int32_t, int32_t>>& buffers) {
4786 for (const auto& pair : buffers) {
4787 int32_t frameNumber = pair.first;
4788 int32_t streamId = pair.second;
4789 popInflightBuffer(frameNumber, streamId, nullptr);
4790 }
4791}
4792
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004793status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004794 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004795 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004796 auto pair = mRequestedBuffers.insert({bufferId, {streamId, buf}});
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004797 if (!pair.second) {
4798 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4799 __FUNCTION__, bufferId);
4800 return BAD_VALUE;
4801 }
4802 return OK;
4803}
4804
4805// Find and pop a buffer_handle_t based on bufferId
4806status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004807 uint64_t bufferId,
4808 /*out*/ buffer_handle_t** buffer,
4809 /*optional out*/ int32_t* streamId) {
4810 if (buffer == nullptr) {
4811 ALOGE("%s: buffer (%p) must not be null", __FUNCTION__, buffer);
4812 return BAD_VALUE;
4813 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004814 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4815 auto it = mRequestedBuffers.find(bufferId);
4816 if (it == mRequestedBuffers.end()) {
4817 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4818 __FUNCTION__, bufferId);
4819 return BAD_VALUE;
4820 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004821 *buffer = it->second.second;
4822 if (streamId != nullptr) {
4823 *streamId = it->second.first;
4824 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004825 mRequestedBuffers.erase(it);
4826 return OK;
4827}
4828
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004829std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4830 const buffer_handle_t& buf, int streamId) {
4831 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4832
4833 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4834 auto it = bIdMap.find(buf);
4835 if (it == bIdMap.end()) {
4836 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004837 ALOGV("stream %d now have %zu buffer caches, buf %p",
4838 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004839 return std::make_pair(true, mNextBufferId - 1);
4840 } else {
4841 return std::make_pair(false, it->second);
4842 }
4843}
4844
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004845void Camera3Device::HalInterface::onBufferFreed(
4846 int streamId, const native_handle_t* handle) {
4847 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4848 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4849 auto mapIt = mBufferIdMaps.find(streamId);
4850 if (mapIt == mBufferIdMaps.end()) {
4851 // streamId might be from a deleted stream here
4852 ALOGI("%s: stream %d has been removed",
4853 __FUNCTION__, streamId);
4854 return;
4855 }
4856 BufferIdMap& bIdMap = mapIt->second;
4857 auto it = bIdMap.find(handle);
4858 if (it == bIdMap.end()) {
4859 ALOGW("%s: cannot find buffer %p in stream %d",
4860 __FUNCTION__, handle, streamId);
4861 return;
4862 } else {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004863 bufferId = it->second;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004864 bIdMap.erase(it);
4865 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4866 __FUNCTION__, streamId, bIdMap.size(), handle);
4867 }
4868 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4869}
4870
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004871void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
4872 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4873 auto mapIt = mBufferIdMaps.find(streamId);
4874 if (mapIt == mBufferIdMaps.end()) {
4875 ALOGE("%s: streamId %d not found!", __FUNCTION__, streamId);
4876 return;
4877 }
4878
4879 BufferIdMap& bIdMap = mapIt->second;
4880 for (const auto& it : bIdMap) {
4881 uint64_t bufferId = it.second;
4882 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4883 }
4884 bIdMap.clear();
4885}
4886
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004887/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004888 * RequestThread inner class methods
4889 */
4890
4891Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004892 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004893 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4894 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004895 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004896 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004897 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004898 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004899 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004900 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004901 mReconfigured(false),
4902 mDoPause(false),
4903 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004904 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004905 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004906 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004907 mCurrentAfTriggerId(0),
4908 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004909 mRepeatingLastFrameNumber(
4910 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004911 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004912 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004913 mRequestLatency(kRequestLatencyBinSize),
4914 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004915 mLatestSessionParams(sessionParamKeys.size()),
4916 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004917 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004918}
4919
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004920Camera3Device::RequestThread::~RequestThread() {}
4921
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004922void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004923 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004924 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004925 Mutex::Autolock l(mRequestLock);
4926 mListener = listener;
4927}
4928
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004929void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4930 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004931 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004932 Mutex::Autolock l(mRequestLock);
4933 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004934 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004935 // Prepare video stream for high speed recording.
4936 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004937 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004938}
4939
Jianing Wei90e59c92014-03-12 18:29:36 -07004940status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004941 List<sp<CaptureRequest> > &requests,
4942 /*out*/
4943 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004944 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004945 Mutex::Autolock l(mRequestLock);
4946 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4947 ++it) {
4948 mRequestQueue.push_back(*it);
4949 }
4950
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004951 if (lastFrameNumber != NULL) {
4952 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4953 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4954 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4955 *lastFrameNumber);
4956 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004957
Jianing Wei90e59c92014-03-12 18:29:36 -07004958 unpauseForNewRequests();
4959
4960 return OK;
4961}
4962
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004963
4964status_t Camera3Device::RequestThread::queueTrigger(
4965 RequestTrigger trigger[],
4966 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004967 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004968 Mutex::Autolock l(mTriggerMutex);
4969 status_t ret;
4970
4971 for (size_t i = 0; i < count; ++i) {
4972 ret = queueTriggerLocked(trigger[i]);
4973
4974 if (ret != OK) {
4975 return ret;
4976 }
4977 }
4978
4979 return OK;
4980}
4981
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004982const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4983 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004984 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004985 if (d != nullptr) return d->mId;
4986 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004987}
4988
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004989status_t Camera3Device::RequestThread::queueTriggerLocked(
4990 RequestTrigger trigger) {
4991
4992 uint32_t tag = trigger.metadataTag;
4993 ssize_t index = mTriggerMap.indexOfKey(tag);
4994
4995 switch (trigger.getTagType()) {
4996 case TYPE_BYTE:
4997 // fall-through
4998 case TYPE_INT32:
4999 break;
5000 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005001 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
5002 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005003 return INVALID_OPERATION;
5004 }
5005
5006 /**
5007 * Collect only the latest trigger, since we only have 1 field
5008 * in the request settings per trigger tag, and can't send more than 1
5009 * trigger per request.
5010 */
5011 if (index != NAME_NOT_FOUND) {
5012 mTriggerMap.editValueAt(index) = trigger;
5013 } else {
5014 mTriggerMap.add(tag, trigger);
5015 }
5016
5017 return OK;
5018}
5019
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005020status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005021 const RequestList &requests,
5022 /*out*/
5023 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005024 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005025 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005026 if (lastFrameNumber != NULL) {
5027 *lastFrameNumber = mRepeatingLastFrameNumber;
5028 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005029 mRepeatingRequests.clear();
5030 mRepeatingRequests.insert(mRepeatingRequests.begin(),
5031 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005032
5033 unpauseForNewRequests();
5034
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005035 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005036 return OK;
5037}
5038
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07005039bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005040 if (mRepeatingRequests.empty()) {
5041 return false;
5042 }
5043 int32_t requestId = requestIn->mResultExtras.requestId;
5044 const RequestList &repeatRequests = mRepeatingRequests;
5045 // All repeating requests are guaranteed to have same id so only check first quest
5046 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
5047 return (firstRequest->mResultExtras.requestId == requestId);
5048}
5049
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005050status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005051 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005052 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005053 return clearRepeatingRequestsLocked(lastFrameNumber);
5054
5055}
5056
5057status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005058 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005059 if (lastFrameNumber != NULL) {
5060 *lastFrameNumber = mRepeatingLastFrameNumber;
5061 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005062 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005063 return OK;
5064}
5065
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005066status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005067 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005068 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005069 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005070 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005071
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005072 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005073
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005074 // Send errors for all requests pending in the request queue, including
5075 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005076 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005077 if (listener != NULL) {
5078 for (RequestList::iterator it = mRequestQueue.begin();
5079 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005080 // Abort the input buffers for reprocess requests.
5081 if ((*it)->mInputStream != NULL) {
5082 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07005083 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
5084 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005085 if (res != OK) {
5086 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
5087 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5088 } else {
5089 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
5090 if (res != OK) {
5091 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
5092 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5093 }
5094 }
5095 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005096 // Set the frame number this request would have had, if it
5097 // had been submitted; this frame number will not be reused.
5098 // The requestId and burstId fields were set when the request was
5099 // submitted originally (in convertMetadataListToRequestListLocked)
5100 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005101 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005102 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005103 }
5104 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005105 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08005106
5107 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005108 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005109 if (lastFrameNumber != NULL) {
5110 *lastFrameNumber = mRepeatingLastFrameNumber;
5111 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005112 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005113 return OK;
5114}
5115
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005116status_t Camera3Device::RequestThread::flush() {
5117 ATRACE_CALL();
5118 Mutex::Autolock l(mFlushLock);
5119
Emilian Peev08dd2452017-04-06 16:55:14 +01005120 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005121}
5122
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005123void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005124 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005125 Mutex::Autolock l(mPauseLock);
5126 mDoPause = paused;
5127 mDoPauseSignal.signal();
5128}
5129
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005130status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
5131 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005132 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005133 Mutex::Autolock l(mLatestRequestMutex);
5134 status_t res;
5135 while (mLatestRequestId != requestId) {
5136 nsecs_t startTime = systemTime();
5137
5138 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
5139 if (res != OK) return res;
5140
5141 timeout -= (systemTime() - startTime);
5142 }
5143
5144 return OK;
5145}
5146
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005147void Camera3Device::RequestThread::requestExit() {
5148 // Call parent to set up shutdown
5149 Thread::requestExit();
5150 // The exit from any possible waits
5151 mDoPauseSignal.signal();
5152 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07005153
5154 mRequestLatency.log("ProcessCaptureRequest latency histogram");
5155 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005156}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005157
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005158void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005159 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005160 bool surfaceAbandoned = false;
5161 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005162 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005163 {
5164 Mutex::Autolock l(mRequestLock);
5165 // Check all streams needed by repeating requests are still valid. Otherwise, stop
5166 // repeating requests.
5167 for (const auto& request : mRepeatingRequests) {
5168 for (const auto& s : request->mOutputStreams) {
5169 if (s->isAbandoned()) {
5170 surfaceAbandoned = true;
5171 clearRepeatingRequestsLocked(&lastFrameNumber);
5172 break;
5173 }
5174 }
5175 if (surfaceAbandoned) {
5176 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005177 }
5178 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005179 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005180 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005181
5182 if (listener != NULL && surfaceAbandoned) {
5183 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005184 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005185}
5186
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005187bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005188 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005189 status_t res;
5190 size_t batchSize = mNextRequests.size();
5191 std::vector<camera3_capture_request_t*> requests(batchSize);
5192 uint32_t numRequestProcessed = 0;
5193 for (size_t i = 0; i < batchSize; i++) {
5194 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07005195 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005196 }
5197
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005198 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
5199
5200 bool triggerRemoveFailed = false;
5201 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
5202 for (size_t i = 0; i < numRequestProcessed; i++) {
5203 NextRequest& nextRequest = mNextRequests.editItemAt(i);
5204 nextRequest.submitted = true;
5205
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005206 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00005207
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005208 if (!triggerRemoveFailed) {
5209 // Remove any previously queued triggers (after unlock)
5210 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5211 if (removeTriggerRes != OK) {
5212 triggerRemoveFailed = true;
5213 triggerFailedRequest = nextRequest;
5214 }
5215 }
5216 }
5217
5218 if (triggerRemoveFailed) {
5219 SET_ERR("RequestThread: Unable to remove triggers "
5220 "(capture request %d, HAL device: %s (%d)",
5221 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5222 cleanUpFailedRequests(/*sendRequestError*/ false);
5223 return false;
5224 }
5225
5226 if (res != OK) {
5227 // Should only get a failure here for malformed requests or device-level
5228 // errors, so consider all errors fatal. Bad metadata failures should
5229 // come through notify.
5230 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5231 mNextRequests[numRequestProcessed].halRequest.frame_number,
5232 strerror(-res), res);
5233 cleanUpFailedRequests(/*sendRequestError*/ false);
5234 return false;
5235 }
5236 return true;
5237}
5238
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005239nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5240 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5241 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5242 find_camera_metadata_ro_entry(request,
5243 ANDROID_CONTROL_AE_MODE,
5244 &e);
5245 if (e.count == 0) return maxExpectedDuration;
5246
5247 switch (e.data.u8[0]) {
5248 case ANDROID_CONTROL_AE_MODE_OFF:
5249 find_camera_metadata_ro_entry(request,
5250 ANDROID_SENSOR_EXPOSURE_TIME,
5251 &e);
5252 if (e.count > 0) {
5253 maxExpectedDuration = e.data.i64[0];
5254 }
5255 find_camera_metadata_ro_entry(request,
5256 ANDROID_SENSOR_FRAME_DURATION,
5257 &e);
5258 if (e.count > 0) {
5259 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5260 }
5261 break;
5262 default:
5263 find_camera_metadata_ro_entry(request,
5264 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5265 &e);
5266 if (e.count > 1) {
5267 maxExpectedDuration = 1e9 / e.data.u8[0];
5268 }
5269 break;
5270 }
5271
5272 return maxExpectedDuration;
5273}
5274
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005275bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5276 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5277 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5278 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5279 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5280 return true;
5281 }
5282
5283 return false;
5284}
5285
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005286void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
5287 // Update the latest request sent to HAL
5288 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5289 Mutex::Autolock al(mLatestRequestMutex);
5290
5291 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5292 mLatestRequest.acquire(cloned);
5293
5294 mLatestPhysicalRequest.clear();
5295 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
5296 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
5297 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
5298 CameraMetadata(cloned));
5299 }
5300
5301 sp<Camera3Device> parent = mParent.promote();
5302 if (parent != NULL) {
5303 parent->monitorMetadata(TagMonitor::REQUEST,
5304 nextRequest.halRequest.frame_number,
5305 0, mLatestRequest, mLatestPhysicalRequest);
5306 }
5307 }
5308
5309 if (nextRequest.halRequest.settings != NULL) {
5310 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5311 nextRequest.halRequest.settings);
5312 }
5313
5314 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5315}
5316
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005317bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5318 ATRACE_CALL();
5319 bool updatesDetected = false;
5320
Emilian Peev4ec17882019-01-24 17:16:58 -08005321 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005322 for (auto tag : mSessionParamKeys) {
5323 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005324 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005325
5326 if (entry.count > 0) {
5327 bool isDifferent = false;
5328 if (lastEntry.count > 0) {
5329 // Have a last value, compare to see if changed
5330 if (lastEntry.type == entry.type &&
5331 lastEntry.count == entry.count) {
5332 // Same type and count, compare values
5333 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5334 size_t entryBytes = bytesPerValue * lastEntry.count;
5335 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5336 if (cmp != 0) {
5337 isDifferent = true;
5338 }
5339 } else {
5340 // Count or type has changed
5341 isDifferent = true;
5342 }
5343 } else {
5344 // No last entry, so always consider to be different
5345 isDifferent = true;
5346 }
5347
5348 if (isDifferent) {
5349 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005350 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5351 updatesDetected = true;
5352 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005353 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005354 }
5355 } else if (lastEntry.count > 0) {
5356 // Value has been removed
5357 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005358 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005359 updatesDetected = true;
5360 }
5361 }
5362
Emilian Peev4ec17882019-01-24 17:16:58 -08005363 bool reconfigureRequired;
5364 if (updatesDetected) {
5365 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5366 updatedParams);
5367 mLatestSessionParams = updatedParams;
5368 } else {
5369 reconfigureRequired = false;
5370 }
5371
5372 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005373}
5374
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005375bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005376 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005377 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08005378 // Any function called from threadLoop() must not hold mInterfaceLock since
5379 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
5380 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005381
5382 // Handle paused state.
5383 if (waitIfPaused()) {
5384 return true;
5385 }
5386
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005387 // Wait for the next batch of requests.
5388 waitForNextRequestBatch();
5389 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005390 return true;
5391 }
5392
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005393 // Get the latest request ID, if any
5394 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005395 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005396 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005397 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005398 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005399 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005400 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5401 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005402 }
5403
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005404 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5405 // or a single request from streaming or burst. In either case the first element
5406 // should contain the latest camera settings that we need to check for any session
5407 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005408 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005409 res = OK;
5410
5411 //Input stream buffers are already acquired at this point so an input stream
5412 //will not be able to move to idle state unless we force it.
5413 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5414 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5415 if (res != OK) {
5416 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5417 cleanUpFailedRequests(/*sendRequestError*/ false);
5418 return false;
5419 }
5420 }
5421
5422 if (res == OK) {
5423 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5424 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005425 sp<Camera3Device> parent = mParent.promote();
5426 if (parent != nullptr) {
5427 parent->pauseStateNotify(true);
5428 }
5429
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005430 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5431
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005432 if (parent != nullptr) {
5433 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5434 }
5435
5436 statusTracker->markComponentActive(mStatusId);
5437 setPaused(false);
5438 }
5439
5440 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5441 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5442 if (res != OK) {
5443 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5444 cleanUpFailedRequests(/*sendRequestError*/ false);
5445 return false;
5446 }
5447 }
5448 }
5449 }
5450
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005451 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005452 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005453 if (res == TIMED_OUT) {
5454 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005455 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005456 // Check if any stream is abandoned.
5457 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005458 return true;
5459 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005460 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005461 return false;
5462 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005463
Zhijun Hecc27e112013-10-03 16:12:43 -07005464 // Inform waitUntilRequestProcessed thread of a new request ID
5465 {
5466 Mutex::Autolock al(mLatestRequestMutex);
5467
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005468 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005469 mLatestRequestSignal.signal();
5470 }
5471
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005472 // Submit a batch of requests to HAL.
5473 // Use flush lock only when submitting multilple requests in a batch.
5474 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5475 // which may take a long time to finish so synchronizing flush() and
5476 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5477 // For now, only synchronize for high speed recording and we should figure something out for
5478 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005479 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005480
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005481 if (useFlushLock) {
5482 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005483 }
5484
Zhijun Hef0645c12016-08-02 00:58:11 -07005485 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005486 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005487
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005488 sp<Camera3Device> parent = mParent.promote();
5489 if (parent != nullptr) {
5490 parent->mRequestBufferSM.onSubmittingRequest();
5491 }
5492
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005493 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005494 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07005495 submitRequestSuccess = sendRequestsBatch();
5496
Shuzhen Wang686f6442017-06-20 16:16:04 -07005497 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5498 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005499
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005500 if (useFlushLock) {
5501 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005502 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005503
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005504 // Unset as current request
5505 {
5506 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005507 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005508 }
5509
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005510 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005511}
5512
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005513status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005514 ATRACE_CALL();
5515
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005516 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005517 for (size_t i = 0; i < mNextRequests.size(); i++) {
5518 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005519 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5520 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5521 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5522
5523 // Prepare a request to HAL
5524 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5525
5526 // Insert any queued triggers (before metadata is locked)
5527 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005528 if (res < 0) {
5529 SET_ERR("RequestThread: Unable to insert triggers "
5530 "(capture request %d, HAL device: %s (%d)",
5531 halRequest->frame_number, strerror(-res), res);
5532 return INVALID_OPERATION;
5533 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005534
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005535 int triggerCount = res;
5536 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5537 mPrevTriggers = triggerCount;
5538
5539 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005540 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5541 // Request settings are all the same within one batch, so only treat the first
5542 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005543 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005544 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005545 /**
5546 * HAL workaround:
5547 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5548 */
5549 res = addDummyTriggerIds(captureRequest);
5550 if (res != OK) {
5551 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5552 "(capture request %d, HAL device: %s (%d)",
5553 halRequest->frame_number, strerror(-res), res);
5554 return INVALID_OPERATION;
5555 }
5556
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005557 {
5558 // Correct metadata regions for distortion correction if enabled
5559 sp<Camera3Device> parent = mParent.promote();
5560 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07005561 List<PhysicalCameraSettings>::iterator it;
5562 for (it = captureRequest->mSettingsList.begin();
5563 it != captureRequest->mSettingsList.end(); it++) {
5564 if (parent->mDistortionMappers.find(it->cameraId) ==
5565 parent->mDistortionMappers.end()) {
5566 continue;
5567 }
5568 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
5569 &(it->metadata));
5570 if (res != OK) {
5571 SET_ERR("RequestThread: Unable to correct capture requests "
5572 "for lens distortion for request %d: %s (%d)",
5573 halRequest->frame_number, strerror(-res), res);
5574 return INVALID_OPERATION;
5575 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005576 }
5577 }
5578 }
5579
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005580 /**
5581 * The request should be presorted so accesses in HAL
5582 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5583 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005584 captureRequest->mSettingsList.begin()->metadata.sort();
5585 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005586 mPrevRequest = captureRequest;
5587 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5588
5589 IF_ALOGV() {
5590 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5591 find_camera_metadata_ro_entry(
5592 halRequest->settings,
5593 ANDROID_CONTROL_AF_TRIGGER,
5594 &e
5595 );
5596 if (e.count > 0) {
5597 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5598 __FUNCTION__,
5599 halRequest->frame_number,
5600 e.data.u8[0]);
5601 }
5602 }
5603 } else {
5604 // leave request.settings NULL to indicate 'reuse latest given'
5605 ALOGVV("%s: Request settings are REUSED",
5606 __FUNCTION__);
5607 }
5608
Emilian Peevaebbe412018-01-15 13:53:24 +00005609 if (captureRequest->mSettingsList.size() > 1) {
5610 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5611 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005612 if (newRequest) {
5613 halRequest->physcam_settings =
5614 new const camera_metadata* [halRequest->num_physcam_settings];
5615 } else {
5616 halRequest->physcam_settings = nullptr;
5617 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005618 auto it = ++captureRequest->mSettingsList.begin();
5619 size_t i = 0;
5620 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5621 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005622 if (newRequest) {
5623 it->metadata.sort();
5624 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5625 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005626 }
5627 }
5628
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005629 uint32_t totalNumBuffers = 0;
5630
5631 // Fill in buffers
5632 if (captureRequest->mInputStream != NULL) {
5633 halRequest->input_buffer = &captureRequest->mInputBuffer;
5634 totalNumBuffers += 1;
5635 } else {
5636 halRequest->input_buffer = NULL;
5637 }
5638
5639 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5640 captureRequest->mOutputStreams.size());
5641 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005642 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005643
5644 sp<Camera3Device> parent = mParent.promote();
5645 if (parent == NULL) {
5646 // Should not happen, and nowhere to send errors to, so just log it
5647 CLOGE("RequestThread: Parent is gone");
5648 return INVALID_OPERATION;
5649 }
5650 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5651
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005652 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005653 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005654 sp<Camera3OutputStreamInterface> outputStream =
5655 captureRequest->mOutputStreams.editItemAt(j);
5656 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005657
5658 // Prepare video buffers for high speed recording on the first video request.
5659 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5660 // Only try to prepare video stream on the first video request.
5661 mPrepareVideoStream = false;
5662
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005663 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5664 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005665 while (res == NOT_ENOUGH_DATA) {
5666 res = outputStream->prepareNextBuffer();
5667 }
5668 if (res != OK) {
5669 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5670 __FUNCTION__, strerror(-res), res);
5671 outputStream->cancelPrepare();
5672 }
5673 }
5674
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005675 std::vector<size_t> uniqueSurfaceIds;
5676 res = outputStream->getUniqueSurfaceIds(
5677 captureRequest->mOutputSurfaces[streamId],
5678 &uniqueSurfaceIds);
5679 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5680 if (res != OK && res != INVALID_OPERATION) {
5681 ALOGE("%s: failed to query stream %d unique surface IDs",
5682 __FUNCTION__, streamId);
5683 return res;
5684 }
5685 if (res == OK) {
5686 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5687 }
5688
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005689 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005690 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005691 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005692 return TIMED_OUT;
5693 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005694 // HAL will request buffer through requestStreamBuffer API
5695 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5696 buffer.stream = outputStream->asHalStream();
5697 buffer.buffer = nullptr;
5698 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5699 buffer.acquire_fence = -1;
5700 buffer.release_fence = -1;
5701 } else {
5702 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5703 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005704 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005705 if (res != OK) {
5706 // Can't get output buffer from gralloc queue - this could be due to
5707 // abandoned queue or other consumer misbehavior, so not a fatal
5708 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005709 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005710 " %s (%d)", strerror(-res), res);
5711
5712 return TIMED_OUT;
5713 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005714 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005715
5716 {
5717 sp<Camera3Device> parent = mParent.promote();
5718 if (parent != nullptr) {
5719 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5720 for (const auto& settings : captureRequest->mSettingsList) {
5721 if ((streamCameraId.isEmpty() &&
5722 parent->getId() == settings.cameraId.c_str()) ||
5723 streamCameraId == settings.cameraId.c_str()) {
5724 outputStream->fireBufferRequestForFrameNumber(
5725 captureRequest->mResultExtras.frameNumber,
5726 settings.metadata);
5727 }
5728 }
5729 }
5730 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005731
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005732 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5733
5734 if (!physicalCameraId.isEmpty()) {
5735 // Physical stream isn't supported for input request.
5736 if (halRequest->input_buffer) {
5737 CLOGE("Physical stream is not supported for input request");
5738 return INVALID_OPERATION;
5739 }
5740 requestedPhysicalCameras.insert(physicalCameraId);
5741 }
5742 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005743 }
5744 totalNumBuffers += halRequest->num_output_buffers;
5745
5746 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005747 // If this request list is for constrained high speed recording (not
5748 // preview), and the current request is not the last one in the batch,
5749 // do not send callback to the app.
5750 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005751 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005752 hasCallback = false;
5753 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005754 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005755 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005756 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5757 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5758 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5759 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5760 isStillCapture = true;
5761 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5762 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005763
5764 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5765 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5766 isZslCapture = true;
5767 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005768 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005769 res = parent->registerInFlight(halRequest->frame_number,
5770 totalNumBuffers, captureRequest->mResultExtras,
5771 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005772 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005773 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005774 requestedPhysicalCameras, isStillCapture, isZslCapture,
5775 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5776 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005777 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5778 ", burstId = %" PRId32 ".",
5779 __FUNCTION__,
5780 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5781 captureRequest->mResultExtras.burstId);
5782 if (res != OK) {
5783 SET_ERR("RequestThread: Unable to register new in-flight request:"
5784 " %s (%d)", strerror(-res), res);
5785 return INVALID_OPERATION;
5786 }
5787 }
5788
5789 return OK;
5790}
5791
Igor Murashkin1e479c02013-09-06 16:55:14 -07005792CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005793 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005794 Mutex::Autolock al(mLatestRequestMutex);
5795
5796 ALOGV("RequestThread::%s", __FUNCTION__);
5797
5798 return mLatestRequest;
5799}
5800
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005801bool Camera3Device::RequestThread::isStreamPending(
5802 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005803 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005804 Mutex::Autolock l(mRequestLock);
5805
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005806 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005807 if (!nextRequest.submitted) {
5808 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5809 if (stream == s) return true;
5810 }
5811 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005812 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005813 }
5814
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005815 for (const auto& request : mRequestQueue) {
5816 for (const auto& s : request->mOutputStreams) {
5817 if (stream == s) return true;
5818 }
5819 if (stream == request->mInputStream) return true;
5820 }
5821
5822 for (const auto& request : mRepeatingRequests) {
5823 for (const auto& s : request->mOutputStreams) {
5824 if (stream == s) return true;
5825 }
5826 if (stream == request->mInputStream) return true;
5827 }
5828
5829 return false;
5830}
Jianing Weicb0652e2014-03-12 18:29:36 -07005831
Emilian Peev40ead602017-09-26 15:46:36 +01005832bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5833 ATRACE_CALL();
5834 Mutex::Autolock l(mRequestLock);
5835
5836 for (const auto& nextRequest : mNextRequests) {
5837 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5838 if (s.first == streamId) {
5839 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5840 if (it != s.second.end()) {
5841 return true;
5842 }
5843 }
5844 }
5845 }
5846
5847 for (const auto& request : mRequestQueue) {
5848 for (const auto& s : request->mOutputSurfaces) {
5849 if (s.first == streamId) {
5850 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5851 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005852 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005853 }
5854 }
5855 }
5856 }
5857
5858 for (const auto& request : mRepeatingRequests) {
5859 for (const auto& s : request->mOutputSurfaces) {
5860 if (s.first == streamId) {
5861 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5862 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005863 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005864 }
5865 }
5866 }
5867 }
5868
5869 return false;
5870}
5871
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005872void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5873 if (!mUseHalBufManager) {
5874 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5875 return;
5876 }
5877
5878 Mutex::Autolock pl(mPauseLock);
5879 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005880 mInterface->signalPipelineDrain(streamIds);
5881 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005882 }
5883 // If request thread is still busy, wait until paused then notify HAL
5884 mNotifyPipelineDrain = true;
5885 mStreamIdsToBeDrained = streamIds;
5886}
5887
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005888nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005889 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005890 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005891 return mExpectedInflightDuration > kMinInflightDuration ?
5892 mExpectedInflightDuration : kMinInflightDuration;
5893}
5894
Emilian Peevaebbe412018-01-15 13:53:24 +00005895void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5896 camera3_capture_request_t *halRequest) {
5897 if ((request == nullptr) || (halRequest == nullptr)) {
5898 ALOGE("%s: Invalid request!", __FUNCTION__);
5899 return;
5900 }
5901
5902 if (halRequest->num_physcam_settings > 0) {
5903 if (halRequest->physcam_id != nullptr) {
5904 delete [] halRequest->physcam_id;
5905 halRequest->physcam_id = nullptr;
5906 }
5907 if (halRequest->physcam_settings != nullptr) {
5908 auto it = ++(request->mSettingsList.begin());
5909 size_t i = 0;
5910 for (; it != request->mSettingsList.end(); it++, i++) {
5911 it->metadata.unlock(halRequest->physcam_settings[i]);
5912 }
5913 delete [] halRequest->physcam_settings;
5914 halRequest->physcam_settings = nullptr;
5915 }
5916 }
5917}
5918
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005919void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5920 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005921 return;
5922 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005923
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005924 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005925 // Skip the ones that have been submitted successfully.
5926 if (nextRequest.submitted) {
5927 continue;
5928 }
5929
5930 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5931 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5932 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5933
5934 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005935 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005936 }
5937
Emilian Peevaebbe412018-01-15 13:53:24 +00005938 cleanupPhysicalSettings(captureRequest, halRequest);
5939
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005940 if (captureRequest->mInputStream != NULL) {
5941 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5942 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5943 }
5944
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005945 // No output buffer can be returned when using HAL buffer manager
5946 if (!mUseHalBufManager) {
5947 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5948 //Buffers that failed processing could still have
5949 //valid acquire fence.
5950 int acquireFence = (*outputBuffers)[i].acquire_fence;
5951 if (0 <= acquireFence) {
5952 close(acquireFence);
5953 outputBuffers->editItemAt(i).acquire_fence = -1;
5954 }
5955 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5956 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5957 /*timestampIncreasing*/true, std::vector<size_t> (),
5958 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005959 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005960 }
5961
5962 if (sendRequestError) {
5963 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005964 sp<NotificationListener> listener = mListener.promote();
5965 if (listener != NULL) {
5966 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005967 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005968 captureRequest->mResultExtras);
5969 }
5970 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005971
5972 // Remove yet-to-be submitted inflight request from inflightMap
5973 {
5974 sp<Camera3Device> parent = mParent.promote();
5975 if (parent != NULL) {
5976 Mutex::Autolock l(parent->mInFlightLock);
5977 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5978 if (idx >= 0) {
5979 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5980 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5981 parent->removeInFlightMapEntryLocked(idx);
5982 }
5983 }
5984 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005985 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005986
5987 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005988 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005989}
5990
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005991void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005992 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005993 // Optimized a bit for the simple steady-state case (single repeating
5994 // request), to avoid putting that request in the queue temporarily.
5995 Mutex::Autolock l(mRequestLock);
5996
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005997 assert(mNextRequests.empty());
5998
5999 NextRequest nextRequest;
6000 nextRequest.captureRequest = waitForNextRequestLocked();
6001 if (nextRequest.captureRequest == nullptr) {
6002 return;
6003 }
6004
6005 nextRequest.halRequest = camera3_capture_request_t();
6006 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006007 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006008
6009 // Wait for additional requests
6010 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
6011
6012 for (size_t i = 1; i < batchSize; i++) {
6013 NextRequest additionalRequest;
6014 additionalRequest.captureRequest = waitForNextRequestLocked();
6015 if (additionalRequest.captureRequest == nullptr) {
6016 break;
6017 }
6018
6019 additionalRequest.halRequest = camera3_capture_request_t();
6020 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006021 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006022 }
6023
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006024 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006025 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006026 mNextRequests.size(), batchSize);
6027 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006028 }
6029
6030 return;
6031}
6032
6033sp<Camera3Device::CaptureRequest>
6034 Camera3Device::RequestThread::waitForNextRequestLocked() {
6035 status_t res;
6036 sp<CaptureRequest> nextRequest;
6037
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006038 while (mRequestQueue.empty()) {
6039 if (!mRepeatingRequests.empty()) {
6040 // Always atomically enqueue all requests in a repeating request
6041 // list. Guarantees a complete in-sequence set of captures to
6042 // application.
6043 const RequestList &requests = mRepeatingRequests;
6044 RequestList::const_iterator firstRequest =
6045 requests.begin();
6046 nextRequest = *firstRequest;
6047 mRequestQueue.insert(mRequestQueue.end(),
6048 ++firstRequest,
6049 requests.end());
6050 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07006051
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006052 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07006053
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006054 break;
6055 }
6056
6057 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
6058
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006059 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
6060 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006061 Mutex::Autolock pl(mPauseLock);
6062 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006063 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006064 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006065 if (mNotifyPipelineDrain) {
6066 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6067 mNotifyPipelineDrain = false;
6068 mStreamIdsToBeDrained.clear();
6069 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006070 // Let the tracker know
6071 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6072 if (statusTracker != 0) {
6073 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6074 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006075 sp<Camera3Device> parent = mParent.promote();
6076 if (parent != nullptr) {
6077 parent->mRequestBufferSM.onRequestThreadPaused();
6078 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006079 }
6080 // Stop waiting for now and let thread management happen
6081 return NULL;
6082 }
6083 }
6084
6085 if (nextRequest == NULL) {
6086 // Don't have a repeating request already in hand, so queue
6087 // must have an entry now.
6088 RequestList::iterator firstRequest =
6089 mRequestQueue.begin();
6090 nextRequest = *firstRequest;
6091 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07006092 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
6093 sp<NotificationListener> listener = mListener.promote();
6094 if (listener != NULL) {
6095 listener->notifyRequestQueueEmpty();
6096 }
6097 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006098 }
6099
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006100 // In case we've been unpaused by setPaused clearing mDoPause, need to
6101 // update internal pause state (capture/setRepeatingRequest unpause
6102 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006103 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006104 if (mPaused) {
6105 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
6106 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6107 if (statusTracker != 0) {
6108 statusTracker->markComponentActive(mStatusId);
6109 }
6110 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006111 mPaused = false;
6112
6113 // Check if we've reconfigured since last time, and reset the preview
6114 // request if so. Can't use 'NULL request == repeat' across configure calls.
6115 if (mReconfigured) {
6116 mPrevRequest.clear();
6117 mReconfigured = false;
6118 }
6119
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006120 if (nextRequest != NULL) {
6121 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006122 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
6123 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006124
6125 // Since RequestThread::clear() removes buffers from the input stream,
6126 // get the right buffer here before unlocking mRequestLock
6127 if (nextRequest->mInputStream != NULL) {
6128 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
6129 if (res != OK) {
6130 // Can't get input buffer from gralloc queue - this could be due to
6131 // disconnected queue or other producer misbehavior, so not a fatal
6132 // error
6133 ALOGE("%s: Can't get input buffer, skipping request:"
6134 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006135
6136 sp<NotificationListener> listener = mListener.promote();
6137 if (listener != NULL) {
6138 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006139 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006140 nextRequest->mResultExtras);
6141 }
6142 return NULL;
6143 }
6144 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006145 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07006146
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006147 return nextRequest;
6148}
6149
6150bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006151 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006152 status_t res;
6153 Mutex::Autolock l(mPauseLock);
6154 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006155 if (mPaused == false) {
6156 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006157 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006158 if (mNotifyPipelineDrain) {
6159 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6160 mNotifyPipelineDrain = false;
6161 mStreamIdsToBeDrained.clear();
6162 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006163 // Let the tracker know
6164 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6165 if (statusTracker != 0) {
6166 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6167 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006168 sp<Camera3Device> parent = mParent.promote();
6169 if (parent != nullptr) {
6170 parent->mRequestBufferSM.onRequestThreadPaused();
6171 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006172 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006173
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006174 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006175 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006176 return true;
6177 }
6178 }
6179 // We don't set mPaused to false here, because waitForNextRequest needs
6180 // to further manage the paused state in case of starvation.
6181 return false;
6182}
6183
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006184void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006185 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006186 // With work to do, mark thread as unpaused.
6187 // If paused by request (setPaused), don't resume, to avoid
6188 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006189 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006190 Mutex::Autolock p(mPauseLock);
6191 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006192 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6193 if (mPaused) {
6194 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6195 if (statusTracker != 0) {
6196 statusTracker->markComponentActive(mStatusId);
6197 }
6198 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006199 mPaused = false;
6200 }
6201}
6202
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006203void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6204 sp<Camera3Device> parent = mParent.promote();
6205 if (parent != NULL) {
6206 va_list args;
6207 va_start(args, fmt);
6208
6209 parent->setErrorStateV(fmt, args);
6210
6211 va_end(args);
6212 }
6213}
6214
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006215status_t Camera3Device::RequestThread::insertTriggers(
6216 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006217 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006218 Mutex::Autolock al(mTriggerMutex);
6219
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006220 sp<Camera3Device> parent = mParent.promote();
6221 if (parent == NULL) {
6222 CLOGE("RequestThread: Parent is gone");
6223 return DEAD_OBJECT;
6224 }
6225
Emilian Peevaebbe412018-01-15 13:53:24 +00006226 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006227 size_t count = mTriggerMap.size();
6228
6229 for (size_t i = 0; i < count; ++i) {
6230 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006231 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006232
6233 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6234 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6235 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006236 if (isAeTrigger) {
6237 request->mResultExtras.precaptureTriggerId = triggerId;
6238 mCurrentPreCaptureTriggerId = triggerId;
6239 } else {
6240 request->mResultExtras.afTriggerId = triggerId;
6241 mCurrentAfTriggerId = triggerId;
6242 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006243 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006244 }
6245
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006246 camera_metadata_entry entry = metadata.find(tag);
6247
6248 if (entry.count > 0) {
6249 /**
6250 * Already has an entry for this trigger in the request.
6251 * Rewrite it with our requested trigger value.
6252 */
6253 RequestTrigger oldTrigger = trigger;
6254
6255 oldTrigger.entryValue = entry.data.u8[0];
6256
6257 mTriggerReplacedMap.add(tag, oldTrigger);
6258 } else {
6259 /**
6260 * More typical, no trigger entry, so we just add it
6261 */
6262 mTriggerRemovedMap.add(tag, trigger);
6263 }
6264
6265 status_t res;
6266
6267 switch (trigger.getTagType()) {
6268 case TYPE_BYTE: {
6269 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6270 res = metadata.update(tag,
6271 &entryValue,
6272 /*count*/1);
6273 break;
6274 }
6275 case TYPE_INT32:
6276 res = metadata.update(tag,
6277 &trigger.entryValue,
6278 /*count*/1);
6279 break;
6280 default:
6281 ALOGE("%s: Type not supported: 0x%x",
6282 __FUNCTION__,
6283 trigger.getTagType());
6284 return INVALID_OPERATION;
6285 }
6286
6287 if (res != OK) {
6288 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6289 ", value %d", __FUNCTION__, trigger.getTagName(),
6290 trigger.entryValue);
6291 return res;
6292 }
6293
6294 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6295 trigger.getTagName(),
6296 trigger.entryValue);
6297 }
6298
6299 mTriggerMap.clear();
6300
6301 return count;
6302}
6303
6304status_t Camera3Device::RequestThread::removeTriggers(
6305 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006306 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006307 Mutex::Autolock al(mTriggerMutex);
6308
Emilian Peevaebbe412018-01-15 13:53:24 +00006309 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006310
6311 /**
6312 * Replace all old entries with their old values.
6313 */
6314 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6315 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6316
6317 status_t res;
6318
6319 uint32_t tag = trigger.metadataTag;
6320 switch (trigger.getTagType()) {
6321 case TYPE_BYTE: {
6322 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6323 res = metadata.update(tag,
6324 &entryValue,
6325 /*count*/1);
6326 break;
6327 }
6328 case TYPE_INT32:
6329 res = metadata.update(tag,
6330 &trigger.entryValue,
6331 /*count*/1);
6332 break;
6333 default:
6334 ALOGE("%s: Type not supported: 0x%x",
6335 __FUNCTION__,
6336 trigger.getTagType());
6337 return INVALID_OPERATION;
6338 }
6339
6340 if (res != OK) {
6341 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6342 ", trigger value %d", __FUNCTION__,
6343 trigger.getTagName(), trigger.entryValue);
6344 return res;
6345 }
6346 }
6347 mTriggerReplacedMap.clear();
6348
6349 /**
6350 * Remove all new entries.
6351 */
6352 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6353 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6354 status_t res = metadata.erase(trigger.metadataTag);
6355
6356 if (res != OK) {
6357 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6358 ", trigger value %d", __FUNCTION__,
6359 trigger.getTagName(), trigger.entryValue);
6360 return res;
6361 }
6362 }
6363 mTriggerRemovedMap.clear();
6364
6365 return OK;
6366}
6367
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006368status_t Camera3Device::RequestThread::addDummyTriggerIds(
6369 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006370 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006371 static const int32_t dummyTriggerId = 1;
6372 status_t res;
6373
Emilian Peevaebbe412018-01-15 13:53:24 +00006374 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006375
6376 // If AF trigger is active, insert a dummy AF trigger ID if none already
6377 // exists
6378 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6379 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6380 if (afTrigger.count > 0 &&
6381 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6382 afId.count == 0) {
6383 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6384 if (res != OK) return res;
6385 }
6386
6387 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6388 // if none already exists
6389 camera_metadata_entry pcTrigger =
6390 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6391 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6392 if (pcTrigger.count > 0 &&
6393 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6394 pcId.count == 0) {
6395 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6396 &dummyTriggerId, 1);
6397 if (res != OK) return res;
6398 }
6399
6400 return OK;
6401}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006402
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006403/**
6404 * PreparerThread inner class methods
6405 */
6406
6407Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006408 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006409 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006410}
6411
6412Camera3Device::PreparerThread::~PreparerThread() {
6413 Thread::requestExitAndWait();
6414 if (mCurrentStream != nullptr) {
6415 mCurrentStream->cancelPrepare();
6416 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6417 mCurrentStream.clear();
6418 }
6419 clear();
6420}
6421
Ruben Brunkc78ac262015-08-13 17:58:46 -07006422status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006423 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006424 status_t res;
6425
6426 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006427 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006428
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006429 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006430 if (res == OK) {
6431 // No preparation needed, fire listener right off
6432 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006433 if (listener != NULL) {
6434 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006435 }
6436 return OK;
6437 } else if (res != NOT_ENOUGH_DATA) {
6438 return res;
6439 }
6440
6441 // Need to prepare, start up thread if necessary
6442 if (!mActive) {
6443 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6444 // isn't running
6445 Thread::requestExitAndWait();
6446 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6447 if (res != OK) {
6448 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006449 if (listener != NULL) {
6450 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006451 }
6452 return res;
6453 }
6454 mCancelNow = false;
6455 mActive = true;
6456 ALOGV("%s: Preparer stream started", __FUNCTION__);
6457 }
6458
6459 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006460 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006461 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6462
6463 return OK;
6464}
6465
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006466void Camera3Device::PreparerThread::pause() {
6467 ATRACE_CALL();
6468
6469 Mutex::Autolock l(mLock);
6470
6471 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6472 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6473 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6474 int currentMaxCount = mCurrentMaxCount;
6475 mPendingStreams.clear();
6476 mCancelNow = true;
6477 while (mActive) {
6478 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6479 if (res == TIMED_OUT) {
6480 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6481 return;
6482 } else if (res != OK) {
6483 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6484 return;
6485 }
6486 }
6487
6488 //Check whether the prepare thread was able to complete the current
6489 //stream. In case work is still pending emplace it along with the rest
6490 //of the streams in the pending list.
6491 if (currentStream != nullptr) {
6492 if (!mCurrentPrepareComplete) {
6493 pendingStreams.emplace(currentMaxCount, currentStream);
6494 }
6495 }
6496
6497 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6498 for (const auto& it : mPendingStreams) {
6499 it.second->cancelPrepare();
6500 }
6501}
6502
6503status_t Camera3Device::PreparerThread::resume() {
6504 ATRACE_CALL();
6505 status_t res;
6506
6507 Mutex::Autolock l(mLock);
6508 sp<NotificationListener> listener = mListener.promote();
6509
6510 if (mActive) {
6511 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6512 return NO_INIT;
6513 }
6514
6515 auto it = mPendingStreams.begin();
6516 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006517 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006518 if (res == OK) {
6519 if (listener != NULL) {
6520 listener->notifyPrepared(it->second->getId());
6521 }
6522 it = mPendingStreams.erase(it);
6523 } else if (res != NOT_ENOUGH_DATA) {
6524 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6525 res, strerror(-res));
6526 it = mPendingStreams.erase(it);
6527 } else {
6528 it++;
6529 }
6530 }
6531
6532 if (mPendingStreams.empty()) {
6533 return OK;
6534 }
6535
6536 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6537 if (res != OK) {
6538 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6539 __FUNCTION__, res, strerror(-res));
6540 return res;
6541 }
6542 mCancelNow = false;
6543 mActive = true;
6544 ALOGV("%s: Preparer stream started", __FUNCTION__);
6545
6546 return OK;
6547}
6548
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006549status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006550 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006551 Mutex::Autolock l(mLock);
6552
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006553 for (const auto& it : mPendingStreams) {
6554 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006555 }
6556 mPendingStreams.clear();
6557 mCancelNow = true;
6558
6559 return OK;
6560}
6561
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006562void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006563 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006564 Mutex::Autolock l(mLock);
6565 mListener = listener;
6566}
6567
6568bool Camera3Device::PreparerThread::threadLoop() {
6569 status_t res;
6570 {
6571 Mutex::Autolock l(mLock);
6572 if (mCurrentStream == nullptr) {
6573 // End thread if done with work
6574 if (mPendingStreams.empty()) {
6575 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6576 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6577 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6578 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006579 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006580 return false;
6581 }
6582
6583 // Get next stream to prepare
6584 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006585 mCurrentStream = it->second;
6586 mCurrentMaxCount = it->first;
6587 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006588 mPendingStreams.erase(it);
6589 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6590 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6591 } else if (mCancelNow) {
6592 mCurrentStream->cancelPrepare();
6593 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6594 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6595 mCurrentStream.clear();
6596 mCancelNow = false;
6597 return true;
6598 }
6599 }
6600
6601 res = mCurrentStream->prepareNextBuffer();
6602 if (res == NOT_ENOUGH_DATA) return true;
6603 if (res != OK) {
6604 // Something bad happened; try to recover by cancelling prepare and
6605 // signalling listener anyway
6606 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6607 mCurrentStream->getId(), res, strerror(-res));
6608 mCurrentStream->cancelPrepare();
6609 }
6610
6611 // This stream has finished, notify listener
6612 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006613 sp<NotificationListener> listener = mListener.promote();
6614 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006615 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6616 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006617 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006618 }
6619
6620 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6621 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006622 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006623
6624 return true;
6625}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006626
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006627status_t Camera3Device::RequestBufferStateMachine::initialize(
6628 sp<camera3::StatusTracker> statusTracker) {
6629 if (statusTracker == nullptr) {
6630 ALOGE("%s: statusTracker is null", __FUNCTION__);
6631 return BAD_VALUE;
6632 }
6633
6634 std::lock_guard<std::mutex> lock(mLock);
6635 mStatusTracker = statusTracker;
6636 mRequestBufferStatusId = statusTracker->addComponent();
6637 return OK;
6638}
6639
6640bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6641 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006642 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006643 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006644 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006645 return true;
6646 }
6647 return false;
6648}
6649
6650void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6651 std::lock_guard<std::mutex> lock(mLock);
6652 if (!mRequestBufferOngoing) {
6653 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6654 return;
6655 }
6656 mRequestBufferOngoing = false;
6657 if (mStatus == RB_STATUS_PENDING_STOP) {
6658 checkSwitchToStopLocked();
6659 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006660 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006661}
6662
6663void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6664 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006665 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006666 return;
6667}
6668
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006669void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006670 std::lock_guard<std::mutex> lock(mLock);
6671 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006672 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6673 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006674 mInflightMapEmpty = false;
6675 if (mStatus == RB_STATUS_STOPPED) {
6676 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006677 }
6678 return;
6679}
6680
6681void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6682 std::lock_guard<std::mutex> lock(mLock);
6683 mRequestThreadPaused = true;
6684 if (mStatus == RB_STATUS_PENDING_STOP) {
6685 checkSwitchToStopLocked();
6686 }
6687 return;
6688}
6689
6690void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6691 std::lock_guard<std::mutex> lock(mLock);
6692 mInflightMapEmpty = true;
6693 if (mStatus == RB_STATUS_PENDING_STOP) {
6694 checkSwitchToStopLocked();
6695 }
6696 return;
6697}
6698
6699void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6700 std::lock_guard<std::mutex> lock(mLock);
6701 if (!checkSwitchToStopLocked()) {
6702 mStatus = RB_STATUS_PENDING_STOP;
6703 }
6704 return;
6705}
6706
6707void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6708 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6709 if (statusTracker != nullptr) {
6710 if (active) {
6711 statusTracker->markComponentActive(mRequestBufferStatusId);
6712 } else {
6713 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6714 }
6715 }
6716}
6717
6718bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6719 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6720 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006721 return true;
6722 }
6723 return false;
6724}
6725
Shuzhen Wang268a1362018-10-16 16:32:59 -07006726status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6727 CameraMetadata& resultMetadata) {
6728 status_t res = OK;
6729 if (!mNeedFixupMonochromeTags) {
6730 return res;
6731 }
6732
6733 // Remove tags that are not applicable to monochrome camera.
6734 int32_t tagsToRemove[] = {
6735 ANDROID_SENSOR_GREEN_SPLIT,
6736 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6737 ANDROID_COLOR_CORRECTION_MODE,
6738 ANDROID_COLOR_CORRECTION_TRANSFORM,
6739 ANDROID_COLOR_CORRECTION_GAINS,
6740 };
6741 for (auto tag : tagsToRemove) {
6742 res = resultMetadata.erase(tag);
6743 if (res != OK) {
6744 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6745 return res;
6746 }
6747 }
6748
6749 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6750 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6751 for (size_t i = 1; i < blEntry.count; i++) {
6752 blEntry.data.f[i] = blEntry.data.f[0];
6753 }
6754
6755 // ANDROID_SENSOR_NOISE_PROFILE
6756 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6757 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6758 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6759 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6760 if (res != OK) {
6761 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6762 __FUNCTION__, strerror(-res), res);
6763 return res;
6764 }
6765 }
6766
6767 // ANDROID_STATISTICS_LENS_SHADING_MAP
6768 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6769 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6770 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6771 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6772 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6773 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6774 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6775 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6776 }
6777 }
6778
6779 // ANDROID_TONEMAP_CURVE_BLUE
6780 // ANDROID_TONEMAP_CURVE_GREEN
6781 // ANDROID_TONEMAP_CURVE_RED
6782 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6783 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6784 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6785 if (tcbEntry.count > 0
6786 && tcbEntry.count == tcgEntry.count
6787 && tcbEntry.count == tcrEntry.count) {
6788 for (size_t i = 0; i < tcbEntry.count; i++) {
6789 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6790 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6791 }
6792 }
6793
6794 return res;
6795}
6796
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006797}; // namespace android