blob: ed5acd8edf2a55285993e1951ec8f8482316c586 [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();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700342 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800343
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700344 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700345 std::vector<wp<Camera3StreamInterface>> streams;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700346 {
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800347 Mutex::Autolock il(mInterfaceLock);
348 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
349 {
350 Mutex::Autolock l(mLock);
351 if (mStatus == STATUS_UNINITIALIZED) return res;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700352
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800353 if (mStatus == STATUS_ACTIVE ||
354 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
355 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700356 if (res != OK) {
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800357 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700358 // Continue to close device even in case of error
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800359 } else {
360 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
361 if (res != OK) {
362 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
363 maxExpectedDuration);
364 // Continue to close device even in case of error
365 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700366 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700367 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800368
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800369 if (mStatus == STATUS_ERROR) {
370 CLOGE("Shutting down in an error state");
371 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700372
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800373 if (mStatusTracker != NULL) {
374 mStatusTracker->requestExit();
375 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700376
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800377 if (mRequestThread != NULL) {
378 mRequestThread->requestExit();
379 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700380
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800381 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 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700388 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700389 }
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800390 // Joining done without holding mLock and mInterfaceLock, otherwise deadlocks may ensue
391 // as the threads try to access parent state (b/143513518)
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700392 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.
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800396 // give up mInterfaceLock here and then lock it again. Could this lead
397 // to other deadlocks
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700398 mRequestThread->join();
399 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700400 {
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800401 Mutex::Autolock il(mInterfaceLock);
402 if (mStatusTracker != NULL) {
403 mStatusTracker->join();
404 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800405
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800406 HalInterface* interface;
407 {
408 Mutex::Autolock l(mLock);
409 mRequestThread.clear();
410 Mutex::Autolock stLock(mTrackerLock);
411 mStatusTracker.clear();
412 interface = mInterface.get();
413 }
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700414
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800415 // Call close without internal mutex held, as the HAL close may need to
416 // wait on assorted callbacks,etc, to complete before it can return.
417 interface->close();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700418
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800419 flushInflightRequests();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800420
Jayant Chowdharydfc46592020-01-30 13:09:59 -0800421 {
422 Mutex::Autolock l(mLock);
423 mInterface->clear();
424 mOutputStreams.clear();
425 mInputStream.clear();
426 mDeletedStreams.clear();
427 mBufferManager.clear();
428 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
429 }
430
431 for (auto& weakStream : streams) {
432 sp<Camera3StreamInterface> stream = weakStream.promote();
433 if (stream != nullptr) {
434 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
435 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
436 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700437 }
438 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700439 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700440 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800441}
442
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700443// For dumping/debugging only -
444// try to acquire a lock a few times, eventually give up to proceed with
445// debug/dump operations
446bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
447 bool gotLock = false;
448 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
449 if (lock.tryLock() == NO_ERROR) {
450 gotLock = true;
451 break;
452 } else {
453 usleep(kDumpSleepDuration);
454 }
455 }
456 return gotLock;
457}
458
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700459Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
460 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100461 const int STREAM_CONFIGURATION_SIZE = 4;
462 const int STREAM_FORMAT_OFFSET = 0;
463 const int STREAM_WIDTH_OFFSET = 1;
464 const int STREAM_HEIGHT_OFFSET = 2;
465 const int STREAM_IS_INPUT_OFFSET = 3;
466 camera_metadata_ro_entry_t availableStreamConfigs =
467 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
468 if (availableStreamConfigs.count == 0 ||
469 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
470 return Size(0, 0);
471 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700472
Emilian Peev08dd2452017-04-06 16:55:14 +0100473 // Get max jpeg size (area-wise).
474 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
475 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
476 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
477 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
478 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
479 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
480 && format == HAL_PIXEL_FORMAT_BLOB &&
481 (width * height > maxJpegWidth * maxJpegHeight)) {
482 maxJpegWidth = width;
483 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700484 }
485 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100486
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700487 return Size(maxJpegWidth, maxJpegHeight);
488}
489
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800490nsecs_t Camera3Device::getMonoToBoottimeOffset() {
491 // try three times to get the clock offset, choose the one
492 // with the minimum gap in measurements.
493 const int tries = 3;
494 nsecs_t bestGap, measured;
495 for (int i = 0; i < tries; ++i) {
496 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
497 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
498 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
499 const nsecs_t gap = tmono2 - tmono;
500 if (i == 0 || gap < bestGap) {
501 bestGap = gap;
502 measured = tbase - ((tmono + tmono2) >> 1);
503 }
504 }
505 return measured;
506}
507
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800508hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
509 int frameworkFormat) {
510 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
511}
512
513DataspaceFlags Camera3Device::mapToHidlDataspace(
514 android_dataspace dataSpace) {
515 return dataSpace;
516}
517
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700518BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100519 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700520 return usage;
521}
522
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800523StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
524 switch (rotation) {
525 case CAMERA3_STREAM_ROTATION_0:
526 return StreamRotation::ROTATION_0;
527 case CAMERA3_STREAM_ROTATION_90:
528 return StreamRotation::ROTATION_90;
529 case CAMERA3_STREAM_ROTATION_180:
530 return StreamRotation::ROTATION_180;
531 case CAMERA3_STREAM_ROTATION_270:
532 return StreamRotation::ROTATION_270;
533 }
534 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
535 return StreamRotation::ROTATION_0;
536}
537
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800538status_t Camera3Device::mapToStreamConfigurationMode(
539 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
540 if (mode == nullptr) return BAD_VALUE;
541 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
542 switch(operationMode) {
543 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
544 *mode = StreamConfigurationMode::NORMAL_MODE;
545 break;
546 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
547 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
548 break;
549 default:
550 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
551 return BAD_VALUE;
552 }
553 } else {
554 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800555 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800556 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800557}
558
559camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
560 switch (status) {
561 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
562 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
563 }
564 return CAMERA3_BUFFER_STATUS_ERROR;
565}
566
567int Camera3Device::mapToFrameworkFormat(
568 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
569 return static_cast<uint32_t>(pixelFormat);
570}
571
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700572android_dataspace Camera3Device::mapToFrameworkDataspace(
573 DataspaceFlags dataSpace) {
574 return static_cast<android_dataspace>(dataSpace);
575}
576
Emilian Peev050f5dc2017-05-18 14:43:56 +0100577uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700578 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700579 return usage;
580}
581
Emilian Peev050f5dc2017-05-18 14:43:56 +0100582uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700583 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700584 return usage;
585}
586
Zhijun Hef7da0962014-04-24 13:27:56 -0700587ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700588 // Get max jpeg size (area-wise).
589 Size maxJpegResolution = getMaxJpegResolution();
590 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800591 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
592 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700593 return BAD_VALUE;
594 }
595
Zhijun Hef7da0962014-04-24 13:27:56 -0700596 // Get max jpeg buffer size
597 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700598 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
599 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800600 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
601 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700602 return BAD_VALUE;
603 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700604 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800605 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700606
607 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700608 float scaleFactor = ((float) (width * height)) /
609 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800610 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
611 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700612 if (jpegBufferSize > maxJpegBufferSize) {
613 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700614 }
615
616 return jpegBufferSize;
617}
618
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700619ssize_t Camera3Device::getPointCloudBufferSize() const {
620 const int FLOATS_PER_POINT=4;
621 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
622 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800623 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
624 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700625 return BAD_VALUE;
626 }
627 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
628 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
629 return maxBytesForPointCloud;
630}
631
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800632ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800633 const int PER_CONFIGURATION_SIZE = 3;
634 const int WIDTH_OFFSET = 0;
635 const int HEIGHT_OFFSET = 1;
636 const int SIZE_OFFSET = 2;
637 camera_metadata_ro_entry rawOpaqueSizes =
638 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800639 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800640 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800641 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
642 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800643 return BAD_VALUE;
644 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700645
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800646 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
647 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
648 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
649 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
650 }
651 }
652
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800653 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
654 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800655 return BAD_VALUE;
656}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700657
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800658status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
659 ATRACE_CALL();
660 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700661
662 // Try to lock, but continue in case of failure (to avoid blocking in
663 // deadlocks)
664 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
665 bool gotLock = tryLockSpinRightRound(mLock);
666
667 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800668 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
669 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700670 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800671 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
672 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700673
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800674 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700675
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800676 String16 templatesOption("-t");
677 int n = args.size();
678 for (int i = 0; i < n; i++) {
679 if (args[i] == templatesOption) {
680 dumpTemplates = true;
681 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000682 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700683 if (i + 1 < n) {
684 String8 monitorTags = String8(args[i + 1]);
685 if (monitorTags == "off") {
686 mTagMonitor.disableMonitoring();
687 } else {
688 mTagMonitor.parseTagsToMonitor(monitorTags);
689 }
690 } else {
691 mTagMonitor.disableMonitoring();
692 }
693 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800694 }
695
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800696 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800697
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800698 const char *status =
699 mStatus == STATUS_ERROR ? "ERROR" :
700 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700701 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
702 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800703 mStatus == STATUS_ACTIVE ? "ACTIVE" :
704 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700705
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800706 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700707 if (mStatus == STATUS_ERROR) {
708 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
709 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800710 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800711 const char *mode =
712 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
713 mOperatingMode == static_cast<int>(
714 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
715 "CUSTOM";
716 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800717
718 if (mInputStream != NULL) {
719 write(fd, lines.string(), lines.size());
720 mInputStream->dump(fd, args);
721 } else {
722 lines.appendFormat(" No input stream.\n");
723 write(fd, lines.string(), lines.size());
724 }
725 for (size_t i = 0; i < mOutputStreams.size(); i++) {
726 mOutputStreams[i]->dump(fd,args);
727 }
728
Zhijun He431503c2016-03-07 17:30:16 -0800729 if (mBufferManager != NULL) {
730 lines = String8(" Camera3 Buffer Manager:\n");
731 write(fd, lines.string(), lines.size());
732 mBufferManager->dump(fd, args);
733 }
Zhijun He125684a2015-12-26 15:07:30 -0800734
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700735 lines = String8(" In-flight requests:\n");
736 if (mInFlightMap.size() == 0) {
737 lines.append(" None\n");
738 } else {
739 for (size_t i = 0; i < mInFlightMap.size(); i++) {
740 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700741 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700742 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800743 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700744 r.numBuffersLeft);
745 }
746 }
747 write(fd, lines.string(), lines.size());
748
Shuzhen Wang686f6442017-06-20 16:16:04 -0700749 if (mRequestThread != NULL) {
750 mRequestThread->dumpCaptureRequestLatency(fd,
751 " ProcessCaptureRequest latency histogram:");
752 }
753
Igor Murashkin1e479c02013-09-06 16:55:14 -0700754 {
755 lines = String8(" Last request sent:\n");
756 write(fd, lines.string(), lines.size());
757
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700758 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700759 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
760 }
761
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800762 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800763 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800764 "TEMPLATE_PREVIEW",
765 "TEMPLATE_STILL_CAPTURE",
766 "TEMPLATE_VIDEO_RECORD",
767 "TEMPLATE_VIDEO_SNAPSHOT",
768 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800769 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800770 };
771
772 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800773 camera_metadata_t *templateRequest = nullptr;
774 mInterface->constructDefaultRequestSettings(
775 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800776 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800777 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800778 lines.append(" Not supported\n");
779 write(fd, lines.string(), lines.size());
780 } else {
781 write(fd, lines.string(), lines.size());
782 dump_indented_camera_metadata(templateRequest,
783 fd, /*verbosity*/2, /*indentation*/8);
784 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800785 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800786 }
787 }
788
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700789 mTagMonitor.dumpMonitoredMetadata(fd);
790
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800791 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800792 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800793 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800794 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800795 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800796
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700797 if (gotLock) mLock.unlock();
798 if (gotInterfaceLock) mInterfaceLock.unlock();
799
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800800 return OK;
801}
802
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700803const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800804 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800805 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
806 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700807 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800808 mStatus == STATUS_ERROR ?
809 "when in error state" : "before init");
810 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700811 if (physicalId.isEmpty()) {
812 return mDeviceInfo;
813 } else {
814 std::string id(physicalId.c_str());
815 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
816 return mPhysicalDeviceInfoMap.at(id);
817 } else {
818 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
819 return mDeviceInfo;
820 }
821 }
822}
823
824const CameraMetadata& Camera3Device::info() const {
825 String8 emptyId;
826 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800827}
828
Jianing Wei90e59c92014-03-12 18:29:36 -0700829status_t Camera3Device::checkStatusOkToCaptureLocked() {
830 switch (mStatus) {
831 case STATUS_ERROR:
832 CLOGE("Device has encountered a serious error");
833 return INVALID_OPERATION;
834 case STATUS_UNINITIALIZED:
835 CLOGE("Device not initialized");
836 return INVALID_OPERATION;
837 case STATUS_UNCONFIGURED:
838 case STATUS_CONFIGURED:
839 case STATUS_ACTIVE:
840 // OK
841 break;
842 default:
843 SET_ERR_L("Unexpected status: %d", mStatus);
844 return INVALID_OPERATION;
845 }
846 return OK;
847}
848
849status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000850 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700851 const std::list<const SurfaceMap> &surfaceMaps,
852 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700853 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700854 if (requestList == NULL) {
855 CLOGE("requestList cannot be NULL.");
856 return BAD_VALUE;
857 }
858
Jianing Weicb0652e2014-03-12 18:29:36 -0700859 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000860 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700861 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
862 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
863 ++metadataIt, ++surfaceMapIt) {
864 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700865 if (newRequest == 0) {
866 CLOGE("Can't create capture request");
867 return BAD_VALUE;
868 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700869
Shuzhen Wang9d066012016-09-30 11:30:20 -0700870 newRequest->mRepeating = repeating;
871
Jianing Weicb0652e2014-03-12 18:29:36 -0700872 // Setup burst Id and request Id
873 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000874 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
875 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700876 CLOGE("RequestID entry exists; but must not be empty in metadata");
877 return BAD_VALUE;
878 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000879 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
880 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700881 } else {
882 CLOGE("RequestID does not exist in metadata");
883 return BAD_VALUE;
884 }
885
Jianing Wei90e59c92014-03-12 18:29:36 -0700886 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700887
888 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700889 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700890 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
891 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
892 return BAD_VALUE;
893 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700894
895 // Setup batch size if this is a high speed video recording request.
896 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
897 auto firstRequest = requestList->begin();
898 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
899 if (outputStream->isVideoStream()) {
900 (*firstRequest)->mBatchSize = requestList->size();
901 break;
902 }
903 }
904 }
905
Jianing Wei90e59c92014-03-12 18:29:36 -0700906 return OK;
907}
908
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800909status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800910 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800911
Emilian Peevaebbe412018-01-15 13:53:24 +0000912 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700913 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000914 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700915
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800916 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700917}
918
Emilian Peevaebbe412018-01-15 13:53:24 +0000919void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700920 std::list<const SurfaceMap>& surfaceMaps,
921 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000922 PhysicalCameraSettingsList requestList;
923 requestList.push_back({std::string(getId().string()), request});
924 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700925
926 SurfaceMap surfaceMap;
927 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
928 // With no surface list passed in, stream and surface will have 1-to-1
929 // mapping. So the surface index is 0 for each stream in the surfaceMap.
930 for (size_t i = 0; i < streams.count; i++) {
931 surfaceMap[streams.data.i32[i]].push_back(0);
932 }
933 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800934}
935
Jianing Wei90e59c92014-03-12 18:29:36 -0700936status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000937 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700938 const std::list<const SurfaceMap> &surfaceMaps,
939 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700940 /*out*/
941 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700942 ATRACE_CALL();
943 Mutex::Autolock il(mInterfaceLock);
944 Mutex::Autolock l(mLock);
945
946 status_t res = checkStatusOkToCaptureLocked();
947 if (res != OK) {
948 // error logged by previous call
949 return res;
950 }
951
952 RequestList requestList;
953
Shuzhen Wang0129d522016-10-30 22:43:41 -0700954 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
955 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700956 if (res != OK) {
957 // error logged by previous call
958 return res;
959 }
960
961 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700962 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700963 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700964 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700965 }
966
967 if (res == OK) {
968 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
969 if (res != OK) {
970 SET_ERR_L("Can't transition to active in %f seconds!",
971 kActiveTimeout/1e9);
972 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800973 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700974 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700975 } else {
976 CLOGE("Cannot queue request. Impossible.");
977 return BAD_VALUE;
978 }
979
980 return res;
981}
982
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700983hardware::Return<void> Camera3Device::requestStreamBuffers(
984 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
985 requestStreamBuffers_cb _hidl_cb) {
986 using hardware::camera::device::V3_5::BufferRequestStatus;
987 using hardware::camera::device::V3_5::StreamBufferRet;
988 using hardware::camera::device::V3_5::StreamBufferRequestError;
989
990 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
991
992 hardware::hidl_vec<StreamBufferRet> bufRets;
993 if (!mUseHalBufManager) {
994 ALOGE("%s: Camera %s does not support HAL buffer management",
995 __FUNCTION__, mId.string());
996 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
997 return hardware::Void();
998 }
999
1000 SortedVector<int32_t> streamIds;
1001 ssize_t sz = streamIds.setCapacity(bufReqs.size());
1002 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
1003 ALOGE("%s: failed to allocate memory for %zu buffer requests",
1004 __FUNCTION__, bufReqs.size());
1005 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1006 return hardware::Void();
1007 }
1008
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001009 if (bufReqs.size() > mOutputStreams.size()) {
1010 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
1011 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
1012 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1013 return hardware::Void();
1014 }
1015
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001016 // Check for repeated streamId
1017 for (const auto& bufReq : bufReqs) {
1018 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
1019 ALOGE("%s: Stream %d appear multiple times in buffer requests",
1020 __FUNCTION__, bufReq.streamId);
1021 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1022 return hardware::Void();
1023 }
1024 streamIds.add(bufReq.streamId);
1025 }
1026
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001027 if (!mRequestBufferSM.startRequestBuffer()) {
1028 ALOGE("%s: request buffer disallowed while camera service is configuring",
1029 __FUNCTION__);
1030 _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001031 return hardware::Void();
1032 }
1033
1034 bufRets.resize(bufReqs.size());
1035
1036 bool allReqsSucceeds = true;
1037 bool oneReqSucceeds = false;
1038 for (size_t i = 0; i < bufReqs.size(); i++) {
1039 const auto& bufReq = bufReqs[i];
1040 auto& bufRet = bufRets[i];
1041 int32_t streamId = bufReq.streamId;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001042 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
1043 if (outputStream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001044 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
1045 hardware::hidl_vec<StreamBufferRet> emptyBufRets;
1046 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001047 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001048 return hardware::Void();
1049 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001050
Yin-Chia Yehee2d1042020-07-13 15:51:17 -07001051 bufRet.streamId = streamId;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001052 if (outputStream->isAbandoned()) {
1053 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1054 allReqsSucceeds = false;
1055 continue;
1056 }
1057
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001058 size_t handOutBufferCount = outputStream->getOutstandingBuffersCount();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001059 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001060 size_t totalHandout = handOutBufferCount + numBuffersRequested;
1061 uint32_t maxBuffers = outputStream->asHalStream()->max_buffers;
1062 if (totalHandout > maxBuffers) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001063 // Not able to allocate enough buffer. Exit early for this stream
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001064 ALOGE("%s: request too much buffers for stream %d: at HAL: %zu + requesting: %d"
1065 " > max: %d", __FUNCTION__, streamId, handOutBufferCount,
1066 numBuffersRequested, maxBuffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001067 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1068 allReqsSucceeds = false;
1069 continue;
1070 }
1071
1072 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1073 bool currentReqSucceeds = true;
1074 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1075 size_t numAllocatedBuffers = 0;
1076 size_t numPushedInflightBuffers = 0;
1077 for (size_t b = 0; b < numBuffersRequested; b++) {
1078 camera3_stream_buffer_t& sb = streamBuffers[b];
1079 // Since this method can run concurrently with request thread
1080 // We need to update the wait duration everytime we call getbuffer
1081 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1082 status_t res = outputStream->getBuffer(&sb, waitDuration);
1083 if (res != OK) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001084 if (res == NO_INIT || res == DEAD_OBJECT) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001085 ALOGV("%s: Can't get output buffer for stream %d: %s (%d)",
1086 __FUNCTION__, streamId, strerror(-res), res);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001087 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001088 } else {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001089 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1090 __FUNCTION__, streamId, strerror(-res), res);
1091 if (res == TIMED_OUT || res == NO_MEMORY) {
1092 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1093 } else {
1094 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1095 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001096 }
1097 currentReqSucceeds = false;
1098 break;
1099 }
1100 numAllocatedBuffers++;
1101
1102 buffer_handle_t *buffer = sb.buffer;
1103 auto pair = mInterface->getBufferId(*buffer, streamId);
1104 bool isNewBuffer = pair.first;
1105 uint64_t bufferId = pair.second;
1106 StreamBuffer& hBuf = tmpRetBuffers[b];
1107
1108 hBuf.streamId = streamId;
1109 hBuf.bufferId = bufferId;
1110 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1111 hBuf.status = BufferStatus::OK;
1112 hBuf.releaseFence = nullptr;
1113
1114 native_handle_t *acquireFence = nullptr;
1115 if (sb.acquire_fence != -1) {
1116 acquireFence = native_handle_create(1,0);
1117 acquireFence->data[0] = sb.acquire_fence;
1118 }
1119 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1120 hBuf.releaseFence = nullptr;
1121
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08001122 res = mInterface->pushInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001123 if (res != OK) {
1124 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1125 __FUNCTION__, streamId, strerror(-res), res);
1126 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1127 currentReqSucceeds = false;
1128 break;
1129 }
1130 numPushedInflightBuffers++;
1131 }
1132 if (currentReqSucceeds) {
1133 bufRet.val.buffers(std::move(tmpRetBuffers));
1134 oneReqSucceeds = true;
1135 } else {
1136 allReqsSucceeds = false;
1137 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1138 StreamBuffer& hBuf = tmpRetBuffers[b];
1139 buffer_handle_t* buffer;
1140 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1141 if (res != OK) {
1142 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1143 __FUNCTION__, streamId, strerror(-res), res);
1144 }
1145 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001146 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1147 camera3_stream_buffer_t& sb = streamBuffers[b];
1148 sb.acquire_fence = -1;
1149 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1150 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001151 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1152 }
1153 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001154
1155 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1156 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1157 BufferRequestStatus::FAILED_UNKNOWN,
1158 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001159 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001160 return hardware::Void();
1161}
1162
1163hardware::Return<void> Camera3Device::returnStreamBuffers(
1164 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1165 if (!mUseHalBufManager) {
1166 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1167 __FUNCTION__, mId.string());
1168 return hardware::Void();
1169 }
1170
1171 for (const auto& buf : buffers) {
1172 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1173 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1174 continue;
1175 }
1176
1177 buffer_handle_t* buffer;
1178 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1179
1180 if (res != OK) {
1181 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1182 __FUNCTION__, buf.bufferId, buf.streamId);
1183 continue;
1184 }
1185
1186 camera3_stream_buffer_t streamBuffer;
1187 streamBuffer.buffer = buffer;
1188 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1189 streamBuffer.acquire_fence = -1;
1190 streamBuffer.release_fence = -1;
1191
1192 if (buf.releaseFence == nullptr) {
1193 streamBuffer.release_fence = -1;
1194 } else if (buf.releaseFence->numFds == 1) {
1195 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1196 } else {
1197 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1198 __FUNCTION__, buf.releaseFence->numFds);
1199 continue;
1200 }
1201
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001202 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1203 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001204 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1205 continue;
1206 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001207 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001208 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1209 }
1210 return hardware::Void();
1211}
1212
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001213hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001214 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001215 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001216 // Ideally we should grab mLock, but that can lead to deadlock, and
1217 // it's not super important to get up to date value of mStatus for this
1218 // warning print, hence skipping the lock here
1219 if (mStatus == STATUS_ERROR) {
1220 // Per API contract, HAL should act as closed after device error
1221 // But mStatus can be set to error by framework as well, so just log
1222 // a warning here.
1223 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001224 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001225
1226 if (mProcessCaptureResultLock.tryLock() != OK) {
1227 // This should never happen; it indicates a wrong client implementation
1228 // that doesn't follow the contract. But, we can be tolerant here.
1229 ALOGE("%s: callback overlapped! waiting 1s...",
1230 __FUNCTION__);
1231 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1232 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1233 __FUNCTION__);
1234 // really don't know what to do, so bail out.
1235 return hardware::Void();
1236 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001237 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001238 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001239 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001240 }
1241 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001242 return hardware::Void();
1243}
1244
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001245// Only one processCaptureResult should be called at a time, so
1246// the locks won't block. The locks are present here simply to enforce this.
1247hardware::Return<void> Camera3Device::processCaptureResult(
1248 const hardware::hidl_vec<
1249 hardware::camera::device::V3_2::CaptureResult>& results) {
1250 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1251
1252 // Ideally we should grab mLock, but that can lead to deadlock, and
1253 // it's not super important to get up to date value of mStatus for this
1254 // warning print, hence skipping the lock here
1255 if (mStatus == STATUS_ERROR) {
1256 // Per API contract, HAL should act as closed after device error
1257 // But mStatus can be set to error by framework as well, so just log
1258 // a warning here.
1259 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1260 }
1261
1262 if (mProcessCaptureResultLock.tryLock() != OK) {
1263 // This should never happen; it indicates a wrong client implementation
1264 // that doesn't follow the contract. But, we can be tolerant here.
1265 ALOGE("%s: callback overlapped! waiting 1s...",
1266 __FUNCTION__);
1267 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1268 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1269 __FUNCTION__);
1270 // really don't know what to do, so bail out.
1271 return hardware::Void();
1272 }
1273 }
1274 for (const auto& result : results) {
1275 processOneCaptureResultLocked(result, noPhysMetadata);
1276 }
1277 mProcessCaptureResultLock.unlock();
1278 return hardware::Void();
1279}
1280
1281status_t Camera3Device::readOneCameraMetadataLocked(
1282 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1283 const hardware::camera::device::V3_2::CameraMetadata& result) {
1284 if (fmqResultSize > 0) {
1285 resultMetadata.resize(fmqResultSize);
1286 if (mResultMetadataQueue == nullptr) {
1287 return NO_MEMORY; // logged in initialize()
1288 }
1289 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1290 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1291 __FUNCTION__, fmqResultSize);
1292 return INVALID_OPERATION;
1293 }
1294 } else {
1295 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1296 result.size());
1297 }
1298
1299 if (resultMetadata.size() != 0) {
1300 status_t res;
1301 const camera_metadata_t* metadata =
1302 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1303 size_t expected_metadata_size = resultMetadata.size();
1304 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1305 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1306 __FUNCTION__, strerror(-res), res);
1307 return INVALID_OPERATION;
1308 }
1309 }
1310
1311 return OK;
1312}
1313
Yifan Honga640c5a2017-04-12 16:30:31 -07001314void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001315 const hardware::camera::device::V3_2::CaptureResult& result,
1316 const hardware::hidl_vec<
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001317 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadata) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001318 camera3_capture_result r;
1319 status_t res;
1320 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001321
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001322 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001323 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001324 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1325 if (res != OK) {
1326 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1327 __FUNCTION__, result.frameNumber);
1328 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001329 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001330 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001331
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001332 // Read and validate physical camera metadata
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001333 size_t physResultCount = physicalCameraMetadata.size();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001334 std::vector<const char*> physCamIds(physResultCount);
1335 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1336 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1337 physResultMetadata.resize(physResultCount);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001338 for (size_t i = 0; i < physicalCameraMetadata.size(); i++) {
1339 res = readOneCameraMetadataLocked(physicalCameraMetadata[i].fmqMetadataSize,
1340 physResultMetadata[i], physicalCameraMetadata[i].metadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001341 if (res != OK) {
1342 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1343 __FUNCTION__, result.frameNumber,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001344 physicalCameraMetadata[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001345 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001346 }
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001347 physCamIds[i] = physicalCameraMetadata[i].physicalCameraId.c_str();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001348 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1349 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001350 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001351 r.num_physcam_metadata = physResultCount;
1352 r.physcam_ids = physCamIds.data();
1353 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001354
1355 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1356 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1357 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1358 auto& bDst = outputBuffers[i];
1359 const StreamBuffer &bSrc = result.outputBuffers[i];
1360
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001361 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1362 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001363 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1364 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001365 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001366 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001367 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001368
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001369 bool noBufferReturned = false;
1370 buffer_handle_t *buffer = nullptr;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001371 if (mUseHalBufManager) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001372 // This is suspicious most of the time but can be correct during flush where HAL
1373 // has to return capture result before a buffer is requested
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001374 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001375 if (bSrc.status == BufferStatus::OK) {
1376 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1377 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1378 // Still proceeds so other buffers can be returned
1379 }
1380 noBufferReturned = true;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001381 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001382 if (noBufferReturned) {
1383 res = OK;
1384 } else {
1385 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1386 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001387 } else {
1388 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1389 }
1390
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001391 if (res != OK) {
1392 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1393 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001394 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001395 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001396
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001397 bDst.buffer = buffer;
1398 bDst.status = mapHidlBufferStatus(bSrc.status);
1399 bDst.acquire_fence = -1;
1400 if (bSrc.releaseFence == nullptr) {
1401 bDst.release_fence = -1;
1402 } else if (bSrc.releaseFence->numFds == 1) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001403 if (noBufferReturned) {
1404 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
1405 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001406 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1407 } else {
1408 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1409 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001410 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001411 }
1412 }
1413 r.num_output_buffers = outputBuffers.size();
1414 r.output_buffers = outputBuffers.data();
1415
1416 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001417 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001418 r.input_buffer = nullptr;
1419 } else {
1420 if (mInputStream->getId() != result.inputBuffer.streamId) {
1421 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1422 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001423 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001424 }
1425 inputBuffer.stream = mInputStream->asHalStream();
1426 buffer_handle_t *buffer;
1427 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1428 &buffer);
1429 if (res != OK) {
1430 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1431 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001432 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001433 }
1434 inputBuffer.buffer = buffer;
1435 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1436 inputBuffer.acquire_fence = -1;
1437 if (result.inputBuffer.releaseFence == nullptr) {
1438 inputBuffer.release_fence = -1;
1439 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1440 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1441 } else {
1442 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1443 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001444 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001445 }
1446 r.input_buffer = &inputBuffer;
1447 }
1448
1449 r.partial_result = result.partialResult;
1450
1451 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001452}
1453
1454hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001455 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001456 // Ideally we should grab mLock, but that can lead to deadlock, and
1457 // it's not super important to get up to date value of mStatus for this
1458 // warning print, hence skipping the lock here
1459 if (mStatus == STATUS_ERROR) {
1460 // Per API contract, HAL should act as closed after device error
1461 // But mStatus can be set to error by framework as well, so just log
1462 // a warning here.
1463 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001464 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001465
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001466 for (const auto& msg : msgs) {
1467 notify(msg);
1468 }
1469 return hardware::Void();
1470}
1471
1472void Camera3Device::notify(
1473 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1474
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001475 camera3_notify_msg m;
1476 switch (msg.type) {
1477 case MsgType::ERROR:
1478 m.type = CAMERA3_MSG_ERROR;
1479 m.message.error.frame_number = msg.msg.error.frameNumber;
1480 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001481 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1482 if (stream == nullptr) {
1483 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1484 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001485 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001486 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001487 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001488 } else {
1489 m.message.error.error_stream = nullptr;
1490 }
1491 switch (msg.msg.error.errorCode) {
1492 case ErrorCode::ERROR_DEVICE:
1493 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1494 break;
1495 case ErrorCode::ERROR_REQUEST:
1496 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1497 break;
1498 case ErrorCode::ERROR_RESULT:
1499 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1500 break;
1501 case ErrorCode::ERROR_BUFFER:
1502 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1503 break;
1504 }
1505 break;
1506 case MsgType::SHUTTER:
1507 m.type = CAMERA3_MSG_SHUTTER;
1508 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1509 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1510 break;
1511 }
1512 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001513}
1514
Emilian Peevaebbe412018-01-15 13:53:24 +00001515status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001516 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001517 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001518 ATRACE_CALL();
1519
Emilian Peevaebbe412018-01-15 13:53:24 +00001520 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001521}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001522
Jianing Weicb0652e2014-03-12 18:29:36 -07001523status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1524 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001525 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001526
Emilian Peevaebbe412018-01-15 13:53:24 +00001527 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001528 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001529 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001530
Emilian Peevaebbe412018-01-15 13:53:24 +00001531 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001532 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001533}
1534
Emilian Peevaebbe412018-01-15 13:53:24 +00001535status_t Camera3Device::setStreamingRequestList(
1536 const List<const PhysicalCameraSettingsList> &requestsList,
1537 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001538 ATRACE_CALL();
1539
Emilian Peevaebbe412018-01-15 13:53:24 +00001540 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001541}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542
1543sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001544 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 status_t res;
1546
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001547 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001548 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1549 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001550 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1551 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001552 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001554 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001555 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001556 } else if (mStatus == STATUS_UNCONFIGURED) {
1557 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001558 CLOGE("No streams configured");
1559 return NULL;
1560 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001561 }
1562
Shuzhen Wang0129d522016-10-30 22:43:41 -07001563 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001565}
1566
Jianing Weicb0652e2014-03-12 18:29:36 -07001567status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001568 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001569 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001570 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001571
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 switch (mStatus) {
1573 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001574 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 return INVALID_OPERATION;
1576 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001577 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001578 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001579 case STATUS_UNCONFIGURED:
1580 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001581 case STATUS_ACTIVE:
1582 // OK
1583 break;
1584 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001585 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001586 return INVALID_OPERATION;
1587 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001588 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001589
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001590 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001591}
1592
1593status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1594 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001595 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001596
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001597 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001598}
1599
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001600status_t Camera3Device::createInputStream(
1601 uint32_t width, uint32_t height, int format, int *id) {
1602 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001603 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001604 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001605 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001606 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1607 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001608
1609 status_t res;
1610 bool wasActive = false;
1611
1612 switch (mStatus) {
1613 case STATUS_ERROR:
1614 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1615 return INVALID_OPERATION;
1616 case STATUS_UNINITIALIZED:
1617 ALOGE("%s: Device not initialized", __FUNCTION__);
1618 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001619 case STATUS_UNCONFIGURED:
1620 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001621 // OK
1622 break;
1623 case STATUS_ACTIVE:
1624 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001625 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001626 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001627 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001628 return res;
1629 }
1630 wasActive = true;
1631 break;
1632 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001633 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001634 return INVALID_OPERATION;
1635 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001636 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001637
1638 if (mInputStream != 0) {
1639 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1640 return INVALID_OPERATION;
1641 }
1642
1643 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1644 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001645 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001646
1647 mInputStream = newStream;
1648
1649 *id = mNextStreamId++;
1650
1651 // Continue captures if active at start
1652 if (wasActive) {
1653 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001654 // Reuse current operating mode and session parameters for new stream config
1655 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001656 if (res != OK) {
1657 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1658 __FUNCTION__, mNextStreamId, strerror(-res), res);
1659 return res;
1660 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001661 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001662 }
1663
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001664 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001665 return OK;
1666}
1667
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001668status_t Camera3Device::StreamSet::add(
1669 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1670 if (stream == nullptr) {
1671 ALOGE("%s: cannot add null stream", __FUNCTION__);
1672 return BAD_VALUE;
1673 }
1674 std::lock_guard<std::mutex> lock(mLock);
1675 return mData.add(streamId, stream);
1676}
1677
1678ssize_t Camera3Device::StreamSet::remove(int streamId) {
1679 std::lock_guard<std::mutex> lock(mLock);
1680 return mData.removeItem(streamId);
1681}
1682
1683sp<camera3::Camera3OutputStreamInterface>
1684Camera3Device::StreamSet::get(int streamId) {
1685 std::lock_guard<std::mutex> lock(mLock);
1686 ssize_t idx = mData.indexOfKey(streamId);
1687 if (idx == NAME_NOT_FOUND) {
1688 return nullptr;
1689 }
1690 return mData.editValueAt(idx);
1691}
1692
1693sp<camera3::Camera3OutputStreamInterface>
1694Camera3Device::StreamSet::operator[] (size_t index) {
1695 std::lock_guard<std::mutex> lock(mLock);
1696 return mData.editValueAt(index);
1697}
1698
1699size_t Camera3Device::StreamSet::size() const {
1700 std::lock_guard<std::mutex> lock(mLock);
1701 return mData.size();
1702}
1703
1704void Camera3Device::StreamSet::clear() {
1705 std::lock_guard<std::mutex> lock(mLock);
1706 return mData.clear();
1707}
1708
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001709std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1710 std::lock_guard<std::mutex> lock(mLock);
1711 std::vector<int> streamIds(mData.size());
1712 for (size_t i = 0; i < mData.size(); i++) {
1713 streamIds[i] = mData.keyAt(i);
1714 }
1715 return streamIds;
1716}
1717
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001718status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001719 uint32_t width, uint32_t height, int format,
1720 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001721 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001722 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001723 ATRACE_CALL();
1724
1725 if (consumer == nullptr) {
1726 ALOGE("%s: consumer must not be null", __FUNCTION__);
1727 return BAD_VALUE;
1728 }
1729
1730 std::vector<sp<Surface>> consumers;
1731 consumers.push_back(consumer);
1732
1733 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001734 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1735 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001736}
1737
1738status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1739 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1740 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001741 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001742 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001743 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001744
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001745 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001746 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001747 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001748 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001749 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1750 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1751 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001752
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001753 status_t res;
1754 bool wasActive = false;
1755
1756 switch (mStatus) {
1757 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001758 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001759 return INVALID_OPERATION;
1760 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001761 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001762 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001763 case STATUS_UNCONFIGURED:
1764 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001765 // OK
1766 break;
1767 case STATUS_ACTIVE:
1768 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001769 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001770 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001771 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001772 return res;
1773 }
1774 wasActive = true;
1775 break;
1776 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001777 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001778 return INVALID_OPERATION;
1779 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001780 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001781
1782 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001783
Shuzhen Wang0129d522016-10-30 22:43:41 -07001784 if (consumers.size() == 0 && !hasDeferredConsumer) {
1785 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1786 return BAD_VALUE;
1787 }
Zhijun He5d677d12016-05-29 16:52:39 -07001788
Shuzhen Wang0129d522016-10-30 22:43:41 -07001789 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001790 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1791 return BAD_VALUE;
1792 }
1793
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001794 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001795 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001796 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001797 blobBufferSize = getPointCloudBufferSize();
1798 if (blobBufferSize <= 0) {
1799 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1800 return BAD_VALUE;
1801 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001802 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1803 blobBufferSize = width * height;
1804 } else {
1805 blobBufferSize = getJpegBufferSize(width, height);
1806 if (blobBufferSize <= 0) {
1807 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1808 return BAD_VALUE;
1809 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001810 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001811 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001812 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001813 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001814 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1815 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1816 if (rawOpaqueBufferSize <= 0) {
1817 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1818 return BAD_VALUE;
1819 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001820 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001821 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001822 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001823 } else if (isShared) {
1824 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1825 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001826 mTimestampOffset, physicalCameraId, streamSetId,
1827 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001828 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001829 newStream = new Camera3OutputStream(mNextStreamId,
1830 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001831 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001832 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001833 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001834 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001835 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001836 }
Emilian Peev40ead602017-09-26 15:46:36 +01001837
1838 size_t consumerCount = consumers.size();
1839 for (size_t i = 0; i < consumerCount; i++) {
1840 int id = newStream->getSurfaceId(consumers[i]);
1841 if (id < 0) {
1842 SET_ERR_L("Invalid surface id");
1843 return BAD_VALUE;
1844 }
1845 if (surfaceIds != nullptr) {
1846 surfaceIds->push_back(id);
1847 }
1848 }
1849
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001850 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001851
Emilian Peev08dd2452017-04-06 16:55:14 +01001852 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001853
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001854 res = mOutputStreams.add(mNextStreamId, newStream);
1855 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001856 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001857 return res;
1858 }
1859
1860 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001861 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001862
1863 // Continue captures if active at start
1864 if (wasActive) {
1865 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001866 // Reuse current operating mode and session parameters for new stream config
1867 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001868 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001869 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1870 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001871 return res;
1872 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001873 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001874 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001875 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001876 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001877}
1878
Emilian Peev710c1422017-08-30 11:19:38 +01001879status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001880 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001881 if (nullptr == streamInfo) {
1882 return BAD_VALUE;
1883 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001884 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001885 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001886
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001887 switch (mStatus) {
1888 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001889 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001890 return INVALID_OPERATION;
1891 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001892 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001893 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001894 case STATUS_UNCONFIGURED:
1895 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001896 case STATUS_ACTIVE:
1897 // OK
1898 break;
1899 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001900 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001901 return INVALID_OPERATION;
1902 }
1903
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001904 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1905 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001906 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001907 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001908 }
1909
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001910 streamInfo->width = stream->getWidth();
1911 streamInfo->height = stream->getHeight();
1912 streamInfo->format = stream->getFormat();
1913 streamInfo->dataSpace = stream->getDataSpace();
1914 streamInfo->formatOverridden = stream->isFormatOverridden();
1915 streamInfo->originalFormat = stream->getOriginalFormat();
1916 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1917 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001918 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001919}
1920
1921status_t Camera3Device::setStreamTransform(int id,
1922 int transform) {
1923 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001924 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001925 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001926
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001927 switch (mStatus) {
1928 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001929 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001930 return INVALID_OPERATION;
1931 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001932 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001933 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001934 case STATUS_UNCONFIGURED:
1935 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001936 case STATUS_ACTIVE:
1937 // OK
1938 break;
1939 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001940 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001941 return INVALID_OPERATION;
1942 }
1943
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001944 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1945 if (stream == nullptr) {
1946 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001947 return BAD_VALUE;
1948 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001949 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001950}
1951
1952status_t Camera3Device::deleteStream(int id) {
1953 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001954 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001955 Mutex::Autolock l(mLock);
1956 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001957
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001958 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001959
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001960 // CameraDevice semantics require device to already be idle before
1961 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001962 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001963 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001964 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001965 }
1966
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001967 if (mStatus == STATUS_ERROR) {
1968 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1969 __FUNCTION__, mId.string());
1970 return -EBUSY;
1971 }
1972
Igor Murashkin2fba5842013-04-22 14:03:54 -07001973 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001974 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001975 if (mInputStream != NULL && id == mInputStream->getId()) {
1976 deletedStream = mInputStream;
1977 mInputStream.clear();
1978 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001979 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001980 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001981 return BAD_VALUE;
1982 }
Zhijun He5f446352014-01-22 09:49:33 -08001983 }
1984
1985 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001986 if (stream != nullptr) {
1987 deletedStream = stream;
1988 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001989 }
1990
1991 // Free up the stream endpoint so that it can be used by some other stream
1992 res = deletedStream->disconnect();
1993 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001994 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001995 // fall through since we want to still list the stream as deleted.
1996 }
1997 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001998 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001999
2000 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002001}
2002
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002003status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07002004 ATRACE_CALL();
2005 ALOGV("%s: E", __FUNCTION__);
2006
2007 Mutex::Autolock il(mInterfaceLock);
2008 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07002009
Emilian Peev811d2952018-05-25 11:08:40 +01002010 // In case the client doesn't include any session parameter, try a
2011 // speculative configuration using the values from the last cached
2012 // default request.
2013 if (sessionParams.isEmpty() &&
2014 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
2015 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
2016 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
2017 mLastTemplateId);
2018 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
2019 operatingMode);
2020 }
2021
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002022 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
2023}
2024
2025status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
2026 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002027 //Filter out any incoming session parameters
2028 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002029 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
2030 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002031 CameraMetadata filteredParams(availableSessionKeys.count);
2032 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2033 filteredParams.getAndLock());
2034 set_camera_metadata_vendor_id(meta, mVendorTagId);
2035 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002036 if (availableSessionKeys.count > 0) {
2037 for (size_t i = 0; i < availableSessionKeys.count; i++) {
2038 camera_metadata_ro_entry entry = params.find(
2039 availableSessionKeys.data.i32[i]);
2040 if (entry.count > 0) {
2041 filteredParams.update(entry);
2042 }
2043 }
2044 }
2045
2046 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07002047}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002048
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002049status_t Camera3Device::getInputBufferProducer(
2050 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002051 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002052 Mutex::Autolock il(mInterfaceLock);
2053 Mutex::Autolock l(mLock);
2054
2055 if (producer == NULL) {
2056 return BAD_VALUE;
2057 } else if (mInputStream == NULL) {
2058 return INVALID_OPERATION;
2059 }
2060
2061 return mInputStream->getInputBufferProducer(producer);
2062}
2063
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002064status_t Camera3Device::createDefaultRequest(int templateId,
2065 CameraMetadata *request) {
2066 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002067 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002068
2069 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2070 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002071 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002072 return BAD_VALUE;
2073 }
2074
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002075 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002076
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002077 {
2078 Mutex::Autolock l(mLock);
2079 switch (mStatus) {
2080 case STATUS_ERROR:
2081 CLOGE("Device has encountered a serious error");
2082 return INVALID_OPERATION;
2083 case STATUS_UNINITIALIZED:
2084 CLOGE("Device is not initialized!");
2085 return INVALID_OPERATION;
2086 case STATUS_UNCONFIGURED:
2087 case STATUS_CONFIGURED:
2088 case STATUS_ACTIVE:
2089 // OK
2090 break;
2091 default:
2092 SET_ERR_L("Unexpected status: %d", mStatus);
2093 return INVALID_OPERATION;
2094 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002095
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002096 if (!mRequestTemplateCache[templateId].isEmpty()) {
2097 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002098 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002099 return OK;
2100 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002101 }
2102
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002103 camera_metadata_t *rawRequest;
2104 status_t res = mInterface->constructDefaultRequestSettings(
2105 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002106
2107 {
2108 Mutex::Autolock l(mLock);
2109 if (res == BAD_VALUE) {
2110 ALOGI("%s: template %d is not supported on this camera device",
2111 __FUNCTION__, templateId);
2112 return res;
2113 } else if (res != OK) {
2114 CLOGE("Unable to construct request template %d: %s (%d)",
2115 templateId, strerror(-res), res);
2116 return res;
2117 }
2118
2119 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2120 mRequestTemplateCache[templateId].acquire(rawRequest);
2121
2122 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002123 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002124 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002125 return OK;
2126}
2127
2128status_t Camera3Device::waitUntilDrained() {
2129 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002130 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002131 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002132 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002133
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002134 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002135}
2136
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002137status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002138 switch (mStatus) {
2139 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002140 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002141 ALOGV("%s: Already idle", __FUNCTION__);
2142 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002143 case STATUS_CONFIGURED:
2144 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002145 case STATUS_ERROR:
2146 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002147 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002148 break;
2149 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002150 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002151 return INVALID_OPERATION;
2152 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002153 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2154 maxExpectedDuration);
2155 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002156 if (res != OK) {
2157 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2158 res);
2159 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002160 return res;
2161}
2162
Ruben Brunk183f0562015-08-12 12:55:02 -07002163
2164void Camera3Device::internalUpdateStatusLocked(Status status) {
2165 mStatus = status;
2166 mRecentStatusUpdates.add(mStatus);
2167 mStatusChanged.broadcast();
2168}
2169
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002170void Camera3Device::pauseStateNotify(bool enable) {
Jayant Chowdharydfc46592020-01-30 13:09:59 -08002171 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002172 Mutex::Autolock l(mLock);
2173
2174 mPauseStateNotify = enable;
2175}
2176
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002177// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002178status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08002179 if (mRequestThread.get() != nullptr) {
2180 mRequestThread->setPaused(true);
2181 } else {
2182 return NO_INIT;
2183 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002184
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002185 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2186 maxExpectedDuration);
2187 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002188 if (res != OK) {
2189 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002190 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002191 }
2192
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002193 return res;
2194}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002195
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002196// Resume after internalPauseAndWaitLocked
2197status_t Camera3Device::internalResumeLocked() {
2198 status_t res;
2199
2200 mRequestThread->setPaused(false);
2201
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002202 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2203 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002204 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2205 if (res != OK) {
2206 SET_ERR_L("Can't transition to active in %f seconds!",
2207 kActiveTimeout/1e9);
2208 }
2209 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002210 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002211}
2212
Ruben Brunk183f0562015-08-12 12:55:02 -07002213status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002214 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002215
2216 size_t startIndex = 0;
2217 if (mStatusWaiters == 0) {
2218 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2219 // this status list
2220 mRecentStatusUpdates.clear();
2221 } else {
2222 // If other threads are waiting on updates to this status list, set the position of the
2223 // first element that this list will check rather than clearing the list.
2224 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002225 }
2226
Ruben Brunk183f0562015-08-12 12:55:02 -07002227 mStatusWaiters++;
2228
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002229 if (!active && mUseHalBufManager) {
2230 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08002231 if (mStatus == STATUS_ACTIVE) {
2232 mRequestThread->signalPipelineDrain(streamIds);
2233 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002234 mRequestBufferSM.onWaitUntilIdle();
2235 }
2236
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002237 bool stateSeen = false;
2238 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002239 if (active == (mStatus == STATUS_ACTIVE)) {
2240 // Desired state is current
2241 break;
2242 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002243
2244 res = mStatusChanged.waitRelative(mLock, timeout);
2245 if (res != OK) break;
2246
Ruben Brunk183f0562015-08-12 12:55:02 -07002247 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2248 // transitions.
2249 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2250 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2251 __FUNCTION__);
2252
2253 // Encountered desired state since we began waiting
2254 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002255 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2256 stateSeen = true;
2257 break;
2258 }
2259 }
2260 } while (!stateSeen);
2261
Ruben Brunk183f0562015-08-12 12:55:02 -07002262 mStatusWaiters--;
2263
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002264 return res;
2265}
2266
2267
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002268status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002269 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002270 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002271
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002272 if (listener != NULL && mListener != NULL) {
2273 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2274 }
2275 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002276 mRequestThread->setNotificationListener(listener);
2277 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002278
2279 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002280}
2281
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002282bool Camera3Device::willNotify3A() {
2283 return false;
2284}
2285
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002286status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002287 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002288 status_t res;
2289 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002290
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002291 while (mResultQueue.empty()) {
2292 res = mResultSignal.waitRelative(mOutputLock, timeout);
2293 if (res == TIMED_OUT) {
2294 return res;
2295 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002296 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2297 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002298 return res;
2299 }
2300 }
2301 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002302}
2303
Jianing Weicb0652e2014-03-12 18:29:36 -07002304status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002305 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002306 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002307
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002308 if (mResultQueue.empty()) {
2309 return NOT_ENOUGH_DATA;
2310 }
2311
Jianing Weicb0652e2014-03-12 18:29:36 -07002312 if (frame == NULL) {
2313 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2314 return BAD_VALUE;
2315 }
2316
2317 CaptureResult &result = *(mResultQueue.begin());
2318 frame->mResultExtras = result.mResultExtras;
2319 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002320 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002321 mResultQueue.erase(mResultQueue.begin());
2322
2323 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002324}
2325
2326status_t Camera3Device::triggerAutofocus(uint32_t id) {
2327 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002328 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002329
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002330 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2331 // Mix-in this trigger into the next request and only the next request.
2332 RequestTrigger trigger[] = {
2333 {
2334 ANDROID_CONTROL_AF_TRIGGER,
2335 ANDROID_CONTROL_AF_TRIGGER_START
2336 },
2337 {
2338 ANDROID_CONTROL_AF_TRIGGER_ID,
2339 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002340 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002341 };
2342
2343 return mRequestThread->queueTrigger(trigger,
2344 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002345}
2346
2347status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2348 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002349 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002350
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002351 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2352 // Mix-in this trigger into the next request and only the next request.
2353 RequestTrigger trigger[] = {
2354 {
2355 ANDROID_CONTROL_AF_TRIGGER,
2356 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2357 },
2358 {
2359 ANDROID_CONTROL_AF_TRIGGER_ID,
2360 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002361 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002362 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002363
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002364 return mRequestThread->queueTrigger(trigger,
2365 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002366}
2367
2368status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2369 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002370 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002371
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002372 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2373 // Mix-in this trigger into the next request and only the next request.
2374 RequestTrigger trigger[] = {
2375 {
2376 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2377 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2378 },
2379 {
2380 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2381 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002382 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002383 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002384
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002385 return mRequestThread->queueTrigger(trigger,
2386 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002387}
2388
Jianing Weicb0652e2014-03-12 18:29:36 -07002389status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002390 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002391 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002392 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002393
Zhijun He7ef20392014-04-21 16:04:17 -07002394 {
2395 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002396
2397 // b/116514106 "disconnect()" can get called twice for the same device. The
2398 // camera device will not be initialized during the second run.
2399 if (mStatus == STATUS_UNINITIALIZED) {
2400 return OK;
2401 }
2402
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002403 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002404 }
2405
Emilian Peev08dd2452017-04-06 16:55:14 +01002406 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002407}
2408
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002409status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002410 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2411}
2412
2413status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002414 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002415 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002416 Mutex::Autolock il(mInterfaceLock);
2417 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002418
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002419 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2420 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002421 CLOGE("Stream %d does not exist", streamId);
2422 return BAD_VALUE;
2423 }
2424
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002425 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002426 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002427 return BAD_VALUE;
2428 }
2429
2430 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002431 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002432 return BAD_VALUE;
2433 }
2434
Ruben Brunkc78ac262015-08-13 17:58:46 -07002435 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002436}
2437
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002438status_t Camera3Device::tearDown(int streamId) {
2439 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002440 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002441 Mutex::Autolock il(mInterfaceLock);
2442 Mutex::Autolock l(mLock);
2443
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002444 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2445 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002446 CLOGE("Stream %d does not exist", streamId);
2447 return BAD_VALUE;
2448 }
2449
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002450 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2451 CLOGE("Stream %d is a target of a in-progress request", streamId);
2452 return BAD_VALUE;
2453 }
2454
2455 return stream->tearDown();
2456}
2457
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002458status_t Camera3Device::addBufferListenerForStream(int streamId,
2459 wp<Camera3StreamBufferListener> listener) {
2460 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002461 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002462 Mutex::Autolock il(mInterfaceLock);
2463 Mutex::Autolock l(mLock);
2464
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002465 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2466 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002467 CLOGE("Stream %d does not exist", streamId);
2468 return BAD_VALUE;
2469 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002470 stream->addBufferListener(listener);
2471
2472 return OK;
2473}
2474
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002475/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002476 * Methods called by subclasses
2477 */
2478
2479void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002480 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002481 {
2482 // Need mLock to safely update state and synchronize to current
2483 // state of methods in flight.
2484 Mutex::Autolock l(mLock);
2485 // We can get various system-idle notices from the status tracker
2486 // while starting up. Only care about them if we've actually sent
2487 // in some requests recently.
2488 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2489 return;
2490 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002491 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2492 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002493 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002494
2495 // Skip notifying listener if we're doing some user-transparent
2496 // state changes
2497 if (mPauseStateNotify) return;
2498 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002499
2500 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002501 {
2502 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002503 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002504 }
2505 if (idle && listener != NULL) {
2506 listener->notifyIdle();
2507 }
2508}
2509
Shuzhen Wang758c2152017-01-10 18:26:18 -08002510status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002511 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002512 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002513 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2514 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002515
2516 if (surfaceIds == nullptr) {
2517 return BAD_VALUE;
2518 }
2519
Zhijun He5d677d12016-05-29 16:52:39 -07002520 Mutex::Autolock il(mInterfaceLock);
2521 Mutex::Autolock l(mLock);
2522
Shuzhen Wang758c2152017-01-10 18:26:18 -08002523 if (consumers.size() == 0) {
2524 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002525 return BAD_VALUE;
2526 }
2527
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002528 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2529 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002530 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002531 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002532 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002533
2534 // isConsumerConfigurationDeferred will be off after setConsumers
2535 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002536 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002537 if (res != OK) {
2538 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2539 return res;
2540 }
2541
Emilian Peev40ead602017-09-26 15:46:36 +01002542 for (auto &consumer : consumers) {
2543 int id = stream->getSurfaceId(consumer);
2544 if (id < 0) {
2545 CLOGE("Invalid surface id!");
2546 return BAD_VALUE;
2547 }
2548 surfaceIds->push_back(id);
2549 }
2550
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002551 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002552 if (!stream->isConfiguring()) {
2553 CLOGE("Stream %d was already fully configured.", streamId);
2554 return INVALID_OPERATION;
2555 }
Zhijun He5d677d12016-05-29 16:52:39 -07002556
Shuzhen Wang0129d522016-10-30 22:43:41 -07002557 res = stream->finishConfiguration();
2558 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002559 // If finishConfiguration fails due to abandoned surface, do not set
2560 // device to error state.
2561 bool isSurfaceAbandoned =
2562 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2563 if (!isSurfaceAbandoned) {
2564 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2565 stream->getId(), strerror(-res), res);
2566 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002567 return res;
2568 }
Zhijun He5d677d12016-05-29 16:52:39 -07002569 }
2570
2571 return OK;
2572}
2573
Emilian Peev40ead602017-09-26 15:46:36 +01002574status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2575 const std::vector<OutputStreamInfo> &outputInfo,
2576 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2577 Mutex::Autolock il(mInterfaceLock);
2578 Mutex::Autolock l(mLock);
2579
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002580 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2581 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002582 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002583 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002584 }
2585
2586 for (const auto &it : removedSurfaceIds) {
2587 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2588 CLOGE("Shared surface still part of a pending request!");
2589 return -EBUSY;
2590 }
2591 }
2592
Emilian Peev40ead602017-09-26 15:46:36 +01002593 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2594 if (res != OK) {
2595 CLOGE("Stream %d failed to update stream (error %d %s) ",
2596 streamId, res, strerror(-res));
2597 if (res == UNKNOWN_ERROR) {
2598 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2599 __FUNCTION__);
2600 }
2601 return res;
2602 }
2603
2604 return res;
2605}
2606
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002607status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2608 Mutex::Autolock il(mInterfaceLock);
2609 Mutex::Autolock l(mLock);
2610
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002611 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2612 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002613 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2614 return BAD_VALUE;
2615 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002616 return stream->dropBuffers(dropping);
2617}
2618
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002619/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002620 * Camera3Device private methods
2621 */
2622
2623sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002624 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002625 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002626
2627 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002628 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002629
2630 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002631 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002632 if (inputStreams.count > 0) {
2633 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002634 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002635 CLOGE("Request references unknown input stream %d",
2636 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002637 return NULL;
2638 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002639
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002640 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002641 SET_ERR_L("%s: input stream %d is not configured!",
2642 __FUNCTION__, mInputStream->getId());
2643 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002644 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002645 // Check if stream prepare is blocking requests.
2646 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002647 CLOGE("Request references an input stream that's being prepared!");
2648 return NULL;
2649 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002650
2651 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002652 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002653 }
2654
2655 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002656 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002657 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002658 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002659 return NULL;
2660 }
2661
2662 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002663 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2664 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002665 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002666 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002667 return NULL;
2668 }
Zhijun He5d677d12016-05-29 16:52:39 -07002669 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002670 auto iter = surfaceMap.find(streams.data.i32[i]);
2671 if (iter != surfaceMap.end()) {
2672 const std::vector<size_t>& surfaces = iter->second;
2673 for (const auto& surface : surfaces) {
2674 if (stream->isConsumerConfigurationDeferred(surface)) {
2675 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2676 "due to deferred consumer", stream->getId(), surface);
2677 return NULL;
2678 }
2679 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002680 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002681 }
2682
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002683 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002684 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2685 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002686 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002687 // Check if stream prepare is blocking requests.
2688 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002689 CLOGE("Request references an output stream that's being prepared!");
2690 return NULL;
2691 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002692
2693 newRequest->mOutputStreams.push(stream);
2694 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002695 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002696 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002697
2698 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002699}
2700
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002701bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2702 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2703 Size size = mSupportedOpaqueInputSizes[i];
2704 if (size.width == width && size.height == height) {
2705 return true;
2706 }
2707 }
2708
2709 return false;
2710}
2711
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002712void Camera3Device::cancelStreamsConfigurationLocked() {
2713 int res = OK;
2714 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2715 res = mInputStream->cancelConfiguration();
2716 if (res != OK) {
2717 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2718 mInputStream->getId(), strerror(-res), res);
2719 }
2720 }
2721
2722 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002723 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002724 if (outputStream->isConfiguring()) {
2725 res = outputStream->cancelConfiguration();
2726 if (res != OK) {
2727 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2728 outputStream->getId(), strerror(-res), res);
2729 }
2730 }
2731 }
2732
2733 // Return state to that at start of call, so that future configures
2734 // properly clean things up
2735 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2736 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002737
2738 res = mPreparerThread->resume();
2739 if (res != OK) {
2740 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2741 }
2742}
2743
2744bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2745 ATRACE_CALL();
2746 bool ret = false;
2747
Jayant Chowdharydfc46592020-01-30 13:09:59 -08002748 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002749 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2750
2751 Mutex::Autolock l(mLock);
2752 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2753 if (rc == NO_ERROR) {
2754 mNeedConfig = true;
2755 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2756 if (rc == NO_ERROR) {
2757 ret = true;
2758 mPauseStateNotify = false;
2759 //Moving to active state while holding 'mLock' is important.
2760 //There could be pending calls to 'create-/deleteStream' which
2761 //will trigger another stream configuration while the already
2762 //present streams end up with outstanding buffers that will
2763 //not get drained.
2764 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002765 } else if (rc == DEAD_OBJECT) {
2766 // DEAD_OBJECT can be returned if either the consumer surface is
2767 // abandoned, or the HAL has died.
2768 // - If the HAL has died, configureStreamsLocked call will set
2769 // device to error state,
2770 // - If surface is abandoned, we should not set device to error
2771 // state.
2772 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002773 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002774 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002775 }
2776 } else {
2777 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2778 }
2779
2780 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002781}
2782
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002783status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002784 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002785 ATRACE_CALL();
2786 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002787
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002788 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002789 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002790 return INVALID_OPERATION;
2791 }
2792
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002793 if (operatingMode < 0) {
2794 CLOGE("Invalid operating mode: %d", operatingMode);
2795 return BAD_VALUE;
2796 }
2797
2798 bool isConstrainedHighSpeed =
2799 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2800 operatingMode;
2801
2802 if (mOperatingMode != operatingMode) {
2803 mNeedConfig = true;
2804 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2805 mOperatingMode = operatingMode;
2806 }
2807
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002808 if (!mNeedConfig) {
2809 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2810 return OK;
2811 }
2812
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002813 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2814 // adding a dummy stream instead.
2815 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2816 if (mOutputStreams.size() == 0) {
2817 addDummyStreamLocked();
2818 } else {
2819 tryRemoveDummyStreamLocked();
2820 }
2821
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002822 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002823 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002824
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002825 mPreparerThread->pause();
2826
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002827 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002828 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002829 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2830
2831 Vector<camera3_stream_t*> streams;
2832 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002833 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002834
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002835
2836 if (mInputStream != NULL) {
2837 camera3_stream_t *inputStream;
2838 inputStream = mInputStream->startConfiguration();
2839 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002840 CLOGE("Can't start input stream configuration");
2841 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002842 return INVALID_OPERATION;
2843 }
2844 streams.add(inputStream);
2845 }
2846
2847 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002848
2849 // Don't configure bidi streams twice, nor add them twice to the list
2850 if (mOutputStreams[i].get() ==
2851 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2852
2853 config.num_streams--;
2854 continue;
2855 }
2856
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002857 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002858 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002859 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002860 CLOGE("Can't start output stream configuration");
2861 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002862 return INVALID_OPERATION;
2863 }
2864 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002865
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002866 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002867 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2868 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002869 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2870 bufferSizes[k] = static_cast<uint32_t>(
2871 getJpegBufferSize(outputStream->width, outputStream->height));
2872 } else if (outputStream->data_space ==
2873 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2874 bufferSizes[k] = outputStream->width * outputStream->height;
2875 } else {
2876 ALOGW("%s: Blob dataSpace %d not supported",
2877 __FUNCTION__, outputStream->data_space);
2878 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002879 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002880 }
2881
2882 config.streams = streams.editArray();
2883
2884 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002885 // max_buffers, usage, and priv fields, as well as data_space and format
2886 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002887
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002888 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002889 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002890 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002891
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002892 if (res == BAD_VALUE) {
2893 // HAL rejected this set of streams as unsupported, clean up config
2894 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002895 CLOGE("Set of requested inputs/outputs not supported by HAL");
2896 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002897 return BAD_VALUE;
2898 } else if (res != OK) {
2899 // Some other kind of error from configure_streams - this is not
2900 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002901 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2902 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002903 return res;
2904 }
2905
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002906 // Finish all stream configuration immediately.
2907 // TODO: Try to relax this later back to lazy completion, which should be
2908 // faster
2909
Igor Murashkin073f8572013-05-02 14:59:28 -07002910 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002911 bool streamReConfigured = false;
2912 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002913 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002914 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002915 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002916 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002917 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2918 return DEAD_OBJECT;
2919 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002920 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002921 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002922 if (streamReConfigured) {
2923 mInterface->onStreamReConfigured(mInputStream->getId());
2924 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002925 }
2926
2927 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002928 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002929 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002930 bool streamReConfigured = false;
2931 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002932 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002933 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002934 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002935 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002936 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2937 return DEAD_OBJECT;
2938 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002939 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002940 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002941 if (streamReConfigured) {
2942 mInterface->onStreamReConfigured(outputStream->getId());
2943 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002944 }
2945 }
2946
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002947 // Request thread needs to know to avoid using repeat-last-settings protocol
2948 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002949 if (notifyRequestThread) {
2950 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2951 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002952
Zhijun He90f7c372016-08-16 16:19:43 -07002953 char value[PROPERTY_VALUE_MAX];
2954 property_get("camera.fifo.disable", value, "0");
2955 int32_t disableFifo = atoi(value);
2956 if (disableFifo != 1) {
2957 // Boost priority of request thread to SCHED_FIFO.
2958 pid_t requestThreadTid = mRequestThread->getTid();
2959 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002960 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002961 if (res != OK) {
2962 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2963 strerror(-res), res);
2964 } else {
2965 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2966 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002967 }
2968
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002969 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002970 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2971 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2972 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2973 sessionParams.unlock(newSessionParams);
2974 mSessionParams.unlock(currentSessionParams);
2975 if (updateSessionParams) {
2976 mSessionParams = sessionParams;
2977 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002978
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002979 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002980
Ruben Brunk183f0562015-08-12 12:55:02 -07002981 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2982 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002983
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002984 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002985
Zhijun He0a210512014-07-24 13:45:15 -07002986 // tear down the deleted streams after configure streams.
2987 mDeletedStreams.clear();
2988
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002989 auto rc = mPreparerThread->resume();
2990 if (rc != OK) {
2991 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2992 return rc;
2993 }
2994
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002995 if (mDummyStreamId == NO_STREAM) {
2996 mRequestBufferSM.onStreamsConfigured();
2997 }
2998
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002999 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003000}
3001
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003002status_t Camera3Device::addDummyStreamLocked() {
3003 ATRACE_CALL();
3004 status_t res;
3005
3006 if (mDummyStreamId != NO_STREAM) {
3007 // Should never be adding a second dummy stream when one is already
3008 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003009 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
3010 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003011 return INVALID_OPERATION;
3012 }
3013
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003014 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003015
3016 sp<Camera3OutputStreamInterface> dummyStream =
3017 new Camera3DummyStream(mNextStreamId);
3018
3019 res = mOutputStreams.add(mNextStreamId, dummyStream);
3020 if (res < 0) {
3021 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
3022 return res;
3023 }
3024
3025 mDummyStreamId = mNextStreamId;
3026 mNextStreamId++;
3027
3028 return OK;
3029}
3030
3031status_t Camera3Device::tryRemoveDummyStreamLocked() {
3032 ATRACE_CALL();
3033 status_t res;
3034
3035 if (mDummyStreamId == NO_STREAM) return OK;
3036 if (mOutputStreams.size() == 1) return OK;
3037
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003038 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003039
3040 // Ok, have a dummy stream and there's at least one other output stream,
3041 // so remove the dummy
3042
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003043 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
3044 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003045 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3046 return INVALID_OPERATION;
3047 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003048 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003049
3050 // Free up the stream endpoint so that it can be used by some other stream
3051 res = deletedStream->disconnect();
3052 if (res != OK) {
3053 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3054 // fall through since we want to still list the stream as deleted.
3055 }
3056 mDeletedStreams.add(deletedStream);
3057 mDummyStreamId = NO_STREAM;
3058
3059 return res;
3060}
3061
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003062void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003063 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003064 Mutex::Autolock l(mLock);
3065 va_list args;
3066 va_start(args, fmt);
3067
3068 setErrorStateLockedV(fmt, args);
3069
3070 va_end(args);
3071}
3072
3073void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003074 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003075 Mutex::Autolock l(mLock);
3076 setErrorStateLockedV(fmt, args);
3077}
3078
3079void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3080 va_list args;
3081 va_start(args, fmt);
3082
3083 setErrorStateLockedV(fmt, args);
3084
3085 va_end(args);
3086}
3087
3088void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003089 // Print out all error messages to log
3090 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003091 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003092
3093 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003094 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003095
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003096 mErrorCause = errorCause;
3097
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003098 if (mRequestThread != nullptr) {
3099 mRequestThread->setPaused(true);
3100 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003101 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003102
3103 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003104 sp<NotificationListener> listener = mListener.promote();
3105 if (listener != NULL) {
3106 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003107 CaptureResultExtras());
3108 }
3109
3110 // Save stack trace. View by dumping it later.
3111 CameraTraces::saveTrace();
3112 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003113}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003114
3115/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003116 * In-flight request management
3117 */
3118
Jianing Weicb0652e2014-03-12 18:29:36 -07003119status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003120 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003121 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003122 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003123 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003124 ATRACE_CALL();
3125 Mutex::Autolock l(mInFlightLock);
3126
3127 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003128 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003129 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3130 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003131 if (res < 0) return res;
3132
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003133 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003134 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3135 // avoid a deadlock during reprocess requests.
3136 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003137 if (mStatusTracker != nullptr) {
3138 mStatusTracker->markComponentActive(mInFlightStatusId);
3139 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003140 }
3141
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003142 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003143 return OK;
3144}
3145
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003146void Camera3Device::returnOutputBuffers(
3147 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003148 nsecs_t timestamp, bool timestampIncreasing,
3149 const SurfaceMap& outputSurfaces,
3150 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003151
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003152 for (size_t i = 0; i < numBuffers; i++)
3153 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003154 if (outputBuffers[i].buffer == nullptr) {
3155 if (!mUseHalBufManager) {
3156 // With HAL buffer management API, HAL sometimes will have to return buffers that
3157 // has not got a output buffer handle filled yet. This is though illegal if HAL
3158 // buffer management API is not being used.
3159 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3160 }
3161 continue;
3162 }
3163
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003164 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3165 int streamId = stream->getId();
3166 const auto& it = outputSurfaces.find(streamId);
3167 status_t res = OK;
3168 if (it != outputSurfaces.end()) {
3169 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003170 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3171 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003172 } else {
3173 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003174 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3175 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003176 }
3177
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003178 // Note: stream may be deallocated at this point, if this buffer was
3179 // the last reference to it.
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003180 if (res == NO_INIT || res == DEAD_OBJECT) {
3181 ALOGV("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
3182 } else if (res != OK) {
3183 ALOGE("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003184 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003185
3186 // Long processing consumers can cause returnBuffer timeout for shared stream
3187 // If that happens, cancel the buffer and send a buffer error to client
3188 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3189 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3190 // cancel the buffer
3191 camera3_stream_buffer_t sb = outputBuffers[i];
3192 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003193 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3194 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003195
3196 // notify client buffer error
3197 sp<NotificationListener> listener;
3198 {
3199 Mutex::Autolock l(mOutputLock);
3200 listener = mListener.promote();
3201 }
3202
3203 if (listener != nullptr) {
3204 CaptureResultExtras extras = inResultExtras;
3205 extras.errorStreamId = streamId;
3206 listener->notifyError(
3207 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3208 extras);
3209 }
3210 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003211 }
3212}
3213
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003214void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003215 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003216 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003217 mInFlightMap.removeItemsAt(idx, 1);
3218
3219 // Indicate idle inFlightMap to the status tracker
3220 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003221 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003222 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3223 // avoid a deadlock during reprocess requests.
3224 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003225 if (mStatusTracker != nullptr) {
3226 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3227 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003228 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003229 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003230}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003231
3232void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3233
3234 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3235 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3236
3237 nsecs_t sensorTimestamp = request.sensorTimestamp;
3238 nsecs_t shutterTimestamp = request.shutterTimestamp;
3239
3240 // Check if it's okay to remove the request from InFlightMap:
3241 // In the case of a successful request:
3242 // all input and output buffers, all result metadata, shutter callback
3243 // arrived.
3244 // In the case of a unsuccessful request:
3245 // all input and output buffers arrived.
3246 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003247 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003248 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003249 if (request.stillCapture) {
3250 ATRACE_ASYNC_END("still capture", frameNumber);
3251 }
3252
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003253 ATRACE_ASYNC_END("frame capture", frameNumber);
3254
Shuzhen Wang403044a2017-02-26 23:29:04 -08003255 // Sanity check - if sensor timestamp matches shutter timestamp in the
3256 // case of request having callback.
3257 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003258 sensorTimestamp != shutterTimestamp) {
3259 SET_ERR("sensor timestamp (%" PRId64
3260 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3261 sensorTimestamp, frameNumber, shutterTimestamp);
3262 }
3263
3264 // for an unsuccessful request, it may have pending output buffers to
3265 // return.
3266 assert(request.requestStatus != OK ||
3267 request.pendingOutputBuffers.size() == 0);
3268 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003269 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3270 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003271
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003272 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003273 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3274 }
3275
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003276 // Sanity check - if we have too many in-flight frames with long total inflight duration,
3277 // something has likely gone wrong. This might still be legit only if application send in
3278 // a long burst of long exposure requests.
3279 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3280 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3281 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3282 mInFlightMap.size(), mExpectedInflightDuration);
3283 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3284 kInFlightWarnLimitHighSpeed) {
3285 CLOGW("In-flight list too large for high speed configuration: %zu,"
3286 "total inflight duration %" PRIu64,
3287 mInFlightMap.size(), mExpectedInflightDuration);
3288 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003289 }
3290}
3291
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003292void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003293 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003294 { // First return buffers cached in mInFlightMap
3295 Mutex::Autolock l(mInFlightLock);
3296 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3297 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3298 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003299 request.pendingOutputBuffers.size(), 0,
3300 /*timestampIncreasing*/true, request.outputSurfaces,
3301 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003302 }
3303 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003304 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003305 }
3306
3307 // Then return all inflight buffers not returned by HAL
3308 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3309 mInterface->getInflightBufferKeys(&inflightKeys);
3310
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003311 // Inflight buffers for HAL buffer manager
3312 std::vector<uint64_t> inflightRequestBufferKeys;
3313 mInterface->getInflightRequestBufferKeys(&inflightRequestBufferKeys);
3314
3315 // (streamId, frameNumber, buffer_handle_t*) tuple for all inflight buffers.
3316 // frameNumber will be -1 for buffers from HAL buffer manager
3317 std::vector<std::tuple<int32_t, int32_t, buffer_handle_t*>> inflightBuffers;
3318 inflightBuffers.reserve(inflightKeys.size() + inflightRequestBufferKeys.size());
3319
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003320 for (auto& pair : inflightKeys) {
3321 int32_t frameNumber = pair.first;
3322 int32_t streamId = pair.second;
3323 buffer_handle_t* buffer;
3324 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3325 if (res != OK) {
3326 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3327 __FUNCTION__, frameNumber, streamId);
3328 continue;
3329 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003330 inflightBuffers.push_back(std::make_tuple(streamId, frameNumber, buffer));
3331 }
3332
3333 for (auto& bufferId : inflightRequestBufferKeys) {
3334 int32_t streamId = -1;
3335 buffer_handle_t* buffer = nullptr;
3336 status_t res = mInterface->popInflightRequestBuffer(bufferId, &buffer, &streamId);
3337 if (res != OK) {
3338 ALOGE("%s: cannot find in-flight buffer %" PRIu64, __FUNCTION__, bufferId);
3339 continue;
3340 }
3341 inflightBuffers.push_back(std::make_tuple(streamId, /*frameNumber*/-1, buffer));
3342 }
3343
3344 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3345 for (auto& tuple : inflightBuffers) {
3346 status_t res = OK;
3347 int32_t streamId = std::get<0>(tuple);
3348 int32_t frameNumber = std::get<1>(tuple);
3349 buffer_handle_t* buffer = std::get<2>(tuple);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003350
3351 camera3_stream_buffer_t streamBuffer;
3352 streamBuffer.buffer = buffer;
3353 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3354 streamBuffer.acquire_fence = -1;
3355 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003356
3357 // First check if the buffer belongs to deleted stream
3358 bool streamDeleted = false;
3359 for (auto& stream : mDeletedStreams) {
3360 if (streamId == stream->getId()) {
3361 streamDeleted = true;
3362 // Return buffer to deleted stream
3363 camera3_stream* halStream = stream->asHalStream();
3364 streamBuffer.stream = halStream;
3365 switch (halStream->stream_type) {
3366 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003367 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3368 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003369 if (res != OK) {
3370 ALOGE("%s: Can't return output buffer for frame %d to"
3371 " stream %d: %s (%d)", __FUNCTION__,
3372 frameNumber, streamId, strerror(-res), res);
3373 }
3374 break;
3375 case CAMERA3_STREAM_INPUT:
3376 res = stream->returnInputBuffer(streamBuffer);
3377 if (res != OK) {
3378 ALOGE("%s: Can't return input buffer for frame %d to"
3379 " stream %d: %s (%d)", __FUNCTION__,
3380 frameNumber, streamId, strerror(-res), res);
3381 }
3382 break;
3383 default: // Bi-direcitonal stream is deprecated
3384 ALOGE("%s: stream %d has unknown stream type %d",
3385 __FUNCTION__, streamId, halStream->stream_type);
3386 break;
3387 }
3388 break;
3389 }
3390 }
3391 if (streamDeleted) {
3392 continue;
3393 }
3394
3395 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003396 if (streamId == inputStreamId) {
3397 streamBuffer.stream = mInputStream->asHalStream();
3398 res = mInputStream->returnInputBuffer(streamBuffer);
3399 if (res != OK) {
3400 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003401 " stream %d: %s (%d)", __FUNCTION__,
3402 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003403 }
3404 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003405 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3406 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003407 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3408 continue;
3409 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003410 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003411 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3412 }
3413 }
3414}
3415
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003416void Camera3Device::insertResultLocked(CaptureResult *result,
3417 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003418 if (result == nullptr) return;
3419
Emilian Peev71c73a22017-03-21 16:35:51 +00003420 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3421 result->mMetadata.getAndLock());
3422 set_camera_metadata_vendor_id(meta, mVendorTagId);
3423 result->mMetadata.unlock(meta);
3424
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003425 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3426 (int32_t*)&frameNumber, 1) != OK) {
3427 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3428 return;
3429 }
3430
3431 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3432 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3433 return;
3434 }
3435
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003436 // Update vendor tag id for physical metadata
3437 for (auto& physicalMetadata : result->mPhysicalMetadatas) {
3438 camera_metadata_t *pmeta = const_cast<camera_metadata_t *>(
3439 physicalMetadata.mPhysicalCameraMetadata.getAndLock());
3440 set_camera_metadata_vendor_id(pmeta, mVendorTagId);
3441 physicalMetadata.mPhysicalCameraMetadata.unlock(pmeta);
3442 }
3443
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003444 // Valid result, insert into queue
3445 List<CaptureResult>::iterator queuedResult =
3446 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3447 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3448 ", burstId = %" PRId32, __FUNCTION__,
3449 queuedResult->mResultExtras.requestId,
3450 queuedResult->mResultExtras.frameNumber,
3451 queuedResult->mResultExtras.burstId);
3452
3453 mResultSignal.signal();
3454}
3455
3456
3457void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003458 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003459 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003460 Mutex::Autolock l(mOutputLock);
3461
3462 CaptureResult captureResult;
3463 captureResult.mResultExtras = resultExtras;
3464 captureResult.mMetadata = partialResult;
3465
Shuzhen Wang268a1362018-10-16 16:32:59 -07003466 // Fix up result metadata for monochrome camera.
3467 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3468 if (res != OK) {
3469 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3470 return;
3471 }
3472
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003473 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003474}
3475
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003476
3477void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3478 CaptureResultExtras &resultExtras,
3479 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003480 uint32_t frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003481 bool reprocess, bool zslStillCapture,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003482 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003483 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003484 if (pendingMetadata.isEmpty())
3485 return;
3486
3487 Mutex::Autolock l(mOutputLock);
3488
3489 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003490 if (reprocess) {
3491 if (frameNumber < mNextReprocessResultFrameNumber) {
3492 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003493 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003494 frameNumber, mNextReprocessResultFrameNumber);
3495 return;
3496 }
3497 mNextReprocessResultFrameNumber = frameNumber + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003498 } else if (zslStillCapture) {
3499 if (frameNumber < mNextZslStillResultFrameNumber) {
3500 SET_ERR("Out-of-order ZSL still capture result metadata submitted! "
3501 "(got frame number %d, expecting %d)",
3502 frameNumber, mNextZslStillResultFrameNumber);
3503 return;
3504 }
3505 mNextZslStillResultFrameNumber = frameNumber + 1;
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003506 } else {
3507 if (frameNumber < mNextResultFrameNumber) {
3508 SET_ERR("Out-of-order capture result metadata submitted! "
3509 "(got frame number %d, expecting %d)",
3510 frameNumber, mNextResultFrameNumber);
3511 return;
3512 }
3513 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003514 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003515
3516 CaptureResult captureResult;
3517 captureResult.mResultExtras = resultExtras;
3518 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003519 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003520
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003521 // Append any previous partials to form a complete result
3522 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3523 captureResult.mMetadata.append(collectedPartialResult);
3524 }
3525
3526 captureResult.mMetadata.sort();
3527
3528 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003529 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3530 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003531 SET_ERR("No timestamp provided by HAL for frame %d!",
3532 frameNumber);
3533 return;
3534 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003535 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3536 camera_metadata_entry timestamp =
3537 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3538 if (timestamp.count == 0) {
3539 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3540 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3541 return;
3542 }
3543 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003544
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003545 // Fix up some result metadata to account for HAL-level distortion correction
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003546 status_t res =
3547 mDistortionMappers[mId.c_str()].correctCaptureResult(&captureResult.mMetadata);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003548 if (res != OK) {
3549 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3550 frameNumber, strerror(res), res);
3551 return;
3552 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003553 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3554 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3555 if (mDistortionMappers.find(cameraId8.c_str()) == mDistortionMappers.end()) {
3556 continue;
3557 }
3558 res = mDistortionMappers[cameraId8.c_str()].correctCaptureResult(
3559 &physicalMetadata.mPhysicalCameraMetadata);
3560 if (res != OK) {
3561 SET_ERR("Unable to correct physical capture result metadata for frame %d: %s (%d)",
3562 frameNumber, strerror(res), res);
3563 return;
3564 }
3565 }
3566
Shuzhen Wang268a1362018-10-16 16:32:59 -07003567 // Fix up result metadata for monochrome camera.
3568 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3569 if (res != OK) {
3570 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3571 return;
3572 }
3573 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3574 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3575 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3576 physicalMetadata.mPhysicalCameraMetadata);
3577 if (res != OK) {
3578 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3579 return;
3580 }
3581 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003582
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003583 std::unordered_map<std::string, CameraMetadata> monitoredPhysicalMetadata;
3584 for (auto& m : physicalMetadatas) {
3585 monitoredPhysicalMetadata.emplace(String8(m.mPhysicalCameraId).string(),
3586 CameraMetadata(m.mPhysicalCameraMetadata));
3587 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003588 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003589 frameNumber, timestamp.data.i64[0], captureResult.mMetadata,
3590 monitoredPhysicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003591
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003592 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003593}
3594
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003595/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003596 * Camera HAL device callback methods
3597 */
3598
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003599void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003600 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003601
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003602 status_t res;
3603
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003604 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003605 if (result->result == NULL && result->num_output_buffers == 0 &&
3606 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003607 SET_ERR("No result data provided by HAL for frame %d",
3608 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003609 return;
3610 }
Zhijun He204e3292014-07-14 17:09:23 -07003611
Zhijun He204e3292014-07-14 17:09:23 -07003612 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003613 result->result != NULL &&
3614 result->partial_result != 1) {
3615 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3616 " if partial result is not supported",
3617 frameNumber, result->partial_result);
3618 return;
3619 }
3620
3621 bool isPartialResult = false;
3622 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003623 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003624
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003625 // Get shutter timestamp and resultExtras from list of in-flight requests,
3626 // where it was added by the shutter notification for this frame. If the
3627 // shutter timestamp isn't received yet, append the output buffers to the
3628 // in-flight request and they will be returned when the shutter timestamp
3629 // arrives. Update the in-flight status and remove the in-flight entry if
3630 // all result data and shutter timestamp have been received.
3631 nsecs_t shutterTimestamp = 0;
3632
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003633 {
3634 Mutex::Autolock l(mInFlightLock);
3635 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3636 if (idx == NAME_NOT_FOUND) {
3637 SET_ERR("Unknown frame number for capture result: %d",
3638 frameNumber);
3639 return;
3640 }
3641 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003642 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3643 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003644 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003645 __FUNCTION__, request.resultExtras.requestId,
3646 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003647 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003648 // Always update the partial count to the latest one if it's not 0
3649 // (buffers only). When framework aggregates adjacent partial results
3650 // into one, the latest partial count will be used.
3651 if (result->partial_result != 0)
3652 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003653
3654 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003655 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003656 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3657 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3658 " the range of [1, %d] when metadata is included in the result",
3659 frameNumber, result->partial_result, mNumPartialResults);
3660 return;
3661 }
3662 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003663 if (isPartialResult && result->num_physcam_metadata) {
3664 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3665 " physical camera result", frameNumber);
3666 return;
3667 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003668 if (isPartialResult) {
3669 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003670 }
3671
Shuzhen Wang4a472662017-02-26 23:29:04 -08003672 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003673 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003674 sendPartialCaptureResult(result->result, request.resultExtras,
3675 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003676 }
3677 }
3678
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003679 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003680 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003681
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003682 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003683 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003684 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3685 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3686 request.physicalCameraIds.size(), result->num_physcam_metadata);
3687 return;
3688 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003689 if (request.haveResultMetadata) {
3690 SET_ERR("Called multiple times with metadata for frame %d",
3691 frameNumber);
3692 return;
3693 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003694 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3695 String8 physicalId(result->physcam_ids[i]);
3696 std::set<String8>::iterator cameraIdIter =
3697 request.physicalCameraIds.find(physicalId);
3698 if (cameraIdIter != request.physicalCameraIds.end()) {
3699 request.physicalCameraIds.erase(cameraIdIter);
3700 } else {
3701 SET_ERR("Total result for frame %d has already returned for camera %s",
3702 frameNumber, physicalId.c_str());
3703 return;
3704 }
3705 }
Zhijun He204e3292014-07-14 17:09:23 -07003706 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003707 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003708 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003709 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003710 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003711 request.haveResultMetadata = true;
3712 }
3713
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003714 uint32_t numBuffersReturned = result->num_output_buffers;
3715 if (result->input_buffer != NULL) {
3716 if (hasInputBufferInRequest) {
3717 numBuffersReturned += 1;
3718 } else {
3719 ALOGW("%s: Input buffer should be NULL if there is no input"
3720 " buffer sent in the request",
3721 __FUNCTION__);
3722 }
3723 }
3724 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003725 if (request.numBuffersLeft < 0) {
3726 SET_ERR("Too many buffers returned for frame %d",
3727 frameNumber);
3728 return;
3729 }
3730
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003731 camera_metadata_ro_entry_t entry;
3732 res = find_camera_metadata_ro_entry(result->result,
3733 ANDROID_SENSOR_TIMESTAMP, &entry);
3734 if (res == OK && entry.count == 1) {
3735 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003736 }
3737
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003738 // If shutter event isn't received yet, append the output buffers to
3739 // the in-flight request. Otherwise, return the output buffers to
3740 // streams.
3741 if (shutterTimestamp == 0) {
3742 request.pendingOutputBuffers.appendArray(result->output_buffers,
3743 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003744 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003745 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003746 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003747 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3748 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003749 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003750
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003751 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003752 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3753 CameraMetadata physicalMetadata;
3754 physicalMetadata.append(result->physcam_metadata[i]);
3755 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3756 physicalMetadata});
3757 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003758 if (shutterTimestamp == 0) {
3759 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003760 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003761 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003762 CameraMetadata metadata;
3763 metadata = result->result;
3764 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003765 collectedPartialResult, frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003766 hasInputBufferInRequest, request.zslCapture && request.stillCapture,
3767 request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003768 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003769 }
3770
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003771 removeInFlightRequestIfReadyLocked(idx);
3772 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003773
Zhijun Hef0d962a2014-06-30 10:24:11 -07003774 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003775 if (hasInputBufferInRequest) {
3776 Camera3Stream *stream =
3777 Camera3Stream::cast(result->input_buffer->stream);
3778 res = stream->returnInputBuffer(*(result->input_buffer));
3779 // Note: stream may be deallocated at this point, if this buffer was the
3780 // last reference to it.
3781 if (res != OK) {
3782 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3783 " its stream:%s (%d)", __FUNCTION__,
3784 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003785 }
3786 } else {
3787 ALOGW("%s: Input buffer should be NULL if there is no input"
3788 " buffer sent in the request, skipping input buffer return.",
3789 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003790 }
3791 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003792}
3793
3794void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003795 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003796 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003797 {
3798 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003799 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003800 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003801
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003802 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003803 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003804 return;
3805 }
3806
3807 switch (msg->type) {
3808 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003809 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003810 break;
3811 }
3812 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003813 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003814 break;
3815 }
3816 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003817 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003818 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003819 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003820}
3821
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003822void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003823 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003824 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003825 // Map camera HAL error codes to ICameraDeviceCallback error codes
3826 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003827 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003828 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003829 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003830 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003831 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003832 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003833 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003834 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003835 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003836 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003837 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003838 };
3839
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003840 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003841 ((msg.error_code >= 0) &&
3842 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3843 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003844 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003845
3846 int streamId = 0;
Emilian Peevedec62d2019-03-19 17:59:24 -07003847 String16 physicalCameraId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003848 if (msg.error_stream != NULL) {
3849 Camera3Stream *stream =
3850 Camera3Stream::cast(msg.error_stream);
3851 streamId = stream->getId();
Emilian Peevedec62d2019-03-19 17:59:24 -07003852 physicalCameraId = String16(stream->physicalCameraId());
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003853 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003854 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3855 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003856 streamId, msg.error_code);
3857
3858 CaptureResultExtras resultExtras;
3859 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003860 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003861 // SET_ERR calls notifyError
3862 SET_ERR("Camera HAL reported serious device error");
3863 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003864 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3865 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3866 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003867 {
3868 Mutex::Autolock l(mInFlightLock);
3869 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3870 if (idx >= 0) {
3871 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3872 r.requestStatus = msg.error_code;
3873 resultExtras = r.resultExtras;
Emilian Peevedec62d2019-03-19 17:59:24 -07003874 bool logicalDeviceResultError = false;
3875 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3876 errorCode) {
3877 if (physicalCameraId.size() > 0) {
3878 String8 cameraId(physicalCameraId);
3879 if (r.physicalCameraIds.find(cameraId) == r.physicalCameraIds.end()) {
3880 ALOGE("%s: Reported result failure for physical camera device: %s "
3881 " which is not part of the respective request!",
3882 __FUNCTION__, cameraId.string());
3883 break;
3884 }
3885 resultExtras.errorPhysicalCameraId = physicalCameraId;
3886 } else {
3887 logicalDeviceResultError = true;
3888 }
3889 }
3890
3891 if (logicalDeviceResultError
Shuzhen Wang20f57342017-08-24 15:39:05 -07003892 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3893 errorCode) {
3894 r.skipResultMetadata = true;
3895 }
Emilian Peevedec62d2019-03-19 17:59:24 -07003896 if (logicalDeviceResultError) {
Emilian Peevba0fac32017-03-30 09:05:34 +01003897 // In case of missing result check whether the buffers
3898 // returned. If they returned, then remove inflight
3899 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003900 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3901 // otherwise we are depending on HAL to send the buffers back after
3902 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003903 removeInFlightRequestIfReadyLocked(idx);
3904 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003905 } else {
3906 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003907 ALOGE("Camera %s: %s: cannot find in-flight request on "
3908 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003909 resultExtras.frameNumber);
3910 }
3911 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003912 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003913 if (listener != NULL) {
3914 listener->notifyError(errorCode, resultExtras);
3915 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003916 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003917 }
3918 break;
3919 default:
3920 // SET_ERR calls notifyError
3921 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3922 break;
3923 }
3924}
3925
3926void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003927 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003928 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003929 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003930
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003931 // Set timestamp for the request in the in-flight tracking
3932 // and get the request ID to send upstream
3933 {
3934 Mutex::Autolock l(mInFlightLock);
3935 idx = mInFlightMap.indexOfKey(msg.frame_number);
3936 if (idx >= 0) {
3937 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003938
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003939 // Verify ordering of shutter notifications
3940 {
3941 Mutex::Autolock l(mOutputLock);
3942 // TODO: need to track errors for tighter bounds on expected frame number.
3943 if (r.hasInputBuffer) {
3944 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003945 SET_ERR("Reprocess shutter notification out-of-order. Expected "
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003946 "notification for frame %d, got frame %d",
3947 mNextReprocessShutterFrameNumber, msg.frame_number);
3948 return;
3949 }
3950 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003951 } else if (r.zslCapture && r.stillCapture) {
3952 if (msg.frame_number < mNextZslStillShutterFrameNumber) {
3953 SET_ERR("ZSL still capture shutter notification out-of-order. Expected "
3954 "notification for frame %d, got frame %d",
3955 mNextZslStillShutterFrameNumber, msg.frame_number);
3956 return;
3957 }
3958 mNextZslStillShutterFrameNumber = msg.frame_number + 1;
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003959 } else {
3960 if (msg.frame_number < mNextShutterFrameNumber) {
3961 SET_ERR("Shutter notification out-of-order. Expected "
3962 "notification for frame %d, got frame %d",
3963 mNextShutterFrameNumber, msg.frame_number);
3964 return;
3965 }
3966 mNextShutterFrameNumber = msg.frame_number + 1;
3967 }
3968 }
3969
Shuzhen Wang4a472662017-02-26 23:29:04 -08003970 r.shutterTimestamp = msg.timestamp;
3971 if (r.hasCallback) {
3972 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003973 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003974 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003975 // Call listener, if any
3976 if (listener != NULL) {
3977 listener->notifyShutter(r.resultExtras, msg.timestamp);
3978 }
3979 // send pending result and buffers
3980 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3981 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003982 r.hasInputBuffer, r.zslCapture && r.stillCapture,
3983 r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003984 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003985 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003986 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003987 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3988 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003989 r.pendingOutputBuffers.clear();
3990
3991 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003992 }
3993 }
3994 if (idx < 0) {
3995 SET_ERR("Shutter notification for non-existent frame number %d",
3996 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003997 }
3998}
3999
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004000CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07004001 ALOGV("%s", __FUNCTION__);
4002
Igor Murashkin1e479c02013-09-06 16:55:14 -07004003 CameraMetadata retVal;
4004
4005 if (mRequestThread != NULL) {
4006 retVal = mRequestThread->getLatestRequest();
4007 }
4008
Igor Murashkin1e479c02013-09-06 16:55:14 -07004009 return retVal;
4010}
4011
Jianing Weicb0652e2014-03-12 18:29:36 -07004012
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004013void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004014 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
4015 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
4016
4017 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
4018 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004019}
4020
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004021/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004022 * HalInterface inner class methods
4023 */
4024
Yifan Hongf79b5542017-04-11 14:44:25 -07004025Camera3Device::HalInterface::HalInterface(
4026 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004027 std::shared_ptr<RequestMetadataQueue> queue,
4028 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004029 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004030 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08004031 mUseHalBufManager(useHalBufManager),
4032 mIsReconfigurationQuerySupported(true) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004033 // Check with hardware service manager if we can downcast these interfaces
4034 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004035 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
4036 if (castResult_3_5.isOk()) {
4037 mHidlSession_3_5 = castResult_3_5;
4038 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004039 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4040 if (castResult_3_4.isOk()) {
4041 mHidlSession_3_4 = castResult_3_4;
4042 }
4043 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
4044 if (castResult_3_3.isOk()) {
4045 mHidlSession_3_3 = castResult_3_3;
4046 }
4047}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004048
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004049Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004050
4051Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004052 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004053 mRequestMetadataQueue(other.mRequestMetadataQueue),
4054 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004055
4056bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004057 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004058}
4059
4060void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00004061 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00004062 mHidlSession_3_4.clear();
4063 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004064 mHidlSession.clear();
4065}
4066
4067status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
4068 camera3_request_template_t templateId,
4069 /*out*/ camera_metadata_t **requestTemplate) {
4070 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
4071 if (!valid()) return INVALID_OPERATION;
4072 status_t res = OK;
4073
Emilian Peev31abd0a2017-05-11 18:37:46 +01004074 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004075
4076 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01004077 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004078 status = s;
4079 if (status == common::V1_0::Status::OK) {
4080 const camera_metadata *r =
4081 reinterpret_cast<const camera_metadata_t*>(request.data());
4082 size_t expectedSize = request.size();
4083 int ret = validate_camera_metadata_structure(r, &expectedSize);
4084 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
4085 *requestTemplate = clone_camera_metadata(r);
4086 if (*requestTemplate == nullptr) {
4087 ALOGE("%s: Unable to clone camera metadata received from HAL",
4088 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004089 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004090 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004091 } else {
4092 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
4093 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004094 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004095 }
4096 };
4097 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004098 RequestTemplate id;
4099 switch (templateId) {
4100 case CAMERA3_TEMPLATE_PREVIEW:
4101 id = RequestTemplate::PREVIEW;
4102 break;
4103 case CAMERA3_TEMPLATE_STILL_CAPTURE:
4104 id = RequestTemplate::STILL_CAPTURE;
4105 break;
4106 case CAMERA3_TEMPLATE_VIDEO_RECORD:
4107 id = RequestTemplate::VIDEO_RECORD;
4108 break;
4109 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
4110 id = RequestTemplate::VIDEO_SNAPSHOT;
4111 break;
4112 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
4113 id = RequestTemplate::ZERO_SHUTTER_LAG;
4114 break;
4115 case CAMERA3_TEMPLATE_MANUAL:
4116 id = RequestTemplate::MANUAL;
4117 break;
4118 default:
4119 // Unknown template ID, or this HAL is too old to support it
4120 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004121 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004122 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004123
Emilian Peev31abd0a2017-05-11 18:37:46 +01004124 if (!err.isOk()) {
4125 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4126 res = DEAD_OBJECT;
4127 } else {
4128 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004129 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004130
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004131 return res;
4132}
4133
Emilian Peev4ec17882019-01-24 17:16:58 -08004134bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4135 CameraMetadata& newSessionParams) {
4136 // We do reconfiguration by default;
4137 bool ret = true;
4138 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4139 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4140 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4141 oldSessionParams.getAndLock());
4142 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4143 newSessionParams.getAndLock());
4144 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4145 get_camera_metadata_size(oldSessioMeta));
4146 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4147 get_camera_metadata_size(newSessioMeta));
4148 hardware::camera::common::V1_0::Status callStatus;
4149 bool required;
4150 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4151 bool requiredFlag) {
4152 callStatus = s;
4153 required = requiredFlag;
4154 };
4155 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4156 oldSessionParams.unlock(oldSessioMeta);
4157 newSessionParams.unlock(newSessioMeta);
4158 if (err.isOk()) {
4159 switch (callStatus) {
4160 case hardware::camera::common::V1_0::Status::OK:
4161 ret = required;
4162 break;
4163 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4164 mIsReconfigurationQuerySupported = false;
4165 ret = true;
4166 break;
4167 default:
4168 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4169 ret = true;
4170 }
4171 } else {
4172 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4173 ret = true;
4174 }
4175 }
4176
4177 return ret;
4178}
4179
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004180status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004181 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004182 ATRACE_NAME("CameraHal::configureStreams");
4183 if (!valid()) return INVALID_OPERATION;
4184 status_t res = OK;
4185
Emilian Peev31abd0a2017-05-11 18:37:46 +01004186 // Convert stream config to HIDL
4187 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004188 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4189 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4190 requestedConfiguration3_2.streams.resize(config->num_streams);
4191 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004192 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004193 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4194 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004195 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004196
Emilian Peev31abd0a2017-05-11 18:37:46 +01004197 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4198 cam3stream->setBufferFreedListener(this);
4199 int streamId = cam3stream->getId();
4200 StreamType streamType;
4201 switch (src->stream_type) {
4202 case CAMERA3_STREAM_OUTPUT:
4203 streamType = StreamType::OUTPUT;
4204 break;
4205 case CAMERA3_STREAM_INPUT:
4206 streamType = StreamType::INPUT;
4207 break;
4208 default:
4209 ALOGE("%s: Stream %d: Unsupported stream type %d",
4210 __FUNCTION__, streamId, config->streams[i]->stream_type);
4211 return BAD_VALUE;
4212 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004213 dst3_2.id = streamId;
4214 dst3_2.streamType = streamType;
4215 dst3_2.width = src->width;
4216 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004217 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004218 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07004219 // For HidlSession version 3.5 or newer, the format and dataSpace sent
4220 // to HAL are original, not the overriden ones.
4221 if (mHidlSession_3_5 != nullptr) {
4222 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
4223 cam3stream->getOriginalFormat() : src->format);
4224 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
4225 cam3stream->getOriginalDataSpace() : src->data_space);
4226 } else {
4227 dst3_2.format = mapToPixelFormat(src->format);
4228 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4229 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004230 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004231 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004232 if (src->physical_camera_id != nullptr) {
4233 dst3_4.physicalCameraId = src->physical_camera_id;
4234 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004235
4236 activeStreams.insert(streamId);
4237 // Create Buffer ID map if necessary
4238 if (mBufferIdMaps.count(streamId) == 0) {
4239 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4240 }
4241 }
4242 // remove BufferIdMap for deleted streams
4243 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4244 int streamId = it->first;
4245 bool active = activeStreams.count(streamId) > 0;
4246 if (!active) {
4247 it = mBufferIdMaps.erase(it);
4248 } else {
4249 ++it;
4250 }
4251 }
4252
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004253 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004254 res = mapToStreamConfigurationMode(
4255 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004256 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004257 if (res != OK) {
4258 return res;
4259 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004260 requestedConfiguration3_2.operationMode = operationMode;
4261 requestedConfiguration3_4.operationMode = operationMode;
4262 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004263 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4264 get_camera_metadata_size(sessionParams));
4265
Emilian Peev31abd0a2017-05-11 18:37:46 +01004266 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004267 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004268 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004269 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004270
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004271 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004272 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4273 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004274 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004275 };
4276
4277 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4278 (hardware::Return<void>& err) -> status_t {
4279 if (!err.isOk()) {
4280 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4281 return DEAD_OBJECT;
4282 }
4283 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4284 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4285 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4286 }
4287 return OK;
4288 };
4289
Shuzhen Wang92653952019-05-07 15:11:43 -07004290 // See which version of HAL we have
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004291 if (mHidlSession_3_5 != nullptr) {
4292 ALOGV("%s: v3.5 device found", __FUNCTION__);
4293 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4294 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4295 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4296 auto err = mHidlSession_3_5->configureStreams_3_5(
4297 requestedConfiguration3_5, configStream34Cb);
4298 res = postprocConfigStream34(err);
4299 if (res != OK) {
4300 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004301 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004302 } else if (mHidlSession_3_4 != nullptr) {
4303 // We do; use v3.4 for the call
4304 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004305 auto err = mHidlSession_3_4->configureStreams_3_4(
4306 requestedConfiguration3_4, configStream34Cb);
4307 res = postprocConfigStream34(err);
4308 if (res != OK) {
4309 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004310 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004311 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004312 // We do; use v3.3 for the call
4313 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004314 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004315 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004316 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004317 finalConfiguration = halConfiguration;
4318 status = s;
4319 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004320 if (!err.isOk()) {
4321 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4322 return DEAD_OBJECT;
4323 }
4324 } else {
4325 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4326 ALOGV("%s: v3.2 device found", __FUNCTION__);
4327 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004328 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004329 [&status, &finalConfiguration_3_2]
4330 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4331 finalConfiguration_3_2 = halConfiguration;
4332 status = s;
4333 });
4334 if (!err.isOk()) {
4335 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4336 return DEAD_OBJECT;
4337 }
4338 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4339 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4340 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4341 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004342 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004343 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004344 }
4345
4346 if (status != common::V1_0::Status::OK ) {
4347 return CameraProviderManager::mapToStatusT(status);
4348 }
4349
4350 // And convert output stream configuration from HIDL
4351
4352 for (size_t i = 0; i < config->num_streams; i++) {
4353 camera3_stream_t *dst = config->streams[i];
4354 int streamId = Camera3Stream::cast(dst)->getId();
4355
4356 // Start scan at i, with the assumption that the stream order matches
4357 size_t realIdx = i;
4358 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004359 size_t halStreamCount = finalConfiguration.streams.size();
4360 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004361 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004362 found = true;
4363 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004364 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004365 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004366 }
4367 if (!found) {
4368 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4369 __FUNCTION__, streamId);
4370 return INVALID_OPERATION;
4371 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004372 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004373
Emilian Peev710c1422017-08-30 11:19:38 +01004374 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004375 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4376 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4377
Yin-Chia Yeh90667662019-07-01 15:45:00 -07004378 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07004379 dstStream->setFormatOverride(false);
4380 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004381 if (dst->format != overrideFormat) {
4382 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4383 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004384 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004385 if (dst->data_space != overrideDataSpace) {
4386 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4387 streamId, dst->format);
4388 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004389 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07004390 bool needFormatOverride =
4391 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
4392 bool needDataspaceOverride =
4393 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004394 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07004395 dstStream->setFormatOverride(needFormatOverride);
4396 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004397 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004398 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004399 }
4400
Emilian Peev31abd0a2017-05-11 18:37:46 +01004401 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004402 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004403 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004404 __FUNCTION__, streamId);
4405 return INVALID_OPERATION;
4406 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004407 dstStream->setUsage(
4408 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004409 } else {
4410 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004411 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004412 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4413 __FUNCTION__, streamId);
4414 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004415 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004416 dstStream->setUsage(
4417 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004418 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004419 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004420 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004421
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004422 return res;
4423}
4424
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004425status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004426 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004427 /*out*/std::vector<native_handle_t*>* handlesCreated,
4428 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004429 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004430 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
4431 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
4432 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004433 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004434 }
4435
4436 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004437
4438 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004439
4440 {
4441 std::lock_guard<std::mutex> lock(mInflightLock);
4442 if (request->input_buffer != nullptr) {
4443 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4444 buffer_handle_t buf = *(request->input_buffer->buffer);
4445 auto pair = getBufferId(buf, streamId);
4446 bool isNewBuffer = pair.first;
4447 uint64_t bufferId = pair.second;
4448 captureRequest->inputBuffer.streamId = streamId;
4449 captureRequest->inputBuffer.bufferId = bufferId;
4450 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4451 captureRequest->inputBuffer.status = BufferStatus::OK;
4452 native_handle_t *acquireFence = nullptr;
4453 if (request->input_buffer->acquire_fence != -1) {
4454 acquireFence = native_handle_create(1,0);
4455 acquireFence->data[0] = request->input_buffer->acquire_fence;
4456 handlesCreated->push_back(acquireFence);
4457 }
4458 captureRequest->inputBuffer.acquireFence = acquireFence;
4459 captureRequest->inputBuffer.releaseFence = nullptr;
4460
4461 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004462 request->input_buffer->buffer);
4463 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004464 } else {
4465 captureRequest->inputBuffer.streamId = -1;
4466 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4467 }
4468
4469 captureRequest->outputBuffers.resize(request->num_output_buffers);
4470 for (size_t i = 0; i < request->num_output_buffers; i++) {
4471 const camera3_stream_buffer_t *src = request->output_buffers + i;
4472 StreamBuffer &dst = captureRequest->outputBuffers[i];
4473 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004474 if (src->buffer != nullptr) {
4475 buffer_handle_t buf = *(src->buffer);
4476 auto pair = getBufferId(buf, streamId);
4477 bool isNewBuffer = pair.first;
4478 dst.bufferId = pair.second;
4479 dst.buffer = isNewBuffer ? buf : nullptr;
4480 native_handle_t *acquireFence = nullptr;
4481 if (src->acquire_fence != -1) {
4482 acquireFence = native_handle_create(1,0);
4483 acquireFence->data[0] = src->acquire_fence;
4484 handlesCreated->push_back(acquireFence);
4485 }
4486 dst.acquireFence = acquireFence;
4487 } else if (mUseHalBufManager) {
4488 // HAL buffer management path
4489 dst.bufferId = BUFFER_ID_NO_BUFFER;
4490 dst.buffer = nullptr;
4491 dst.acquireFence = nullptr;
4492 } else {
4493 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4494 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004495 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004496 dst.streamId = streamId;
4497 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004498 dst.releaseFence = nullptr;
4499
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004500 // Output buffers are empty when using HAL buffer manager
4501 if (!mUseHalBufManager) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004502 pushInflightBufferLocked(captureRequest->frameNumber, streamId, src->buffer);
4503 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004504 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004505 }
4506 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004507 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004508}
4509
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004510void Camera3Device::HalInterface::cleanupNativeHandles(
4511 std::vector<native_handle_t*> *handles, bool closeFd) {
4512 if (handles == nullptr) {
4513 return;
4514 }
4515 if (closeFd) {
4516 for (auto& handle : *handles) {
4517 native_handle_close(handle);
4518 }
4519 }
4520 for (auto& handle : *handles) {
4521 native_handle_delete(handle);
4522 }
4523 handles->clear();
4524 return;
4525}
4526
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004527status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4528 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4529 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4530 if (!valid()) return INVALID_OPERATION;
4531
Emilian Peevaebbe412018-01-15 13:53:24 +00004532 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4533 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4534 if (castResult_3_4.isOk()) {
4535 hidlSession_3_4 = castResult_3_4;
4536 }
4537
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004538 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004539 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004540 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004541 if (hidlSession_3_4 != nullptr) {
4542 captureRequests_3_4.resize(batchSize);
4543 } else {
4544 captureRequests.resize(batchSize);
4545 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004546 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004547 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004548
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004549 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004550 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004551 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004552 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004553 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00004554 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004555 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
4556 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004557 }
4558 if (res != OK) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004559 popInflightBuffers(inflightBuffers);
4560 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004561 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004562 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004563 }
4564
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004565 std::vector<device::V3_2::BufferCache> cachesToRemove;
4566 {
4567 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4568 for (auto& pair : mFreedBuffers) {
4569 // The stream might have been removed since onBufferFreed
4570 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4571 cachesToRemove.push_back({pair.first, pair.second});
4572 }
4573 }
4574 mFreedBuffers.clear();
4575 }
4576
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004577 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4578 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004579
4580 // Write metadata to FMQ.
4581 for (size_t i = 0; i < batchSize; i++) {
4582 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004583 device::V3_2::CaptureRequest* captureRequest;
4584 if (hidlSession_3_4 != nullptr) {
4585 captureRequest = &captureRequests_3_4[i].v3_2;
4586 } else {
4587 captureRequest = &captureRequests[i];
4588 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004589
4590 if (request->settings != nullptr) {
4591 size_t settingsSize = get_camera_metadata_size(request->settings);
4592 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4593 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4594 captureRequest->settings.resize(0);
4595 captureRequest->fmqSettingsSize = settingsSize;
4596 } else {
4597 if (mRequestMetadataQueue != nullptr) {
4598 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4599 }
4600 captureRequest->settings.setToExternal(
4601 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4602 get_camera_metadata_size(request->settings));
4603 captureRequest->fmqSettingsSize = 0u;
4604 }
4605 } else {
4606 // A null request settings maps to a size-0 CameraMetadata
4607 captureRequest->settings.resize(0);
4608 captureRequest->fmqSettingsSize = 0u;
4609 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004610
4611 if (hidlSession_3_4 != nullptr) {
4612 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4613 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004614 if (request->physcam_settings != nullptr) {
4615 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4616 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4617 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4618 settingsSize)) {
4619 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4620 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4621 settingsSize;
4622 } else {
4623 if (mRequestMetadataQueue != nullptr) {
4624 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4625 }
4626 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4627 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4628 request->physcam_settings[j])),
4629 get_camera_metadata_size(request->physcam_settings[j]));
4630 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004631 }
Emilian Peev00420d22018-02-05 21:33:13 +00004632 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004633 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004634 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004635 }
4636 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4637 request->physcam_id[j];
4638 }
4639 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004640 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004641
4642 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004643 auto resultCallback =
4644 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4645 status = s;
4646 *numRequestProcessed = n;
4647 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004648 if (hidlSession_3_4 != nullptr) {
4649 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004650 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004651 } else {
4652 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004653 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004654 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004655 if (!err.isOk()) {
4656 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004657 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004658 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004659
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004660 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4661 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4662 __FUNCTION__, *numRequestProcessed, batchSize);
4663 status = common::V1_0::Status::INTERNAL_ERROR;
4664 }
4665
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004666 res = CameraProviderManager::mapToStatusT(status);
4667 if (res == OK) {
4668 if (mHidlSession->isRemote()) {
4669 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
4670 // sent to camera HAL processes)
4671 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
4672 } else {
4673 // In passthrough mode the FDs are now owned by HAL
4674 cleanupNativeHandles(&handlesCreated);
4675 }
4676 } else {
4677 popInflightBuffers(inflightBuffers);
4678 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004679 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004680 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004681}
4682
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004683status_t Camera3Device::HalInterface::flush() {
4684 ATRACE_NAME("CameraHal::flush");
4685 if (!valid()) return INVALID_OPERATION;
4686 status_t res = OK;
4687
Emilian Peev31abd0a2017-05-11 18:37:46 +01004688 auto err = mHidlSession->flush();
4689 if (!err.isOk()) {
4690 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4691 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004692 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004693 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004694 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004695
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004696 return res;
4697}
4698
Emilian Peev31abd0a2017-05-11 18:37:46 +01004699status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004700 ATRACE_NAME("CameraHal::dump");
4701 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004702
Emilian Peev31abd0a2017-05-11 18:37:46 +01004703 // Handled by CameraProviderManager::dump
4704
4705 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004706}
4707
4708status_t Camera3Device::HalInterface::close() {
4709 ATRACE_NAME("CameraHal::close()");
4710 if (!valid()) return INVALID_OPERATION;
4711 status_t res = OK;
4712
Emilian Peev31abd0a2017-05-11 18:37:46 +01004713 auto err = mHidlSession->close();
4714 // Interface will be dead shortly anyway, so don't log errors
4715 if (!err.isOk()) {
4716 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004717 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004718
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004719 return res;
4720}
4721
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004722void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4723 ATRACE_NAME("CameraHal::signalPipelineDrain");
4724 if (!valid() || mHidlSession_3_5 == nullptr) {
4725 ALOGE("%s called on invalid camera!", __FUNCTION__);
4726 return;
4727 }
4728
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004729 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004730 if (!err.isOk()) {
4731 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4732 return;
4733 }
4734}
4735
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004736void Camera3Device::HalInterface::getInflightBufferKeys(
4737 std::vector<std::pair<int32_t, int32_t>>* out) {
4738 std::lock_guard<std::mutex> lock(mInflightLock);
4739 out->clear();
4740 out->reserve(mInflightBufferMap.size());
4741 for (auto& pair : mInflightBufferMap) {
4742 uint64_t key = pair.first;
4743 int32_t streamId = key & 0xFFFFFFFF;
4744 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4745 out->push_back(std::make_pair(frameNumber, streamId));
4746 }
4747 return;
4748}
4749
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004750void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4751 std::vector<uint64_t>* out) {
4752 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4753 out->clear();
4754 out->reserve(mRequestedBuffers.size());
4755 for (auto& pair : mRequestedBuffers) {
4756 out->push_back(pair.first);
4757 }
4758 return;
4759}
4760
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004761status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004762 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004763 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004764 mInflightBufferMap[key] = buffer;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004765 return OK;
4766}
4767
4768status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004769 int32_t frameNumber, int32_t streamId,
4770 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004771 std::lock_guard<std::mutex> lock(mInflightLock);
4772
4773 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4774 auto it = mInflightBufferMap.find(key);
4775 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004776 if (buffer != nullptr) {
4777 *buffer = it->second;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004778 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004779 mInflightBufferMap.erase(it);
4780 return OK;
4781}
4782
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004783void Camera3Device::HalInterface::popInflightBuffers(
4784 const std::vector<std::pair<int32_t, int32_t>>& buffers) {
4785 for (const auto& pair : buffers) {
4786 int32_t frameNumber = pair.first;
4787 int32_t streamId = pair.second;
4788 popInflightBuffer(frameNumber, streamId, nullptr);
4789 }
4790}
4791
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004792status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004793 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004794 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004795 auto pair = mRequestedBuffers.insert({bufferId, {streamId, buf}});
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004796 if (!pair.second) {
4797 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4798 __FUNCTION__, bufferId);
4799 return BAD_VALUE;
4800 }
4801 return OK;
4802}
4803
4804// Find and pop a buffer_handle_t based on bufferId
4805status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004806 uint64_t bufferId,
4807 /*out*/ buffer_handle_t** buffer,
4808 /*optional out*/ int32_t* streamId) {
4809 if (buffer == nullptr) {
4810 ALOGE("%s: buffer (%p) must not be null", __FUNCTION__, buffer);
4811 return BAD_VALUE;
4812 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004813 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4814 auto it = mRequestedBuffers.find(bufferId);
4815 if (it == mRequestedBuffers.end()) {
4816 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4817 __FUNCTION__, bufferId);
4818 return BAD_VALUE;
4819 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004820 *buffer = it->second.second;
4821 if (streamId != nullptr) {
4822 *streamId = it->second.first;
4823 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004824 mRequestedBuffers.erase(it);
4825 return OK;
4826}
4827
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004828std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4829 const buffer_handle_t& buf, int streamId) {
4830 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4831
4832 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4833 auto it = bIdMap.find(buf);
4834 if (it == bIdMap.end()) {
4835 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004836 ALOGV("stream %d now have %zu buffer caches, buf %p",
4837 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004838 return std::make_pair(true, mNextBufferId - 1);
4839 } else {
4840 return std::make_pair(false, it->second);
4841 }
4842}
4843
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004844void Camera3Device::HalInterface::onBufferFreed(
4845 int streamId, const native_handle_t* handle) {
4846 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4847 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4848 auto mapIt = mBufferIdMaps.find(streamId);
4849 if (mapIt == mBufferIdMaps.end()) {
4850 // streamId might be from a deleted stream here
4851 ALOGI("%s: stream %d has been removed",
4852 __FUNCTION__, streamId);
4853 return;
4854 }
4855 BufferIdMap& bIdMap = mapIt->second;
4856 auto it = bIdMap.find(handle);
4857 if (it == bIdMap.end()) {
4858 ALOGW("%s: cannot find buffer %p in stream %d",
4859 __FUNCTION__, handle, streamId);
4860 return;
4861 } else {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004862 bufferId = it->second;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004863 bIdMap.erase(it);
4864 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4865 __FUNCTION__, streamId, bIdMap.size(), handle);
4866 }
4867 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4868}
4869
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004870void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
4871 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4872 auto mapIt = mBufferIdMaps.find(streamId);
4873 if (mapIt == mBufferIdMaps.end()) {
4874 ALOGE("%s: streamId %d not found!", __FUNCTION__, streamId);
4875 return;
4876 }
4877
4878 BufferIdMap& bIdMap = mapIt->second;
4879 for (const auto& it : bIdMap) {
4880 uint64_t bufferId = it.second;
4881 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4882 }
4883 bIdMap.clear();
4884}
4885
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004886/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004887 * RequestThread inner class methods
4888 */
4889
4890Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004891 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004892 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4893 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004894 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004895 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004896 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004897 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004898 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004899 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004900 mReconfigured(false),
4901 mDoPause(false),
4902 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004903 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004904 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004905 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004906 mCurrentAfTriggerId(0),
4907 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004908 mRepeatingLastFrameNumber(
4909 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004910 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004911 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004912 mRequestLatency(kRequestLatencyBinSize),
4913 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004914 mLatestSessionParams(sessionParamKeys.size()),
4915 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004916 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004917}
4918
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004919Camera3Device::RequestThread::~RequestThread() {}
4920
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004921void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004922 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004923 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004924 Mutex::Autolock l(mRequestLock);
4925 mListener = listener;
4926}
4927
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004928void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4929 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004930 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004931 Mutex::Autolock l(mRequestLock);
4932 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004933 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004934 // Prepare video stream for high speed recording.
4935 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004936 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004937}
4938
Jianing Wei90e59c92014-03-12 18:29:36 -07004939status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004940 List<sp<CaptureRequest> > &requests,
4941 /*out*/
4942 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004943 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004944 Mutex::Autolock l(mRequestLock);
4945 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4946 ++it) {
4947 mRequestQueue.push_back(*it);
4948 }
4949
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004950 if (lastFrameNumber != NULL) {
4951 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4952 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4953 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4954 *lastFrameNumber);
4955 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004956
Jianing Wei90e59c92014-03-12 18:29:36 -07004957 unpauseForNewRequests();
4958
4959 return OK;
4960}
4961
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004962
4963status_t Camera3Device::RequestThread::queueTrigger(
4964 RequestTrigger trigger[],
4965 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004966 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004967 Mutex::Autolock l(mTriggerMutex);
4968 status_t ret;
4969
4970 for (size_t i = 0; i < count; ++i) {
4971 ret = queueTriggerLocked(trigger[i]);
4972
4973 if (ret != OK) {
4974 return ret;
4975 }
4976 }
4977
4978 return OK;
4979}
4980
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004981const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4982 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004983 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004984 if (d != nullptr) return d->mId;
4985 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004986}
4987
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004988status_t Camera3Device::RequestThread::queueTriggerLocked(
4989 RequestTrigger trigger) {
4990
4991 uint32_t tag = trigger.metadataTag;
4992 ssize_t index = mTriggerMap.indexOfKey(tag);
4993
4994 switch (trigger.getTagType()) {
4995 case TYPE_BYTE:
4996 // fall-through
4997 case TYPE_INT32:
4998 break;
4999 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005000 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
5001 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005002 return INVALID_OPERATION;
5003 }
5004
5005 /**
5006 * Collect only the latest trigger, since we only have 1 field
5007 * in the request settings per trigger tag, and can't send more than 1
5008 * trigger per request.
5009 */
5010 if (index != NAME_NOT_FOUND) {
5011 mTriggerMap.editValueAt(index) = trigger;
5012 } else {
5013 mTriggerMap.add(tag, trigger);
5014 }
5015
5016 return OK;
5017}
5018
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005019status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005020 const RequestList &requests,
5021 /*out*/
5022 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005023 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005024 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005025 if (lastFrameNumber != NULL) {
5026 *lastFrameNumber = mRepeatingLastFrameNumber;
5027 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005028 mRepeatingRequests.clear();
5029 mRepeatingRequests.insert(mRepeatingRequests.begin(),
5030 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005031
5032 unpauseForNewRequests();
5033
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005034 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005035 return OK;
5036}
5037
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07005038bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005039 if (mRepeatingRequests.empty()) {
5040 return false;
5041 }
5042 int32_t requestId = requestIn->mResultExtras.requestId;
5043 const RequestList &repeatRequests = mRepeatingRequests;
5044 // All repeating requests are guaranteed to have same id so only check first quest
5045 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
5046 return (firstRequest->mResultExtras.requestId == requestId);
5047}
5048
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005049status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005050 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005051 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005052 return clearRepeatingRequestsLocked(lastFrameNumber);
5053
5054}
5055
5056status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005057 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005058 if (lastFrameNumber != NULL) {
5059 *lastFrameNumber = mRepeatingLastFrameNumber;
5060 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005061 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005062 return OK;
5063}
5064
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005065status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005066 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005067 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005068 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005069 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005070
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005071 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005072
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005073 // Send errors for all requests pending in the request queue, including
5074 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005075 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005076 if (listener != NULL) {
5077 for (RequestList::iterator it = mRequestQueue.begin();
5078 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005079 // Abort the input buffers for reprocess requests.
5080 if ((*it)->mInputStream != NULL) {
5081 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07005082 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
5083 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005084 if (res != OK) {
5085 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
5086 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5087 } else {
5088 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
5089 if (res != OK) {
5090 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
5091 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5092 }
5093 }
5094 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005095 // Set the frame number this request would have had, if it
5096 // had been submitted; this frame number will not be reused.
5097 // The requestId and burstId fields were set when the request was
5098 // submitted originally (in convertMetadataListToRequestListLocked)
5099 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005100 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005101 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005102 }
5103 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005104 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08005105
5106 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005107 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005108 if (lastFrameNumber != NULL) {
5109 *lastFrameNumber = mRepeatingLastFrameNumber;
5110 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005111 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005112 return OK;
5113}
5114
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005115status_t Camera3Device::RequestThread::flush() {
5116 ATRACE_CALL();
5117 Mutex::Autolock l(mFlushLock);
5118
Emilian Peev08dd2452017-04-06 16:55:14 +01005119 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005120}
5121
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005122void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005123 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005124 Mutex::Autolock l(mPauseLock);
5125 mDoPause = paused;
5126 mDoPauseSignal.signal();
5127}
5128
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005129status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
5130 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005131 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005132 Mutex::Autolock l(mLatestRequestMutex);
5133 status_t res;
5134 while (mLatestRequestId != requestId) {
5135 nsecs_t startTime = systemTime();
5136
5137 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
5138 if (res != OK) return res;
5139
5140 timeout -= (systemTime() - startTime);
5141 }
5142
5143 return OK;
5144}
5145
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005146void Camera3Device::RequestThread::requestExit() {
5147 // Call parent to set up shutdown
5148 Thread::requestExit();
5149 // The exit from any possible waits
5150 mDoPauseSignal.signal();
5151 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07005152
5153 mRequestLatency.log("ProcessCaptureRequest latency histogram");
5154 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005155}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005156
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005157void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005158 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005159 bool surfaceAbandoned = false;
5160 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005161 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005162 {
5163 Mutex::Autolock l(mRequestLock);
5164 // Check all streams needed by repeating requests are still valid. Otherwise, stop
5165 // repeating requests.
5166 for (const auto& request : mRepeatingRequests) {
5167 for (const auto& s : request->mOutputStreams) {
5168 if (s->isAbandoned()) {
5169 surfaceAbandoned = true;
5170 clearRepeatingRequestsLocked(&lastFrameNumber);
5171 break;
5172 }
5173 }
5174 if (surfaceAbandoned) {
5175 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005176 }
5177 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005178 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005179 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005180
5181 if (listener != NULL && surfaceAbandoned) {
5182 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005183 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005184}
5185
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005186bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005187 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005188 status_t res;
5189 size_t batchSize = mNextRequests.size();
5190 std::vector<camera3_capture_request_t*> requests(batchSize);
5191 uint32_t numRequestProcessed = 0;
5192 for (size_t i = 0; i < batchSize; i++) {
5193 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07005194 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005195 }
5196
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005197 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
5198
5199 bool triggerRemoveFailed = false;
5200 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
5201 for (size_t i = 0; i < numRequestProcessed; i++) {
5202 NextRequest& nextRequest = mNextRequests.editItemAt(i);
5203 nextRequest.submitted = true;
5204
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005205 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00005206
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005207 if (!triggerRemoveFailed) {
5208 // Remove any previously queued triggers (after unlock)
5209 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5210 if (removeTriggerRes != OK) {
5211 triggerRemoveFailed = true;
5212 triggerFailedRequest = nextRequest;
5213 }
5214 }
5215 }
5216
5217 if (triggerRemoveFailed) {
5218 SET_ERR("RequestThread: Unable to remove triggers "
5219 "(capture request %d, HAL device: %s (%d)",
5220 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5221 cleanUpFailedRequests(/*sendRequestError*/ false);
5222 return false;
5223 }
5224
5225 if (res != OK) {
5226 // Should only get a failure here for malformed requests or device-level
5227 // errors, so consider all errors fatal. Bad metadata failures should
5228 // come through notify.
5229 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5230 mNextRequests[numRequestProcessed].halRequest.frame_number,
5231 strerror(-res), res);
5232 cleanUpFailedRequests(/*sendRequestError*/ false);
5233 return false;
5234 }
5235 return true;
5236}
5237
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005238nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5239 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5240 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5241 find_camera_metadata_ro_entry(request,
5242 ANDROID_CONTROL_AE_MODE,
5243 &e);
5244 if (e.count == 0) return maxExpectedDuration;
5245
5246 switch (e.data.u8[0]) {
5247 case ANDROID_CONTROL_AE_MODE_OFF:
5248 find_camera_metadata_ro_entry(request,
5249 ANDROID_SENSOR_EXPOSURE_TIME,
5250 &e);
5251 if (e.count > 0) {
5252 maxExpectedDuration = e.data.i64[0];
5253 }
5254 find_camera_metadata_ro_entry(request,
5255 ANDROID_SENSOR_FRAME_DURATION,
5256 &e);
5257 if (e.count > 0) {
5258 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5259 }
5260 break;
5261 default:
5262 find_camera_metadata_ro_entry(request,
5263 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5264 &e);
5265 if (e.count > 1) {
5266 maxExpectedDuration = 1e9 / e.data.u8[0];
5267 }
5268 break;
5269 }
5270
5271 return maxExpectedDuration;
5272}
5273
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005274bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5275 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5276 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5277 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5278 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5279 return true;
5280 }
5281
5282 return false;
5283}
5284
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005285void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
5286 // Update the latest request sent to HAL
5287 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5288 Mutex::Autolock al(mLatestRequestMutex);
5289
5290 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5291 mLatestRequest.acquire(cloned);
5292
5293 mLatestPhysicalRequest.clear();
5294 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
5295 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
5296 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
5297 CameraMetadata(cloned));
5298 }
5299
5300 sp<Camera3Device> parent = mParent.promote();
5301 if (parent != NULL) {
5302 parent->monitorMetadata(TagMonitor::REQUEST,
5303 nextRequest.halRequest.frame_number,
5304 0, mLatestRequest, mLatestPhysicalRequest);
5305 }
5306 }
5307
5308 if (nextRequest.halRequest.settings != NULL) {
5309 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5310 nextRequest.halRequest.settings);
5311 }
5312
5313 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5314}
5315
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005316bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5317 ATRACE_CALL();
5318 bool updatesDetected = false;
5319
Emilian Peev4ec17882019-01-24 17:16:58 -08005320 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005321 for (auto tag : mSessionParamKeys) {
5322 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005323 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005324
5325 if (entry.count > 0) {
5326 bool isDifferent = false;
5327 if (lastEntry.count > 0) {
5328 // Have a last value, compare to see if changed
5329 if (lastEntry.type == entry.type &&
5330 lastEntry.count == entry.count) {
5331 // Same type and count, compare values
5332 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5333 size_t entryBytes = bytesPerValue * lastEntry.count;
5334 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5335 if (cmp != 0) {
5336 isDifferent = true;
5337 }
5338 } else {
5339 // Count or type has changed
5340 isDifferent = true;
5341 }
5342 } else {
5343 // No last entry, so always consider to be different
5344 isDifferent = true;
5345 }
5346
5347 if (isDifferent) {
5348 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005349 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5350 updatesDetected = true;
5351 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005352 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005353 }
5354 } else if (lastEntry.count > 0) {
5355 // Value has been removed
5356 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005357 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005358 updatesDetected = true;
5359 }
5360 }
5361
Emilian Peev4ec17882019-01-24 17:16:58 -08005362 bool reconfigureRequired;
5363 if (updatesDetected) {
5364 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5365 updatedParams);
5366 mLatestSessionParams = updatedParams;
5367 } else {
5368 reconfigureRequired = false;
5369 }
5370
5371 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005372}
5373
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005374bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005375 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005376 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08005377 // Any function called from threadLoop() must not hold mInterfaceLock since
5378 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
5379 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005380
5381 // Handle paused state.
5382 if (waitIfPaused()) {
5383 return true;
5384 }
5385
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005386 // Wait for the next batch of requests.
5387 waitForNextRequestBatch();
5388 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005389 return true;
5390 }
5391
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005392 // Get the latest request ID, if any
5393 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005394 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005395 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005396 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005397 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005398 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005399 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5400 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005401 }
5402
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005403 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5404 // or a single request from streaming or burst. In either case the first element
5405 // should contain the latest camera settings that we need to check for any session
5406 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005407 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005408 res = OK;
5409
5410 //Input stream buffers are already acquired at this point so an input stream
5411 //will not be able to move to idle state unless we force it.
5412 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5413 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5414 if (res != OK) {
5415 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5416 cleanUpFailedRequests(/*sendRequestError*/ false);
5417 return false;
5418 }
5419 }
5420
5421 if (res == OK) {
5422 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5423 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005424 sp<Camera3Device> parent = mParent.promote();
5425 if (parent != nullptr) {
5426 parent->pauseStateNotify(true);
5427 }
5428
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005429 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5430
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005431 if (parent != nullptr) {
5432 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5433 }
5434
5435 statusTracker->markComponentActive(mStatusId);
5436 setPaused(false);
5437 }
5438
5439 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5440 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5441 if (res != OK) {
5442 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5443 cleanUpFailedRequests(/*sendRequestError*/ false);
5444 return false;
5445 }
5446 }
5447 }
5448 }
5449
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005450 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005451 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005452 if (res == TIMED_OUT) {
5453 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005454 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005455 // Check if any stream is abandoned.
5456 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005457 return true;
5458 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005459 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005460 return false;
5461 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005462
Zhijun Hecc27e112013-10-03 16:12:43 -07005463 // Inform waitUntilRequestProcessed thread of a new request ID
5464 {
5465 Mutex::Autolock al(mLatestRequestMutex);
5466
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005467 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005468 mLatestRequestSignal.signal();
5469 }
5470
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005471 // Submit a batch of requests to HAL.
5472 // Use flush lock only when submitting multilple requests in a batch.
5473 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5474 // which may take a long time to finish so synchronizing flush() and
5475 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5476 // For now, only synchronize for high speed recording and we should figure something out for
5477 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005478 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005479
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005480 if (useFlushLock) {
5481 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005482 }
5483
Zhijun Hef0645c12016-08-02 00:58:11 -07005484 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005485 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005486
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005487 sp<Camera3Device> parent = mParent.promote();
5488 if (parent != nullptr) {
5489 parent->mRequestBufferSM.onSubmittingRequest();
5490 }
5491
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005492 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005493 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07005494 submitRequestSuccess = sendRequestsBatch();
5495
Shuzhen Wang686f6442017-06-20 16:16:04 -07005496 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5497 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005498
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005499 if (useFlushLock) {
5500 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005501 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005502
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005503 // Unset as current request
5504 {
5505 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005506 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005507 }
5508
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005509 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005510}
5511
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005512status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005513 ATRACE_CALL();
5514
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005515 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005516 for (size_t i = 0; i < mNextRequests.size(); i++) {
5517 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005518 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5519 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5520 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5521
5522 // Prepare a request to HAL
5523 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5524
5525 // Insert any queued triggers (before metadata is locked)
5526 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005527 if (res < 0) {
5528 SET_ERR("RequestThread: Unable to insert triggers "
5529 "(capture request %d, HAL device: %s (%d)",
5530 halRequest->frame_number, strerror(-res), res);
5531 return INVALID_OPERATION;
5532 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005533
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005534 int triggerCount = res;
5535 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5536 mPrevTriggers = triggerCount;
5537
5538 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005539 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5540 // Request settings are all the same within one batch, so only treat the first
5541 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005542 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005543 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005544 /**
5545 * HAL workaround:
5546 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5547 */
5548 res = addDummyTriggerIds(captureRequest);
5549 if (res != OK) {
5550 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5551 "(capture request %d, HAL device: %s (%d)",
5552 halRequest->frame_number, strerror(-res), res);
5553 return INVALID_OPERATION;
5554 }
5555
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005556 {
5557 // Correct metadata regions for distortion correction if enabled
5558 sp<Camera3Device> parent = mParent.promote();
5559 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07005560 List<PhysicalCameraSettings>::iterator it;
5561 for (it = captureRequest->mSettingsList.begin();
5562 it != captureRequest->mSettingsList.end(); it++) {
5563 if (parent->mDistortionMappers.find(it->cameraId) ==
5564 parent->mDistortionMappers.end()) {
5565 continue;
5566 }
5567 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
5568 &(it->metadata));
5569 if (res != OK) {
5570 SET_ERR("RequestThread: Unable to correct capture requests "
5571 "for lens distortion for request %d: %s (%d)",
5572 halRequest->frame_number, strerror(-res), res);
5573 return INVALID_OPERATION;
5574 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005575 }
5576 }
5577 }
5578
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005579 /**
5580 * The request should be presorted so accesses in HAL
5581 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5582 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005583 captureRequest->mSettingsList.begin()->metadata.sort();
5584 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005585 mPrevRequest = captureRequest;
5586 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5587
5588 IF_ALOGV() {
5589 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5590 find_camera_metadata_ro_entry(
5591 halRequest->settings,
5592 ANDROID_CONTROL_AF_TRIGGER,
5593 &e
5594 );
5595 if (e.count > 0) {
5596 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5597 __FUNCTION__,
5598 halRequest->frame_number,
5599 e.data.u8[0]);
5600 }
5601 }
5602 } else {
5603 // leave request.settings NULL to indicate 'reuse latest given'
5604 ALOGVV("%s: Request settings are REUSED",
5605 __FUNCTION__);
5606 }
5607
Emilian Peevaebbe412018-01-15 13:53:24 +00005608 if (captureRequest->mSettingsList.size() > 1) {
5609 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5610 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005611 if (newRequest) {
5612 halRequest->physcam_settings =
5613 new const camera_metadata* [halRequest->num_physcam_settings];
5614 } else {
5615 halRequest->physcam_settings = nullptr;
5616 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005617 auto it = ++captureRequest->mSettingsList.begin();
5618 size_t i = 0;
5619 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5620 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005621 if (newRequest) {
5622 it->metadata.sort();
5623 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5624 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005625 }
5626 }
5627
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005628 uint32_t totalNumBuffers = 0;
5629
5630 // Fill in buffers
5631 if (captureRequest->mInputStream != NULL) {
5632 halRequest->input_buffer = &captureRequest->mInputBuffer;
5633 totalNumBuffers += 1;
5634 } else {
5635 halRequest->input_buffer = NULL;
5636 }
5637
5638 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5639 captureRequest->mOutputStreams.size());
5640 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005641 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005642
5643 sp<Camera3Device> parent = mParent.promote();
5644 if (parent == NULL) {
5645 // Should not happen, and nowhere to send errors to, so just log it
5646 CLOGE("RequestThread: Parent is gone");
5647 return INVALID_OPERATION;
5648 }
5649 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5650
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005651 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005652 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005653 sp<Camera3OutputStreamInterface> outputStream =
5654 captureRequest->mOutputStreams.editItemAt(j);
5655 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005656
5657 // Prepare video buffers for high speed recording on the first video request.
5658 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5659 // Only try to prepare video stream on the first video request.
5660 mPrepareVideoStream = false;
5661
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005662 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5663 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005664 while (res == NOT_ENOUGH_DATA) {
5665 res = outputStream->prepareNextBuffer();
5666 }
5667 if (res != OK) {
5668 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5669 __FUNCTION__, strerror(-res), res);
5670 outputStream->cancelPrepare();
5671 }
5672 }
5673
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005674 std::vector<size_t> uniqueSurfaceIds;
5675 res = outputStream->getUniqueSurfaceIds(
5676 captureRequest->mOutputSurfaces[streamId],
5677 &uniqueSurfaceIds);
5678 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5679 if (res != OK && res != INVALID_OPERATION) {
5680 ALOGE("%s: failed to query stream %d unique surface IDs",
5681 __FUNCTION__, streamId);
5682 return res;
5683 }
5684 if (res == OK) {
5685 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5686 }
5687
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005688 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005689 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005690 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005691 return TIMED_OUT;
5692 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005693 // HAL will request buffer through requestStreamBuffer API
5694 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5695 buffer.stream = outputStream->asHalStream();
5696 buffer.buffer = nullptr;
5697 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5698 buffer.acquire_fence = -1;
5699 buffer.release_fence = -1;
5700 } else {
5701 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5702 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005703 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005704 if (res != OK) {
5705 // Can't get output buffer from gralloc queue - this could be due to
5706 // abandoned queue or other consumer misbehavior, so not a fatal
5707 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005708 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005709 " %s (%d)", strerror(-res), res);
5710
5711 return TIMED_OUT;
5712 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005713 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005714
5715 {
5716 sp<Camera3Device> parent = mParent.promote();
5717 if (parent != nullptr) {
5718 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5719 for (const auto& settings : captureRequest->mSettingsList) {
5720 if ((streamCameraId.isEmpty() &&
5721 parent->getId() == settings.cameraId.c_str()) ||
5722 streamCameraId == settings.cameraId.c_str()) {
5723 outputStream->fireBufferRequestForFrameNumber(
5724 captureRequest->mResultExtras.frameNumber,
5725 settings.metadata);
5726 }
5727 }
5728 }
5729 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005730
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005731 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5732
5733 if (!physicalCameraId.isEmpty()) {
5734 // Physical stream isn't supported for input request.
5735 if (halRequest->input_buffer) {
5736 CLOGE("Physical stream is not supported for input request");
5737 return INVALID_OPERATION;
5738 }
5739 requestedPhysicalCameras.insert(physicalCameraId);
5740 }
5741 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005742 }
5743 totalNumBuffers += halRequest->num_output_buffers;
5744
5745 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005746 // If this request list is for constrained high speed recording (not
5747 // preview), and the current request is not the last one in the batch,
5748 // do not send callback to the app.
5749 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005750 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005751 hasCallback = false;
5752 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005753 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005754 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005755 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5756 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5757 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5758 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5759 isStillCapture = true;
5760 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5761 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005762
5763 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5764 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5765 isZslCapture = true;
5766 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005767 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005768 res = parent->registerInFlight(halRequest->frame_number,
5769 totalNumBuffers, captureRequest->mResultExtras,
5770 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005771 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005772 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005773 requestedPhysicalCameras, isStillCapture, isZslCapture,
5774 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5775 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005776 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5777 ", burstId = %" PRId32 ".",
5778 __FUNCTION__,
5779 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5780 captureRequest->mResultExtras.burstId);
5781 if (res != OK) {
5782 SET_ERR("RequestThread: Unable to register new in-flight request:"
5783 " %s (%d)", strerror(-res), res);
5784 return INVALID_OPERATION;
5785 }
5786 }
5787
5788 return OK;
5789}
5790
Igor Murashkin1e479c02013-09-06 16:55:14 -07005791CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005792 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005793 Mutex::Autolock al(mLatestRequestMutex);
5794
5795 ALOGV("RequestThread::%s", __FUNCTION__);
5796
5797 return mLatestRequest;
5798}
5799
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005800bool Camera3Device::RequestThread::isStreamPending(
5801 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005802 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005803 Mutex::Autolock l(mRequestLock);
5804
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005805 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005806 if (!nextRequest.submitted) {
5807 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5808 if (stream == s) return true;
5809 }
5810 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005811 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005812 }
5813
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005814 for (const auto& request : mRequestQueue) {
5815 for (const auto& s : request->mOutputStreams) {
5816 if (stream == s) return true;
5817 }
5818 if (stream == request->mInputStream) return true;
5819 }
5820
5821 for (const auto& request : mRepeatingRequests) {
5822 for (const auto& s : request->mOutputStreams) {
5823 if (stream == s) return true;
5824 }
5825 if (stream == request->mInputStream) return true;
5826 }
5827
5828 return false;
5829}
Jianing Weicb0652e2014-03-12 18:29:36 -07005830
Emilian Peev40ead602017-09-26 15:46:36 +01005831bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5832 ATRACE_CALL();
5833 Mutex::Autolock l(mRequestLock);
5834
5835 for (const auto& nextRequest : mNextRequests) {
5836 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5837 if (s.first == streamId) {
5838 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5839 if (it != s.second.end()) {
5840 return true;
5841 }
5842 }
5843 }
5844 }
5845
5846 for (const auto& request : mRequestQueue) {
5847 for (const auto& s : request->mOutputSurfaces) {
5848 if (s.first == streamId) {
5849 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5850 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005851 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005852 }
5853 }
5854 }
5855 }
5856
5857 for (const auto& request : mRepeatingRequests) {
5858 for (const auto& s : request->mOutputSurfaces) {
5859 if (s.first == streamId) {
5860 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5861 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005862 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005863 }
5864 }
5865 }
5866 }
5867
5868 return false;
5869}
5870
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005871void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5872 if (!mUseHalBufManager) {
5873 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5874 return;
5875 }
5876
5877 Mutex::Autolock pl(mPauseLock);
5878 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005879 mInterface->signalPipelineDrain(streamIds);
5880 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005881 }
5882 // If request thread is still busy, wait until paused then notify HAL
5883 mNotifyPipelineDrain = true;
5884 mStreamIdsToBeDrained = streamIds;
5885}
5886
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005887nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005888 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005889 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005890 return mExpectedInflightDuration > kMinInflightDuration ?
5891 mExpectedInflightDuration : kMinInflightDuration;
5892}
5893
Emilian Peevaebbe412018-01-15 13:53:24 +00005894void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5895 camera3_capture_request_t *halRequest) {
5896 if ((request == nullptr) || (halRequest == nullptr)) {
5897 ALOGE("%s: Invalid request!", __FUNCTION__);
5898 return;
5899 }
5900
5901 if (halRequest->num_physcam_settings > 0) {
5902 if (halRequest->physcam_id != nullptr) {
5903 delete [] halRequest->physcam_id;
5904 halRequest->physcam_id = nullptr;
5905 }
5906 if (halRequest->physcam_settings != nullptr) {
5907 auto it = ++(request->mSettingsList.begin());
5908 size_t i = 0;
5909 for (; it != request->mSettingsList.end(); it++, i++) {
5910 it->metadata.unlock(halRequest->physcam_settings[i]);
5911 }
5912 delete [] halRequest->physcam_settings;
5913 halRequest->physcam_settings = nullptr;
5914 }
5915 }
5916}
5917
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005918void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5919 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005920 return;
5921 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005922
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005923 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005924 // Skip the ones that have been submitted successfully.
5925 if (nextRequest.submitted) {
5926 continue;
5927 }
5928
5929 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5930 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5931 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5932
5933 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005934 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005935 }
5936
Emilian Peevaebbe412018-01-15 13:53:24 +00005937 cleanupPhysicalSettings(captureRequest, halRequest);
5938
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005939 if (captureRequest->mInputStream != NULL) {
5940 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5941 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5942 }
5943
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005944 // No output buffer can be returned when using HAL buffer manager
5945 if (!mUseHalBufManager) {
5946 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5947 //Buffers that failed processing could still have
5948 //valid acquire fence.
5949 int acquireFence = (*outputBuffers)[i].acquire_fence;
5950 if (0 <= acquireFence) {
5951 close(acquireFence);
5952 outputBuffers->editItemAt(i).acquire_fence = -1;
5953 }
5954 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5955 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5956 /*timestampIncreasing*/true, std::vector<size_t> (),
5957 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005958 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005959 }
5960
5961 if (sendRequestError) {
5962 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005963 sp<NotificationListener> listener = mListener.promote();
5964 if (listener != NULL) {
5965 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005966 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005967 captureRequest->mResultExtras);
5968 }
5969 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005970
5971 // Remove yet-to-be submitted inflight request from inflightMap
5972 {
5973 sp<Camera3Device> parent = mParent.promote();
5974 if (parent != NULL) {
5975 Mutex::Autolock l(parent->mInFlightLock);
5976 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5977 if (idx >= 0) {
5978 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5979 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5980 parent->removeInFlightMapEntryLocked(idx);
5981 }
5982 }
5983 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005984 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005985
5986 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005987 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005988}
5989
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005990void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005991 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005992 // Optimized a bit for the simple steady-state case (single repeating
5993 // request), to avoid putting that request in the queue temporarily.
5994 Mutex::Autolock l(mRequestLock);
5995
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005996 assert(mNextRequests.empty());
5997
5998 NextRequest nextRequest;
5999 nextRequest.captureRequest = waitForNextRequestLocked();
6000 if (nextRequest.captureRequest == nullptr) {
6001 return;
6002 }
6003
6004 nextRequest.halRequest = camera3_capture_request_t();
6005 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006006 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006007
6008 // Wait for additional requests
6009 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
6010
6011 for (size_t i = 1; i < batchSize; i++) {
6012 NextRequest additionalRequest;
6013 additionalRequest.captureRequest = waitForNextRequestLocked();
6014 if (additionalRequest.captureRequest == nullptr) {
6015 break;
6016 }
6017
6018 additionalRequest.halRequest = camera3_capture_request_t();
6019 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006020 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006021 }
6022
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006023 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006024 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006025 mNextRequests.size(), batchSize);
6026 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006027 }
6028
6029 return;
6030}
6031
6032sp<Camera3Device::CaptureRequest>
6033 Camera3Device::RequestThread::waitForNextRequestLocked() {
6034 status_t res;
6035 sp<CaptureRequest> nextRequest;
6036
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006037 while (mRequestQueue.empty()) {
6038 if (!mRepeatingRequests.empty()) {
6039 // Always atomically enqueue all requests in a repeating request
6040 // list. Guarantees a complete in-sequence set of captures to
6041 // application.
6042 const RequestList &requests = mRepeatingRequests;
6043 RequestList::const_iterator firstRequest =
6044 requests.begin();
6045 nextRequest = *firstRequest;
6046 mRequestQueue.insert(mRequestQueue.end(),
6047 ++firstRequest,
6048 requests.end());
6049 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07006050
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006051 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07006052
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006053 break;
6054 }
6055
6056 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
6057
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006058 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
6059 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006060 Mutex::Autolock pl(mPauseLock);
6061 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006062 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006063 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006064 if (mNotifyPipelineDrain) {
6065 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6066 mNotifyPipelineDrain = false;
6067 mStreamIdsToBeDrained.clear();
6068 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006069 // Let the tracker know
6070 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6071 if (statusTracker != 0) {
6072 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6073 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006074 sp<Camera3Device> parent = mParent.promote();
6075 if (parent != nullptr) {
6076 parent->mRequestBufferSM.onRequestThreadPaused();
6077 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006078 }
6079 // Stop waiting for now and let thread management happen
6080 return NULL;
6081 }
6082 }
6083
6084 if (nextRequest == NULL) {
6085 // Don't have a repeating request already in hand, so queue
6086 // must have an entry now.
6087 RequestList::iterator firstRequest =
6088 mRequestQueue.begin();
6089 nextRequest = *firstRequest;
6090 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07006091 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
6092 sp<NotificationListener> listener = mListener.promote();
6093 if (listener != NULL) {
6094 listener->notifyRequestQueueEmpty();
6095 }
6096 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006097 }
6098
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006099 // In case we've been unpaused by setPaused clearing mDoPause, need to
6100 // update internal pause state (capture/setRepeatingRequest unpause
6101 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006102 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006103 if (mPaused) {
6104 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
6105 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6106 if (statusTracker != 0) {
6107 statusTracker->markComponentActive(mStatusId);
6108 }
6109 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006110 mPaused = false;
6111
6112 // Check if we've reconfigured since last time, and reset the preview
6113 // request if so. Can't use 'NULL request == repeat' across configure calls.
6114 if (mReconfigured) {
6115 mPrevRequest.clear();
6116 mReconfigured = false;
6117 }
6118
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006119 if (nextRequest != NULL) {
6120 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006121 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
6122 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006123
6124 // Since RequestThread::clear() removes buffers from the input stream,
6125 // get the right buffer here before unlocking mRequestLock
6126 if (nextRequest->mInputStream != NULL) {
6127 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
6128 if (res != OK) {
6129 // Can't get input buffer from gralloc queue - this could be due to
6130 // disconnected queue or other producer misbehavior, so not a fatal
6131 // error
6132 ALOGE("%s: Can't get input buffer, skipping request:"
6133 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006134
6135 sp<NotificationListener> listener = mListener.promote();
6136 if (listener != NULL) {
6137 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006138 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006139 nextRequest->mResultExtras);
6140 }
6141 return NULL;
6142 }
6143 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006144 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07006145
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006146 return nextRequest;
6147}
6148
6149bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006150 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006151 status_t res;
6152 Mutex::Autolock l(mPauseLock);
6153 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006154 if (mPaused == false) {
6155 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006156 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006157 if (mNotifyPipelineDrain) {
6158 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6159 mNotifyPipelineDrain = false;
6160 mStreamIdsToBeDrained.clear();
6161 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006162 // Let the tracker know
6163 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6164 if (statusTracker != 0) {
6165 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6166 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006167 sp<Camera3Device> parent = mParent.promote();
6168 if (parent != nullptr) {
6169 parent->mRequestBufferSM.onRequestThreadPaused();
6170 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006171 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006172
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006173 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006174 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006175 return true;
6176 }
6177 }
6178 // We don't set mPaused to false here, because waitForNextRequest needs
6179 // to further manage the paused state in case of starvation.
6180 return false;
6181}
6182
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006183void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006184 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006185 // With work to do, mark thread as unpaused.
6186 // If paused by request (setPaused), don't resume, to avoid
6187 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006188 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006189 Mutex::Autolock p(mPauseLock);
6190 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006191 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6192 if (mPaused) {
6193 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6194 if (statusTracker != 0) {
6195 statusTracker->markComponentActive(mStatusId);
6196 }
6197 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006198 mPaused = false;
6199 }
6200}
6201
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006202void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6203 sp<Camera3Device> parent = mParent.promote();
6204 if (parent != NULL) {
6205 va_list args;
6206 va_start(args, fmt);
6207
6208 parent->setErrorStateV(fmt, args);
6209
6210 va_end(args);
6211 }
6212}
6213
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006214status_t Camera3Device::RequestThread::insertTriggers(
6215 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006216 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006217 Mutex::Autolock al(mTriggerMutex);
6218
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006219 sp<Camera3Device> parent = mParent.promote();
6220 if (parent == NULL) {
6221 CLOGE("RequestThread: Parent is gone");
6222 return DEAD_OBJECT;
6223 }
6224
Emilian Peevaebbe412018-01-15 13:53:24 +00006225 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006226 size_t count = mTriggerMap.size();
6227
6228 for (size_t i = 0; i < count; ++i) {
6229 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006230 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006231
6232 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6233 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6234 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006235 if (isAeTrigger) {
6236 request->mResultExtras.precaptureTriggerId = triggerId;
6237 mCurrentPreCaptureTriggerId = triggerId;
6238 } else {
6239 request->mResultExtras.afTriggerId = triggerId;
6240 mCurrentAfTriggerId = triggerId;
6241 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006242 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006243 }
6244
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006245 camera_metadata_entry entry = metadata.find(tag);
6246
6247 if (entry.count > 0) {
6248 /**
6249 * Already has an entry for this trigger in the request.
6250 * Rewrite it with our requested trigger value.
6251 */
6252 RequestTrigger oldTrigger = trigger;
6253
6254 oldTrigger.entryValue = entry.data.u8[0];
6255
6256 mTriggerReplacedMap.add(tag, oldTrigger);
6257 } else {
6258 /**
6259 * More typical, no trigger entry, so we just add it
6260 */
6261 mTriggerRemovedMap.add(tag, trigger);
6262 }
6263
6264 status_t res;
6265
6266 switch (trigger.getTagType()) {
6267 case TYPE_BYTE: {
6268 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6269 res = metadata.update(tag,
6270 &entryValue,
6271 /*count*/1);
6272 break;
6273 }
6274 case TYPE_INT32:
6275 res = metadata.update(tag,
6276 &trigger.entryValue,
6277 /*count*/1);
6278 break;
6279 default:
6280 ALOGE("%s: Type not supported: 0x%x",
6281 __FUNCTION__,
6282 trigger.getTagType());
6283 return INVALID_OPERATION;
6284 }
6285
6286 if (res != OK) {
6287 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6288 ", value %d", __FUNCTION__, trigger.getTagName(),
6289 trigger.entryValue);
6290 return res;
6291 }
6292
6293 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6294 trigger.getTagName(),
6295 trigger.entryValue);
6296 }
6297
6298 mTriggerMap.clear();
6299
6300 return count;
6301}
6302
6303status_t Camera3Device::RequestThread::removeTriggers(
6304 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006305 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006306 Mutex::Autolock al(mTriggerMutex);
6307
Emilian Peevaebbe412018-01-15 13:53:24 +00006308 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006309
6310 /**
6311 * Replace all old entries with their old values.
6312 */
6313 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6314 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6315
6316 status_t res;
6317
6318 uint32_t tag = trigger.metadataTag;
6319 switch (trigger.getTagType()) {
6320 case TYPE_BYTE: {
6321 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6322 res = metadata.update(tag,
6323 &entryValue,
6324 /*count*/1);
6325 break;
6326 }
6327 case TYPE_INT32:
6328 res = metadata.update(tag,
6329 &trigger.entryValue,
6330 /*count*/1);
6331 break;
6332 default:
6333 ALOGE("%s: Type not supported: 0x%x",
6334 __FUNCTION__,
6335 trigger.getTagType());
6336 return INVALID_OPERATION;
6337 }
6338
6339 if (res != OK) {
6340 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6341 ", trigger value %d", __FUNCTION__,
6342 trigger.getTagName(), trigger.entryValue);
6343 return res;
6344 }
6345 }
6346 mTriggerReplacedMap.clear();
6347
6348 /**
6349 * Remove all new entries.
6350 */
6351 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6352 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6353 status_t res = metadata.erase(trigger.metadataTag);
6354
6355 if (res != OK) {
6356 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6357 ", trigger value %d", __FUNCTION__,
6358 trigger.getTagName(), trigger.entryValue);
6359 return res;
6360 }
6361 }
6362 mTriggerRemovedMap.clear();
6363
6364 return OK;
6365}
6366
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006367status_t Camera3Device::RequestThread::addDummyTriggerIds(
6368 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006369 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006370 static const int32_t dummyTriggerId = 1;
6371 status_t res;
6372
Emilian Peevaebbe412018-01-15 13:53:24 +00006373 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006374
6375 // If AF trigger is active, insert a dummy AF trigger ID if none already
6376 // exists
6377 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6378 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6379 if (afTrigger.count > 0 &&
6380 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6381 afId.count == 0) {
6382 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6383 if (res != OK) return res;
6384 }
6385
6386 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6387 // if none already exists
6388 camera_metadata_entry pcTrigger =
6389 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6390 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6391 if (pcTrigger.count > 0 &&
6392 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6393 pcId.count == 0) {
6394 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6395 &dummyTriggerId, 1);
6396 if (res != OK) return res;
6397 }
6398
6399 return OK;
6400}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006401
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006402/**
6403 * PreparerThread inner class methods
6404 */
6405
6406Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006407 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006408 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006409}
6410
6411Camera3Device::PreparerThread::~PreparerThread() {
6412 Thread::requestExitAndWait();
6413 if (mCurrentStream != nullptr) {
6414 mCurrentStream->cancelPrepare();
6415 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6416 mCurrentStream.clear();
6417 }
6418 clear();
6419}
6420
Ruben Brunkc78ac262015-08-13 17:58:46 -07006421status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006422 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006423 status_t res;
6424
6425 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006426 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006427
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006428 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006429 if (res == OK) {
6430 // No preparation needed, fire listener right off
6431 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006432 if (listener != NULL) {
6433 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006434 }
6435 return OK;
6436 } else if (res != NOT_ENOUGH_DATA) {
6437 return res;
6438 }
6439
6440 // Need to prepare, start up thread if necessary
6441 if (!mActive) {
6442 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6443 // isn't running
6444 Thread::requestExitAndWait();
6445 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6446 if (res != OK) {
6447 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006448 if (listener != NULL) {
6449 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006450 }
6451 return res;
6452 }
6453 mCancelNow = false;
6454 mActive = true;
6455 ALOGV("%s: Preparer stream started", __FUNCTION__);
6456 }
6457
6458 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006459 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006460 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6461
6462 return OK;
6463}
6464
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006465void Camera3Device::PreparerThread::pause() {
6466 ATRACE_CALL();
6467
6468 Mutex::Autolock l(mLock);
6469
6470 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6471 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6472 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6473 int currentMaxCount = mCurrentMaxCount;
6474 mPendingStreams.clear();
6475 mCancelNow = true;
6476 while (mActive) {
6477 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6478 if (res == TIMED_OUT) {
6479 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6480 return;
6481 } else if (res != OK) {
6482 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6483 return;
6484 }
6485 }
6486
6487 //Check whether the prepare thread was able to complete the current
6488 //stream. In case work is still pending emplace it along with the rest
6489 //of the streams in the pending list.
6490 if (currentStream != nullptr) {
6491 if (!mCurrentPrepareComplete) {
6492 pendingStreams.emplace(currentMaxCount, currentStream);
6493 }
6494 }
6495
6496 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6497 for (const auto& it : mPendingStreams) {
6498 it.second->cancelPrepare();
6499 }
6500}
6501
6502status_t Camera3Device::PreparerThread::resume() {
6503 ATRACE_CALL();
6504 status_t res;
6505
6506 Mutex::Autolock l(mLock);
6507 sp<NotificationListener> listener = mListener.promote();
6508
6509 if (mActive) {
6510 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6511 return NO_INIT;
6512 }
6513
6514 auto it = mPendingStreams.begin();
6515 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006516 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006517 if (res == OK) {
6518 if (listener != NULL) {
6519 listener->notifyPrepared(it->second->getId());
6520 }
6521 it = mPendingStreams.erase(it);
6522 } else if (res != NOT_ENOUGH_DATA) {
6523 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6524 res, strerror(-res));
6525 it = mPendingStreams.erase(it);
6526 } else {
6527 it++;
6528 }
6529 }
6530
6531 if (mPendingStreams.empty()) {
6532 return OK;
6533 }
6534
6535 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6536 if (res != OK) {
6537 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6538 __FUNCTION__, res, strerror(-res));
6539 return res;
6540 }
6541 mCancelNow = false;
6542 mActive = true;
6543 ALOGV("%s: Preparer stream started", __FUNCTION__);
6544
6545 return OK;
6546}
6547
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006548status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006549 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006550 Mutex::Autolock l(mLock);
6551
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006552 for (const auto& it : mPendingStreams) {
6553 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006554 }
6555 mPendingStreams.clear();
6556 mCancelNow = true;
6557
6558 return OK;
6559}
6560
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006561void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006562 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006563 Mutex::Autolock l(mLock);
6564 mListener = listener;
6565}
6566
6567bool Camera3Device::PreparerThread::threadLoop() {
6568 status_t res;
6569 {
6570 Mutex::Autolock l(mLock);
6571 if (mCurrentStream == nullptr) {
6572 // End thread if done with work
6573 if (mPendingStreams.empty()) {
6574 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6575 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6576 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6577 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006578 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006579 return false;
6580 }
6581
6582 // Get next stream to prepare
6583 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006584 mCurrentStream = it->second;
6585 mCurrentMaxCount = it->first;
6586 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006587 mPendingStreams.erase(it);
6588 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6589 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6590 } else if (mCancelNow) {
6591 mCurrentStream->cancelPrepare();
6592 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6593 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6594 mCurrentStream.clear();
6595 mCancelNow = false;
6596 return true;
6597 }
6598 }
6599
6600 res = mCurrentStream->prepareNextBuffer();
6601 if (res == NOT_ENOUGH_DATA) return true;
6602 if (res != OK) {
6603 // Something bad happened; try to recover by cancelling prepare and
6604 // signalling listener anyway
6605 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6606 mCurrentStream->getId(), res, strerror(-res));
6607 mCurrentStream->cancelPrepare();
6608 }
6609
6610 // This stream has finished, notify listener
6611 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006612 sp<NotificationListener> listener = mListener.promote();
6613 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006614 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6615 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006616 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006617 }
6618
6619 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6620 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006621 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006622
6623 return true;
6624}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006625
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006626status_t Camera3Device::RequestBufferStateMachine::initialize(
6627 sp<camera3::StatusTracker> statusTracker) {
6628 if (statusTracker == nullptr) {
6629 ALOGE("%s: statusTracker is null", __FUNCTION__);
6630 return BAD_VALUE;
6631 }
6632
6633 std::lock_guard<std::mutex> lock(mLock);
6634 mStatusTracker = statusTracker;
6635 mRequestBufferStatusId = statusTracker->addComponent();
6636 return OK;
6637}
6638
6639bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6640 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006641 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006642 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006643 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006644 return true;
6645 }
6646 return false;
6647}
6648
6649void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6650 std::lock_guard<std::mutex> lock(mLock);
6651 if (!mRequestBufferOngoing) {
6652 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6653 return;
6654 }
6655 mRequestBufferOngoing = false;
6656 if (mStatus == RB_STATUS_PENDING_STOP) {
6657 checkSwitchToStopLocked();
6658 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006659 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006660}
6661
6662void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6663 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006664 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006665 return;
6666}
6667
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006668void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006669 std::lock_guard<std::mutex> lock(mLock);
6670 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006671 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6672 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006673 mInflightMapEmpty = false;
6674 if (mStatus == RB_STATUS_STOPPED) {
6675 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006676 }
6677 return;
6678}
6679
6680void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6681 std::lock_guard<std::mutex> lock(mLock);
6682 mRequestThreadPaused = true;
6683 if (mStatus == RB_STATUS_PENDING_STOP) {
6684 checkSwitchToStopLocked();
6685 }
6686 return;
6687}
6688
6689void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6690 std::lock_guard<std::mutex> lock(mLock);
6691 mInflightMapEmpty = true;
6692 if (mStatus == RB_STATUS_PENDING_STOP) {
6693 checkSwitchToStopLocked();
6694 }
6695 return;
6696}
6697
6698void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6699 std::lock_guard<std::mutex> lock(mLock);
6700 if (!checkSwitchToStopLocked()) {
6701 mStatus = RB_STATUS_PENDING_STOP;
6702 }
6703 return;
6704}
6705
6706void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6707 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6708 if (statusTracker != nullptr) {
6709 if (active) {
6710 statusTracker->markComponentActive(mRequestBufferStatusId);
6711 } else {
6712 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6713 }
6714 }
6715}
6716
6717bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6718 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6719 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006720 return true;
6721 }
6722 return false;
6723}
6724
Shuzhen Wang268a1362018-10-16 16:32:59 -07006725status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6726 CameraMetadata& resultMetadata) {
6727 status_t res = OK;
6728 if (!mNeedFixupMonochromeTags) {
6729 return res;
6730 }
6731
6732 // Remove tags that are not applicable to monochrome camera.
6733 int32_t tagsToRemove[] = {
6734 ANDROID_SENSOR_GREEN_SPLIT,
6735 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6736 ANDROID_COLOR_CORRECTION_MODE,
6737 ANDROID_COLOR_CORRECTION_TRANSFORM,
6738 ANDROID_COLOR_CORRECTION_GAINS,
6739 };
6740 for (auto tag : tagsToRemove) {
6741 res = resultMetadata.erase(tag);
6742 if (res != OK) {
6743 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6744 return res;
6745 }
6746 }
6747
6748 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6749 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6750 for (size_t i = 1; i < blEntry.count; i++) {
6751 blEntry.data.f[i] = blEntry.data.f[0];
6752 }
6753
6754 // ANDROID_SENSOR_NOISE_PROFILE
6755 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6756 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6757 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6758 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6759 if (res != OK) {
6760 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6761 __FUNCTION__, strerror(-res), res);
6762 return res;
6763 }
6764 }
6765
6766 // ANDROID_STATISTICS_LENS_SHADING_MAP
6767 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6768 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6769 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6770 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6771 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6772 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6773 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6774 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6775 }
6776 }
6777
6778 // ANDROID_TONEMAP_CURVE_BLUE
6779 // ANDROID_TONEMAP_CURVE_GREEN
6780 // ANDROID_TONEMAP_CURVE_RED
6781 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6782 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6783 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6784 if (tcbEntry.count > 0
6785 && tcbEntry.count == tcgEntry.count
6786 && tcbEntry.count == tcrEntry.count) {
6787 for (size_t i = 0; i < tcbEntry.count; i++) {
6788 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6789 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6790 }
6791 }
6792
6793 return res;
6794}
6795
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006796}; // namespace android