blob: 833f62d28babc8de96512686b2567f20da77ed74 [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 Yehfe70f2d2020-07-28 00:17:58 -07002229 bool signalPipelineDrain = false;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002230 if (!active && mUseHalBufManager) {
2231 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08002232 if (mStatus == STATUS_ACTIVE) {
2233 mRequestThread->signalPipelineDrain(streamIds);
Yin-Chia Yehfe70f2d2020-07-28 00:17:58 -07002234 signalPipelineDrain = true;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08002235 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002236 mRequestBufferSM.onWaitUntilIdle();
2237 }
2238
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002239 bool stateSeen = false;
2240 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002241 if (active == (mStatus == STATUS_ACTIVE)) {
2242 // Desired state is current
2243 break;
2244 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002245
2246 res = mStatusChanged.waitRelative(mLock, timeout);
2247 if (res != OK) break;
2248
Ruben Brunk183f0562015-08-12 12:55:02 -07002249 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2250 // transitions.
2251 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2252 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2253 __FUNCTION__);
2254
2255 // Encountered desired state since we began waiting
2256 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002257 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2258 stateSeen = true;
2259 break;
2260 }
2261 }
2262 } while (!stateSeen);
2263
Yin-Chia Yehfe70f2d2020-07-28 00:17:58 -07002264 if (signalPipelineDrain) {
2265 mRequestThread->resetPipelineDrain();
2266 }
2267
Ruben Brunk183f0562015-08-12 12:55:02 -07002268 mStatusWaiters--;
2269
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002270 return res;
2271}
2272
2273
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002274status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002275 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002276 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002277
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002278 if (listener != NULL && mListener != NULL) {
2279 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2280 }
2281 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002282 mRequestThread->setNotificationListener(listener);
2283 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002284
2285 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002286}
2287
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002288bool Camera3Device::willNotify3A() {
2289 return false;
2290}
2291
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002292status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002293 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002294 status_t res;
2295 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002296
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002297 while (mResultQueue.empty()) {
2298 res = mResultSignal.waitRelative(mOutputLock, timeout);
2299 if (res == TIMED_OUT) {
2300 return res;
2301 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002302 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2303 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002304 return res;
2305 }
2306 }
2307 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002308}
2309
Jianing Weicb0652e2014-03-12 18:29:36 -07002310status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002311 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002312 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002313
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002314 if (mResultQueue.empty()) {
2315 return NOT_ENOUGH_DATA;
2316 }
2317
Jianing Weicb0652e2014-03-12 18:29:36 -07002318 if (frame == NULL) {
2319 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2320 return BAD_VALUE;
2321 }
2322
2323 CaptureResult &result = *(mResultQueue.begin());
2324 frame->mResultExtras = result.mResultExtras;
2325 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002326 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002327 mResultQueue.erase(mResultQueue.begin());
2328
2329 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002330}
2331
2332status_t Camera3Device::triggerAutofocus(uint32_t id) {
2333 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002334 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002335
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002336 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2337 // Mix-in this trigger into the next request and only the next request.
2338 RequestTrigger trigger[] = {
2339 {
2340 ANDROID_CONTROL_AF_TRIGGER,
2341 ANDROID_CONTROL_AF_TRIGGER_START
2342 },
2343 {
2344 ANDROID_CONTROL_AF_TRIGGER_ID,
2345 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002346 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002347 };
2348
2349 return mRequestThread->queueTrigger(trigger,
2350 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002351}
2352
2353status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2354 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002355 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002356
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002357 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2358 // Mix-in this trigger into the next request and only the next request.
2359 RequestTrigger trigger[] = {
2360 {
2361 ANDROID_CONTROL_AF_TRIGGER,
2362 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2363 },
2364 {
2365 ANDROID_CONTROL_AF_TRIGGER_ID,
2366 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002367 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002368 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002369
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002370 return mRequestThread->queueTrigger(trigger,
2371 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002372}
2373
2374status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2375 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002376 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002377
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002378 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2379 // Mix-in this trigger into the next request and only the next request.
2380 RequestTrigger trigger[] = {
2381 {
2382 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2383 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2384 },
2385 {
2386 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2387 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002388 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002389 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002390
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002391 return mRequestThread->queueTrigger(trigger,
2392 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002393}
2394
Jianing Weicb0652e2014-03-12 18:29:36 -07002395status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002396 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002397 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002398 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002399
Zhijun He7ef20392014-04-21 16:04:17 -07002400 {
2401 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002402
2403 // b/116514106 "disconnect()" can get called twice for the same device. The
2404 // camera device will not be initialized during the second run.
2405 if (mStatus == STATUS_UNINITIALIZED) {
2406 return OK;
2407 }
2408
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002409 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002410 }
2411
Emilian Peev08dd2452017-04-06 16:55:14 +01002412 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002413}
2414
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002415status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002416 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2417}
2418
2419status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002420 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002421 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002422 Mutex::Autolock il(mInterfaceLock);
2423 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002424
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002425 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2426 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002427 CLOGE("Stream %d does not exist", streamId);
2428 return BAD_VALUE;
2429 }
2430
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002431 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002432 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002433 return BAD_VALUE;
2434 }
2435
2436 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002437 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002438 return BAD_VALUE;
2439 }
2440
Ruben Brunkc78ac262015-08-13 17:58:46 -07002441 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002442}
2443
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002444status_t Camera3Device::tearDown(int streamId) {
2445 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002446 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002447 Mutex::Autolock il(mInterfaceLock);
2448 Mutex::Autolock l(mLock);
2449
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002450 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2451 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002452 CLOGE("Stream %d does not exist", streamId);
2453 return BAD_VALUE;
2454 }
2455
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002456 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2457 CLOGE("Stream %d is a target of a in-progress request", streamId);
2458 return BAD_VALUE;
2459 }
2460
2461 return stream->tearDown();
2462}
2463
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002464status_t Camera3Device::addBufferListenerForStream(int streamId,
2465 wp<Camera3StreamBufferListener> listener) {
2466 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002467 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002468 Mutex::Autolock il(mInterfaceLock);
2469 Mutex::Autolock l(mLock);
2470
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002471 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2472 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002473 CLOGE("Stream %d does not exist", streamId);
2474 return BAD_VALUE;
2475 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002476 stream->addBufferListener(listener);
2477
2478 return OK;
2479}
2480
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002481/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002482 * Methods called by subclasses
2483 */
2484
2485void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002486 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002487 {
2488 // Need mLock to safely update state and synchronize to current
2489 // state of methods in flight.
2490 Mutex::Autolock l(mLock);
2491 // We can get various system-idle notices from the status tracker
2492 // while starting up. Only care about them if we've actually sent
2493 // in some requests recently.
2494 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2495 return;
2496 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002497 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2498 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002499 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002500
2501 // Skip notifying listener if we're doing some user-transparent
2502 // state changes
2503 if (mPauseStateNotify) return;
2504 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002505
2506 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002507 {
2508 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002509 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002510 }
2511 if (idle && listener != NULL) {
2512 listener->notifyIdle();
2513 }
2514}
2515
Shuzhen Wang758c2152017-01-10 18:26:18 -08002516status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002517 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002518 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002519 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2520 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002521
2522 if (surfaceIds == nullptr) {
2523 return BAD_VALUE;
2524 }
2525
Zhijun He5d677d12016-05-29 16:52:39 -07002526 Mutex::Autolock il(mInterfaceLock);
2527 Mutex::Autolock l(mLock);
2528
Shuzhen Wang758c2152017-01-10 18:26:18 -08002529 if (consumers.size() == 0) {
2530 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002531 return BAD_VALUE;
2532 }
2533
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002534 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2535 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002536 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002537 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002538 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002539
2540 // isConsumerConfigurationDeferred will be off after setConsumers
2541 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002542 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002543 if (res != OK) {
2544 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2545 return res;
2546 }
2547
Emilian Peev40ead602017-09-26 15:46:36 +01002548 for (auto &consumer : consumers) {
2549 int id = stream->getSurfaceId(consumer);
2550 if (id < 0) {
2551 CLOGE("Invalid surface id!");
2552 return BAD_VALUE;
2553 }
2554 surfaceIds->push_back(id);
2555 }
2556
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002557 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002558 if (!stream->isConfiguring()) {
2559 CLOGE("Stream %d was already fully configured.", streamId);
2560 return INVALID_OPERATION;
2561 }
Zhijun He5d677d12016-05-29 16:52:39 -07002562
Shuzhen Wang0129d522016-10-30 22:43:41 -07002563 res = stream->finishConfiguration();
2564 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002565 // If finishConfiguration fails due to abandoned surface, do not set
2566 // device to error state.
2567 bool isSurfaceAbandoned =
2568 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2569 if (!isSurfaceAbandoned) {
2570 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2571 stream->getId(), strerror(-res), res);
2572 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002573 return res;
2574 }
Zhijun He5d677d12016-05-29 16:52:39 -07002575 }
2576
2577 return OK;
2578}
2579
Emilian Peev40ead602017-09-26 15:46:36 +01002580status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2581 const std::vector<OutputStreamInfo> &outputInfo,
2582 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2583 Mutex::Autolock il(mInterfaceLock);
2584 Mutex::Autolock l(mLock);
2585
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002586 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2587 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002588 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002589 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002590 }
2591
2592 for (const auto &it : removedSurfaceIds) {
2593 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2594 CLOGE("Shared surface still part of a pending request!");
2595 return -EBUSY;
2596 }
2597 }
2598
Emilian Peev40ead602017-09-26 15:46:36 +01002599 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2600 if (res != OK) {
2601 CLOGE("Stream %d failed to update stream (error %d %s) ",
2602 streamId, res, strerror(-res));
2603 if (res == UNKNOWN_ERROR) {
2604 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2605 __FUNCTION__);
2606 }
2607 return res;
2608 }
2609
2610 return res;
2611}
2612
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002613status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2614 Mutex::Autolock il(mInterfaceLock);
2615 Mutex::Autolock l(mLock);
2616
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002617 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2618 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002619 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2620 return BAD_VALUE;
2621 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002622 return stream->dropBuffers(dropping);
2623}
2624
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002625/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002626 * Camera3Device private methods
2627 */
2628
2629sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002630 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002631 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002632
2633 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002634 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002635
2636 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002637 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002638 if (inputStreams.count > 0) {
2639 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002640 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002641 CLOGE("Request references unknown input stream %d",
2642 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002643 return NULL;
2644 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002645
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002646 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002647 SET_ERR_L("%s: input stream %d is not configured!",
2648 __FUNCTION__, mInputStream->getId());
2649 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002650 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002651 // Check if stream prepare is blocking requests.
2652 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002653 CLOGE("Request references an input stream that's being prepared!");
2654 return NULL;
2655 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002656
2657 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002658 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002659 }
2660
2661 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002662 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002663 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002664 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002665 return NULL;
2666 }
2667
2668 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002669 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2670 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002671 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002672 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002673 return NULL;
2674 }
Zhijun He5d677d12016-05-29 16:52:39 -07002675 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002676 auto iter = surfaceMap.find(streams.data.i32[i]);
2677 if (iter != surfaceMap.end()) {
2678 const std::vector<size_t>& surfaces = iter->second;
2679 for (const auto& surface : surfaces) {
2680 if (stream->isConsumerConfigurationDeferred(surface)) {
2681 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2682 "due to deferred consumer", stream->getId(), surface);
2683 return NULL;
2684 }
2685 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002686 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002687 }
2688
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002689 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002690 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2691 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002692 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002693 // Check if stream prepare is blocking requests.
2694 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002695 CLOGE("Request references an output stream that's being prepared!");
2696 return NULL;
2697 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002698
2699 newRequest->mOutputStreams.push(stream);
2700 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002701 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002702 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002703
2704 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002705}
2706
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002707bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2708 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2709 Size size = mSupportedOpaqueInputSizes[i];
2710 if (size.width == width && size.height == height) {
2711 return true;
2712 }
2713 }
2714
2715 return false;
2716}
2717
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002718void Camera3Device::cancelStreamsConfigurationLocked() {
2719 int res = OK;
2720 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2721 res = mInputStream->cancelConfiguration();
2722 if (res != OK) {
2723 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2724 mInputStream->getId(), strerror(-res), res);
2725 }
2726 }
2727
2728 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002729 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002730 if (outputStream->isConfiguring()) {
2731 res = outputStream->cancelConfiguration();
2732 if (res != OK) {
2733 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2734 outputStream->getId(), strerror(-res), res);
2735 }
2736 }
2737 }
2738
2739 // Return state to that at start of call, so that future configures
2740 // properly clean things up
2741 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2742 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002743
2744 res = mPreparerThread->resume();
2745 if (res != OK) {
2746 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2747 }
2748}
2749
2750bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2751 ATRACE_CALL();
2752 bool ret = false;
2753
Jayant Chowdharydfc46592020-01-30 13:09:59 -08002754 Mutex::Autolock il(mInterfaceLock);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002755 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2756
2757 Mutex::Autolock l(mLock);
2758 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2759 if (rc == NO_ERROR) {
2760 mNeedConfig = true;
2761 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2762 if (rc == NO_ERROR) {
2763 ret = true;
2764 mPauseStateNotify = false;
2765 //Moving to active state while holding 'mLock' is important.
2766 //There could be pending calls to 'create-/deleteStream' which
2767 //will trigger another stream configuration while the already
2768 //present streams end up with outstanding buffers that will
2769 //not get drained.
2770 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002771 } else if (rc == DEAD_OBJECT) {
2772 // DEAD_OBJECT can be returned if either the consumer surface is
2773 // abandoned, or the HAL has died.
2774 // - If the HAL has died, configureStreamsLocked call will set
2775 // device to error state,
2776 // - If surface is abandoned, we should not set device to error
2777 // state.
2778 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002779 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002780 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002781 }
2782 } else {
2783 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2784 }
2785
2786 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002787}
2788
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002789status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002790 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002791 ATRACE_CALL();
2792 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002793
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002794 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002795 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002796 return INVALID_OPERATION;
2797 }
2798
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002799 if (operatingMode < 0) {
2800 CLOGE("Invalid operating mode: %d", operatingMode);
2801 return BAD_VALUE;
2802 }
2803
2804 bool isConstrainedHighSpeed =
2805 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2806 operatingMode;
2807
2808 if (mOperatingMode != operatingMode) {
2809 mNeedConfig = true;
2810 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2811 mOperatingMode = operatingMode;
2812 }
2813
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002814 if (!mNeedConfig) {
2815 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2816 return OK;
2817 }
2818
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002819 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2820 // adding a dummy stream instead.
2821 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2822 if (mOutputStreams.size() == 0) {
2823 addDummyStreamLocked();
2824 } else {
2825 tryRemoveDummyStreamLocked();
2826 }
2827
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002828 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002829 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002830
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002831 mPreparerThread->pause();
2832
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002833 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002834 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002835 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2836
2837 Vector<camera3_stream_t*> streams;
2838 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002839 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002840
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002841
2842 if (mInputStream != NULL) {
2843 camera3_stream_t *inputStream;
2844 inputStream = mInputStream->startConfiguration();
2845 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002846 CLOGE("Can't start input stream configuration");
2847 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002848 return INVALID_OPERATION;
2849 }
2850 streams.add(inputStream);
2851 }
2852
2853 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002854
2855 // Don't configure bidi streams twice, nor add them twice to the list
2856 if (mOutputStreams[i].get() ==
2857 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2858
2859 config.num_streams--;
2860 continue;
2861 }
2862
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002863 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002864 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002865 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002866 CLOGE("Can't start output stream configuration");
2867 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002868 return INVALID_OPERATION;
2869 }
2870 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002871
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002872 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002873 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2874 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002875 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2876 bufferSizes[k] = static_cast<uint32_t>(
2877 getJpegBufferSize(outputStream->width, outputStream->height));
2878 } else if (outputStream->data_space ==
2879 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2880 bufferSizes[k] = outputStream->width * outputStream->height;
2881 } else {
2882 ALOGW("%s: Blob dataSpace %d not supported",
2883 __FUNCTION__, outputStream->data_space);
2884 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002885 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002886 }
2887
2888 config.streams = streams.editArray();
2889
2890 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002891 // max_buffers, usage, and priv fields, as well as data_space and format
2892 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002893
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002894 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002895 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002896 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002897
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002898 if (res == BAD_VALUE) {
2899 // HAL rejected this set of streams as unsupported, clean up config
2900 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002901 CLOGE("Set of requested inputs/outputs not supported by HAL");
2902 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002903 return BAD_VALUE;
2904 } else if (res != OK) {
2905 // Some other kind of error from configure_streams - this is not
2906 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002907 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2908 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002909 return res;
2910 }
2911
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002912 // Finish all stream configuration immediately.
2913 // TODO: Try to relax this later back to lazy completion, which should be
2914 // faster
2915
Igor Murashkin073f8572013-05-02 14:59:28 -07002916 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002917 bool streamReConfigured = false;
2918 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002919 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002920 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002921 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002922 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002923 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2924 return DEAD_OBJECT;
2925 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002926 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002927 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002928 if (streamReConfigured) {
2929 mInterface->onStreamReConfigured(mInputStream->getId());
2930 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002931 }
2932
2933 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002934 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002935 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002936 bool streamReConfigured = false;
2937 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002938 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002939 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002940 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002941 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002942 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2943 return DEAD_OBJECT;
2944 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002945 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002946 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002947 if (streamReConfigured) {
2948 mInterface->onStreamReConfigured(outputStream->getId());
2949 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002950 }
2951 }
2952
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002953 // Request thread needs to know to avoid using repeat-last-settings protocol
2954 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002955 if (notifyRequestThread) {
2956 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2957 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002958
Zhijun He90f7c372016-08-16 16:19:43 -07002959 char value[PROPERTY_VALUE_MAX];
2960 property_get("camera.fifo.disable", value, "0");
2961 int32_t disableFifo = atoi(value);
2962 if (disableFifo != 1) {
2963 // Boost priority of request thread to SCHED_FIFO.
2964 pid_t requestThreadTid = mRequestThread->getTid();
2965 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002966 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002967 if (res != OK) {
2968 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2969 strerror(-res), res);
2970 } else {
2971 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2972 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002973 }
2974
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002975 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002976 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2977 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2978 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2979 sessionParams.unlock(newSessionParams);
2980 mSessionParams.unlock(currentSessionParams);
2981 if (updateSessionParams) {
2982 mSessionParams = sessionParams;
2983 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002984
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002985 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002986
Ruben Brunk183f0562015-08-12 12:55:02 -07002987 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2988 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002989
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002990 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002991
Zhijun He0a210512014-07-24 13:45:15 -07002992 // tear down the deleted streams after configure streams.
2993 mDeletedStreams.clear();
2994
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002995 auto rc = mPreparerThread->resume();
2996 if (rc != OK) {
2997 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2998 return rc;
2999 }
3000
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003001 if (mDummyStreamId == NO_STREAM) {
3002 mRequestBufferSM.onStreamsConfigured();
3003 }
3004
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003005 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003006}
3007
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003008status_t Camera3Device::addDummyStreamLocked() {
3009 ATRACE_CALL();
3010 status_t res;
3011
3012 if (mDummyStreamId != NO_STREAM) {
3013 // Should never be adding a second dummy stream when one is already
3014 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003015 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
3016 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003017 return INVALID_OPERATION;
3018 }
3019
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003020 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003021
3022 sp<Camera3OutputStreamInterface> dummyStream =
3023 new Camera3DummyStream(mNextStreamId);
3024
3025 res = mOutputStreams.add(mNextStreamId, dummyStream);
3026 if (res < 0) {
3027 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
3028 return res;
3029 }
3030
3031 mDummyStreamId = mNextStreamId;
3032 mNextStreamId++;
3033
3034 return OK;
3035}
3036
3037status_t Camera3Device::tryRemoveDummyStreamLocked() {
3038 ATRACE_CALL();
3039 status_t res;
3040
3041 if (mDummyStreamId == NO_STREAM) return OK;
3042 if (mOutputStreams.size() == 1) return OK;
3043
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003044 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003045
3046 // Ok, have a dummy stream and there's at least one other output stream,
3047 // so remove the dummy
3048
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003049 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
3050 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003051 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3052 return INVALID_OPERATION;
3053 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003054 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003055
3056 // Free up the stream endpoint so that it can be used by some other stream
3057 res = deletedStream->disconnect();
3058 if (res != OK) {
3059 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3060 // fall through since we want to still list the stream as deleted.
3061 }
3062 mDeletedStreams.add(deletedStream);
3063 mDummyStreamId = NO_STREAM;
3064
3065 return res;
3066}
3067
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003068void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003069 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003070 Mutex::Autolock l(mLock);
3071 va_list args;
3072 va_start(args, fmt);
3073
3074 setErrorStateLockedV(fmt, args);
3075
3076 va_end(args);
3077}
3078
3079void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003080 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003081 Mutex::Autolock l(mLock);
3082 setErrorStateLockedV(fmt, args);
3083}
3084
3085void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3086 va_list args;
3087 va_start(args, fmt);
3088
3089 setErrorStateLockedV(fmt, args);
3090
3091 va_end(args);
3092}
3093
3094void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003095 // Print out all error messages to log
3096 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003097 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003098
3099 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003100 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003101
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003102 mErrorCause = errorCause;
3103
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003104 if (mRequestThread != nullptr) {
3105 mRequestThread->setPaused(true);
3106 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003107 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003108
3109 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003110 sp<NotificationListener> listener = mListener.promote();
3111 if (listener != NULL) {
3112 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003113 CaptureResultExtras());
3114 }
3115
3116 // Save stack trace. View by dumping it later.
3117 CameraTraces::saveTrace();
3118 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003119}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003120
3121/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003122 * In-flight request management
3123 */
3124
Jianing Weicb0652e2014-03-12 18:29:36 -07003125status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003126 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003127 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003128 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003129 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003130 ATRACE_CALL();
3131 Mutex::Autolock l(mInFlightLock);
3132
3133 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003134 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003135 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3136 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003137 if (res < 0) return res;
3138
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003139 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003140 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3141 // avoid a deadlock during reprocess requests.
3142 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003143 if (mStatusTracker != nullptr) {
3144 mStatusTracker->markComponentActive(mInFlightStatusId);
3145 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003146 }
3147
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003148 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003149 return OK;
3150}
3151
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003152void Camera3Device::returnOutputBuffers(
3153 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003154 nsecs_t timestamp, bool timestampIncreasing,
3155 const SurfaceMap& outputSurfaces,
3156 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003157
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003158 for (size_t i = 0; i < numBuffers; i++)
3159 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003160 if (outputBuffers[i].buffer == nullptr) {
3161 if (!mUseHalBufManager) {
3162 // With HAL buffer management API, HAL sometimes will have to return buffers that
3163 // has not got a output buffer handle filled yet. This is though illegal if HAL
3164 // buffer management API is not being used.
3165 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3166 }
3167 continue;
3168 }
3169
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003170 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3171 int streamId = stream->getId();
3172 const auto& it = outputSurfaces.find(streamId);
3173 status_t res = OK;
3174 if (it != outputSurfaces.end()) {
3175 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003176 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3177 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003178 } else {
3179 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003180 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3181 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003182 }
3183
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003184 // Note: stream may be deallocated at this point, if this buffer was
3185 // the last reference to it.
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003186 if (res == NO_INIT || res == DEAD_OBJECT) {
3187 ALOGV("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
3188 } else if (res != OK) {
3189 ALOGE("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003190 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003191
3192 // Long processing consumers can cause returnBuffer timeout for shared stream
3193 // If that happens, cancel the buffer and send a buffer error to client
3194 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3195 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3196 // cancel the buffer
3197 camera3_stream_buffer_t sb = outputBuffers[i];
3198 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003199 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3200 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003201
3202 // notify client buffer error
3203 sp<NotificationListener> listener;
3204 {
3205 Mutex::Autolock l(mOutputLock);
3206 listener = mListener.promote();
3207 }
3208
3209 if (listener != nullptr) {
3210 CaptureResultExtras extras = inResultExtras;
3211 extras.errorStreamId = streamId;
3212 listener->notifyError(
3213 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3214 extras);
3215 }
3216 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003217 }
3218}
3219
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003220void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003221 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003222 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003223 mInFlightMap.removeItemsAt(idx, 1);
3224
3225 // Indicate idle inFlightMap to the status tracker
3226 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003227 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003228 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3229 // avoid a deadlock during reprocess requests.
3230 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003231 if (mStatusTracker != nullptr) {
3232 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3233 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003234 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003235 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003236}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003237
3238void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3239
3240 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3241 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3242
3243 nsecs_t sensorTimestamp = request.sensorTimestamp;
3244 nsecs_t shutterTimestamp = request.shutterTimestamp;
3245
3246 // Check if it's okay to remove the request from InFlightMap:
3247 // In the case of a successful request:
3248 // all input and output buffers, all result metadata, shutter callback
3249 // arrived.
3250 // In the case of a unsuccessful request:
3251 // all input and output buffers arrived.
3252 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003253 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003254 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003255 if (request.stillCapture) {
3256 ATRACE_ASYNC_END("still capture", frameNumber);
3257 }
3258
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003259 ATRACE_ASYNC_END("frame capture", frameNumber);
3260
Shuzhen Wang403044a2017-02-26 23:29:04 -08003261 // Sanity check - if sensor timestamp matches shutter timestamp in the
3262 // case of request having callback.
3263 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003264 sensorTimestamp != shutterTimestamp) {
3265 SET_ERR("sensor timestamp (%" PRId64
3266 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3267 sensorTimestamp, frameNumber, shutterTimestamp);
3268 }
3269
3270 // for an unsuccessful request, it may have pending output buffers to
3271 // return.
3272 assert(request.requestStatus != OK ||
3273 request.pendingOutputBuffers.size() == 0);
3274 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003275 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3276 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003277
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003278 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003279 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3280 }
3281
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003282 // Sanity check - if we have too many in-flight frames with long total inflight duration,
3283 // something has likely gone wrong. This might still be legit only if application send in
3284 // a long burst of long exposure requests.
3285 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3286 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3287 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3288 mInFlightMap.size(), mExpectedInflightDuration);
3289 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3290 kInFlightWarnLimitHighSpeed) {
3291 CLOGW("In-flight list too large for high speed configuration: %zu,"
3292 "total inflight duration %" PRIu64,
3293 mInFlightMap.size(), mExpectedInflightDuration);
3294 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003295 }
3296}
3297
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003298void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003299 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003300 { // First return buffers cached in mInFlightMap
3301 Mutex::Autolock l(mInFlightLock);
3302 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3303 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3304 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003305 request.pendingOutputBuffers.size(), 0,
3306 /*timestampIncreasing*/true, request.outputSurfaces,
3307 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003308 }
3309 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003310 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003311 }
3312
3313 // Then return all inflight buffers not returned by HAL
3314 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3315 mInterface->getInflightBufferKeys(&inflightKeys);
3316
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003317 // Inflight buffers for HAL buffer manager
3318 std::vector<uint64_t> inflightRequestBufferKeys;
3319 mInterface->getInflightRequestBufferKeys(&inflightRequestBufferKeys);
3320
3321 // (streamId, frameNumber, buffer_handle_t*) tuple for all inflight buffers.
3322 // frameNumber will be -1 for buffers from HAL buffer manager
3323 std::vector<std::tuple<int32_t, int32_t, buffer_handle_t*>> inflightBuffers;
3324 inflightBuffers.reserve(inflightKeys.size() + inflightRequestBufferKeys.size());
3325
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003326 for (auto& pair : inflightKeys) {
3327 int32_t frameNumber = pair.first;
3328 int32_t streamId = pair.second;
3329 buffer_handle_t* buffer;
3330 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3331 if (res != OK) {
3332 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3333 __FUNCTION__, frameNumber, streamId);
3334 continue;
3335 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003336 inflightBuffers.push_back(std::make_tuple(streamId, frameNumber, buffer));
3337 }
3338
3339 for (auto& bufferId : inflightRequestBufferKeys) {
3340 int32_t streamId = -1;
3341 buffer_handle_t* buffer = nullptr;
3342 status_t res = mInterface->popInflightRequestBuffer(bufferId, &buffer, &streamId);
3343 if (res != OK) {
3344 ALOGE("%s: cannot find in-flight buffer %" PRIu64, __FUNCTION__, bufferId);
3345 continue;
3346 }
3347 inflightBuffers.push_back(std::make_tuple(streamId, /*frameNumber*/-1, buffer));
3348 }
3349
3350 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3351 for (auto& tuple : inflightBuffers) {
3352 status_t res = OK;
3353 int32_t streamId = std::get<0>(tuple);
3354 int32_t frameNumber = std::get<1>(tuple);
3355 buffer_handle_t* buffer = std::get<2>(tuple);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003356
3357 camera3_stream_buffer_t streamBuffer;
3358 streamBuffer.buffer = buffer;
3359 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3360 streamBuffer.acquire_fence = -1;
3361 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003362
3363 // First check if the buffer belongs to deleted stream
3364 bool streamDeleted = false;
3365 for (auto& stream : mDeletedStreams) {
3366 if (streamId == stream->getId()) {
3367 streamDeleted = true;
3368 // Return buffer to deleted stream
3369 camera3_stream* halStream = stream->asHalStream();
3370 streamBuffer.stream = halStream;
3371 switch (halStream->stream_type) {
3372 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003373 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3374 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003375 if (res != OK) {
3376 ALOGE("%s: Can't return output buffer for frame %d to"
3377 " stream %d: %s (%d)", __FUNCTION__,
3378 frameNumber, streamId, strerror(-res), res);
3379 }
3380 break;
3381 case CAMERA3_STREAM_INPUT:
3382 res = stream->returnInputBuffer(streamBuffer);
3383 if (res != OK) {
3384 ALOGE("%s: Can't return input buffer for frame %d to"
3385 " stream %d: %s (%d)", __FUNCTION__,
3386 frameNumber, streamId, strerror(-res), res);
3387 }
3388 break;
3389 default: // Bi-direcitonal stream is deprecated
3390 ALOGE("%s: stream %d has unknown stream type %d",
3391 __FUNCTION__, streamId, halStream->stream_type);
3392 break;
3393 }
3394 break;
3395 }
3396 }
3397 if (streamDeleted) {
3398 continue;
3399 }
3400
3401 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003402 if (streamId == inputStreamId) {
3403 streamBuffer.stream = mInputStream->asHalStream();
3404 res = mInputStream->returnInputBuffer(streamBuffer);
3405 if (res != OK) {
3406 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003407 " stream %d: %s (%d)", __FUNCTION__,
3408 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003409 }
3410 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003411 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3412 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003413 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3414 continue;
3415 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003416 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003417 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3418 }
3419 }
3420}
3421
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003422void Camera3Device::insertResultLocked(CaptureResult *result,
3423 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003424 if (result == nullptr) return;
3425
Emilian Peev71c73a22017-03-21 16:35:51 +00003426 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3427 result->mMetadata.getAndLock());
3428 set_camera_metadata_vendor_id(meta, mVendorTagId);
3429 result->mMetadata.unlock(meta);
3430
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003431 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3432 (int32_t*)&frameNumber, 1) != OK) {
3433 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3434 return;
3435 }
3436
3437 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3438 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3439 return;
3440 }
3441
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003442 // Update vendor tag id for physical metadata
3443 for (auto& physicalMetadata : result->mPhysicalMetadatas) {
3444 camera_metadata_t *pmeta = const_cast<camera_metadata_t *>(
3445 physicalMetadata.mPhysicalCameraMetadata.getAndLock());
3446 set_camera_metadata_vendor_id(pmeta, mVendorTagId);
3447 physicalMetadata.mPhysicalCameraMetadata.unlock(pmeta);
3448 }
3449
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003450 // Valid result, insert into queue
3451 List<CaptureResult>::iterator queuedResult =
3452 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3453 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3454 ", burstId = %" PRId32, __FUNCTION__,
3455 queuedResult->mResultExtras.requestId,
3456 queuedResult->mResultExtras.frameNumber,
3457 queuedResult->mResultExtras.burstId);
3458
3459 mResultSignal.signal();
3460}
3461
3462
3463void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003464 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003465 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003466 Mutex::Autolock l(mOutputLock);
3467
3468 CaptureResult captureResult;
3469 captureResult.mResultExtras = resultExtras;
3470 captureResult.mMetadata = partialResult;
3471
Shuzhen Wang268a1362018-10-16 16:32:59 -07003472 // Fix up result metadata for monochrome camera.
3473 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3474 if (res != OK) {
3475 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3476 return;
3477 }
3478
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003479 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003480}
3481
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003482
3483void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3484 CaptureResultExtras &resultExtras,
3485 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003486 uint32_t frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003487 bool reprocess, bool zslStillCapture,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003488 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003489 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003490 if (pendingMetadata.isEmpty())
3491 return;
3492
3493 Mutex::Autolock l(mOutputLock);
3494
3495 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003496 if (reprocess) {
3497 if (frameNumber < mNextReprocessResultFrameNumber) {
3498 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003499 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003500 frameNumber, mNextReprocessResultFrameNumber);
3501 return;
3502 }
3503 mNextReprocessResultFrameNumber = frameNumber + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003504 } else if (zslStillCapture) {
3505 if (frameNumber < mNextZslStillResultFrameNumber) {
3506 SET_ERR("Out-of-order ZSL still capture result metadata submitted! "
3507 "(got frame number %d, expecting %d)",
3508 frameNumber, mNextZslStillResultFrameNumber);
3509 return;
3510 }
3511 mNextZslStillResultFrameNumber = frameNumber + 1;
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003512 } else {
3513 if (frameNumber < mNextResultFrameNumber) {
3514 SET_ERR("Out-of-order capture result metadata submitted! "
3515 "(got frame number %d, expecting %d)",
3516 frameNumber, mNextResultFrameNumber);
3517 return;
3518 }
3519 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003520 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003521
3522 CaptureResult captureResult;
3523 captureResult.mResultExtras = resultExtras;
3524 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003525 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003526
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003527 // Append any previous partials to form a complete result
3528 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3529 captureResult.mMetadata.append(collectedPartialResult);
3530 }
3531
3532 captureResult.mMetadata.sort();
3533
3534 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003535 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3536 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003537 SET_ERR("No timestamp provided by HAL for frame %d!",
3538 frameNumber);
3539 return;
3540 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003541 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3542 camera_metadata_entry timestamp =
3543 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3544 if (timestamp.count == 0) {
3545 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3546 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3547 return;
3548 }
3549 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003550
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003551 // Fix up some result metadata to account for HAL-level distortion correction
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003552 status_t res =
3553 mDistortionMappers[mId.c_str()].correctCaptureResult(&captureResult.mMetadata);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003554 if (res != OK) {
3555 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3556 frameNumber, strerror(res), res);
3557 return;
3558 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003559 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3560 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3561 if (mDistortionMappers.find(cameraId8.c_str()) == mDistortionMappers.end()) {
3562 continue;
3563 }
3564 res = mDistortionMappers[cameraId8.c_str()].correctCaptureResult(
3565 &physicalMetadata.mPhysicalCameraMetadata);
3566 if (res != OK) {
3567 SET_ERR("Unable to correct physical capture result metadata for frame %d: %s (%d)",
3568 frameNumber, strerror(res), res);
3569 return;
3570 }
3571 }
3572
Shuzhen Wang268a1362018-10-16 16:32:59 -07003573 // Fix up result metadata for monochrome camera.
3574 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3575 if (res != OK) {
3576 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3577 return;
3578 }
3579 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3580 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3581 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3582 physicalMetadata.mPhysicalCameraMetadata);
3583 if (res != OK) {
3584 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3585 return;
3586 }
3587 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003588
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003589 std::unordered_map<std::string, CameraMetadata> monitoredPhysicalMetadata;
3590 for (auto& m : physicalMetadatas) {
3591 monitoredPhysicalMetadata.emplace(String8(m.mPhysicalCameraId).string(),
3592 CameraMetadata(m.mPhysicalCameraMetadata));
3593 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003594 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003595 frameNumber, timestamp.data.i64[0], captureResult.mMetadata,
3596 monitoredPhysicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003597
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003598 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003599}
3600
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003601/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003602 * Camera HAL device callback methods
3603 */
3604
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003605void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003606 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003607
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003608 status_t res;
3609
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003610 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003611 if (result->result == NULL && result->num_output_buffers == 0 &&
3612 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003613 SET_ERR("No result data provided by HAL for frame %d",
3614 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003615 return;
3616 }
Zhijun He204e3292014-07-14 17:09:23 -07003617
Zhijun He204e3292014-07-14 17:09:23 -07003618 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003619 result->result != NULL &&
3620 result->partial_result != 1) {
3621 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3622 " if partial result is not supported",
3623 frameNumber, result->partial_result);
3624 return;
3625 }
3626
3627 bool isPartialResult = false;
3628 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003629 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003630
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003631 // Get shutter timestamp and resultExtras from list of in-flight requests,
3632 // where it was added by the shutter notification for this frame. If the
3633 // shutter timestamp isn't received yet, append the output buffers to the
3634 // in-flight request and they will be returned when the shutter timestamp
3635 // arrives. Update the in-flight status and remove the in-flight entry if
3636 // all result data and shutter timestamp have been received.
3637 nsecs_t shutterTimestamp = 0;
3638
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003639 {
3640 Mutex::Autolock l(mInFlightLock);
3641 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3642 if (idx == NAME_NOT_FOUND) {
3643 SET_ERR("Unknown frame number for capture result: %d",
3644 frameNumber);
3645 return;
3646 }
3647 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003648 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3649 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003650 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003651 __FUNCTION__, request.resultExtras.requestId,
3652 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003653 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003654 // Always update the partial count to the latest one if it's not 0
3655 // (buffers only). When framework aggregates adjacent partial results
3656 // into one, the latest partial count will be used.
3657 if (result->partial_result != 0)
3658 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003659
3660 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003661 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003662 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3663 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3664 " the range of [1, %d] when metadata is included in the result",
3665 frameNumber, result->partial_result, mNumPartialResults);
3666 return;
3667 }
3668 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003669 if (isPartialResult && result->num_physcam_metadata) {
3670 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3671 " physical camera result", frameNumber);
3672 return;
3673 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003674 if (isPartialResult) {
3675 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003676 }
3677
Shuzhen Wang4a472662017-02-26 23:29:04 -08003678 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003679 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003680 sendPartialCaptureResult(result->result, request.resultExtras,
3681 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003682 }
3683 }
3684
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003685 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003686 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003687
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003688 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003689 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003690 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3691 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3692 request.physicalCameraIds.size(), result->num_physcam_metadata);
3693 return;
3694 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003695 if (request.haveResultMetadata) {
3696 SET_ERR("Called multiple times with metadata for frame %d",
3697 frameNumber);
3698 return;
3699 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003700 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3701 String8 physicalId(result->physcam_ids[i]);
3702 std::set<String8>::iterator cameraIdIter =
3703 request.physicalCameraIds.find(physicalId);
3704 if (cameraIdIter != request.physicalCameraIds.end()) {
3705 request.physicalCameraIds.erase(cameraIdIter);
3706 } else {
3707 SET_ERR("Total result for frame %d has already returned for camera %s",
3708 frameNumber, physicalId.c_str());
3709 return;
3710 }
3711 }
Zhijun He204e3292014-07-14 17:09:23 -07003712 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003713 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003714 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003715 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003716 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003717 request.haveResultMetadata = true;
3718 }
3719
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003720 uint32_t numBuffersReturned = result->num_output_buffers;
3721 if (result->input_buffer != NULL) {
3722 if (hasInputBufferInRequest) {
3723 numBuffersReturned += 1;
3724 } else {
3725 ALOGW("%s: Input buffer should be NULL if there is no input"
3726 " buffer sent in the request",
3727 __FUNCTION__);
3728 }
3729 }
3730 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003731 if (request.numBuffersLeft < 0) {
3732 SET_ERR("Too many buffers returned for frame %d",
3733 frameNumber);
3734 return;
3735 }
3736
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003737 camera_metadata_ro_entry_t entry;
3738 res = find_camera_metadata_ro_entry(result->result,
3739 ANDROID_SENSOR_TIMESTAMP, &entry);
3740 if (res == OK && entry.count == 1) {
3741 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003742 }
3743
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003744 // If shutter event isn't received yet, append the output buffers to
3745 // the in-flight request. Otherwise, return the output buffers to
3746 // streams.
3747 if (shutterTimestamp == 0) {
3748 request.pendingOutputBuffers.appendArray(result->output_buffers,
3749 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003750 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003751 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003752 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003753 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3754 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003755 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003756
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003757 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003758 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3759 CameraMetadata physicalMetadata;
3760 physicalMetadata.append(result->physcam_metadata[i]);
3761 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3762 physicalMetadata});
3763 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003764 if (shutterTimestamp == 0) {
3765 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003766 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003767 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003768 CameraMetadata metadata;
3769 metadata = result->result;
3770 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003771 collectedPartialResult, frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003772 hasInputBufferInRequest, request.zslCapture && request.stillCapture,
3773 request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003774 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003775 }
3776
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003777 removeInFlightRequestIfReadyLocked(idx);
3778 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003779
Zhijun Hef0d962a2014-06-30 10:24:11 -07003780 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003781 if (hasInputBufferInRequest) {
3782 Camera3Stream *stream =
3783 Camera3Stream::cast(result->input_buffer->stream);
3784 res = stream->returnInputBuffer(*(result->input_buffer));
3785 // Note: stream may be deallocated at this point, if this buffer was the
3786 // last reference to it.
3787 if (res != OK) {
3788 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3789 " its stream:%s (%d)", __FUNCTION__,
3790 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003791 }
3792 } else {
3793 ALOGW("%s: Input buffer should be NULL if there is no input"
3794 " buffer sent in the request, skipping input buffer return.",
3795 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003796 }
3797 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003798}
3799
3800void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003801 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003802 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003803 {
3804 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003805 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003806 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003807
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003808 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003809 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003810 return;
3811 }
3812
3813 switch (msg->type) {
3814 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003815 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003816 break;
3817 }
3818 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003819 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003820 break;
3821 }
3822 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003823 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003824 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003825 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003826}
3827
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003828void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003829 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003830 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003831 // Map camera HAL error codes to ICameraDeviceCallback error codes
3832 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003833 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003834 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003835 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003836 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003837 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003838 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003839 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003840 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003841 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003842 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003843 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003844 };
3845
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003846 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003847 ((msg.error_code >= 0) &&
3848 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3849 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003850 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003851
3852 int streamId = 0;
Emilian Peevedec62d2019-03-19 17:59:24 -07003853 String16 physicalCameraId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003854 if (msg.error_stream != NULL) {
3855 Camera3Stream *stream =
3856 Camera3Stream::cast(msg.error_stream);
3857 streamId = stream->getId();
Emilian Peevedec62d2019-03-19 17:59:24 -07003858 physicalCameraId = String16(stream->physicalCameraId());
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003859 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003860 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3861 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003862 streamId, msg.error_code);
3863
3864 CaptureResultExtras resultExtras;
3865 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003866 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003867 // SET_ERR calls notifyError
3868 SET_ERR("Camera HAL reported serious device error");
3869 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003870 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3871 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3872 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003873 {
3874 Mutex::Autolock l(mInFlightLock);
3875 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3876 if (idx >= 0) {
3877 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3878 r.requestStatus = msg.error_code;
3879 resultExtras = r.resultExtras;
Emilian Peevedec62d2019-03-19 17:59:24 -07003880 bool logicalDeviceResultError = false;
3881 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3882 errorCode) {
3883 if (physicalCameraId.size() > 0) {
3884 String8 cameraId(physicalCameraId);
3885 if (r.physicalCameraIds.find(cameraId) == r.physicalCameraIds.end()) {
3886 ALOGE("%s: Reported result failure for physical camera device: %s "
3887 " which is not part of the respective request!",
3888 __FUNCTION__, cameraId.string());
3889 break;
3890 }
3891 resultExtras.errorPhysicalCameraId = physicalCameraId;
3892 } else {
3893 logicalDeviceResultError = true;
3894 }
3895 }
3896
3897 if (logicalDeviceResultError
Shuzhen Wang20f57342017-08-24 15:39:05 -07003898 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3899 errorCode) {
3900 r.skipResultMetadata = true;
3901 }
Emilian Peevedec62d2019-03-19 17:59:24 -07003902 if (logicalDeviceResultError) {
Emilian Peevba0fac32017-03-30 09:05:34 +01003903 // In case of missing result check whether the buffers
3904 // returned. If they returned, then remove inflight
3905 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003906 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3907 // otherwise we are depending on HAL to send the buffers back after
3908 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003909 removeInFlightRequestIfReadyLocked(idx);
3910 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003911 } else {
3912 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003913 ALOGE("Camera %s: %s: cannot find in-flight request on "
3914 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003915 resultExtras.frameNumber);
3916 }
3917 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003918 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003919 if (listener != NULL) {
3920 listener->notifyError(errorCode, resultExtras);
3921 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003922 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003923 }
3924 break;
3925 default:
3926 // SET_ERR calls notifyError
3927 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3928 break;
3929 }
3930}
3931
3932void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003933 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003934 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003935 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003936
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003937 // Set timestamp for the request in the in-flight tracking
3938 // and get the request ID to send upstream
3939 {
3940 Mutex::Autolock l(mInFlightLock);
3941 idx = mInFlightMap.indexOfKey(msg.frame_number);
3942 if (idx >= 0) {
3943 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003944
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003945 // Verify ordering of shutter notifications
3946 {
3947 Mutex::Autolock l(mOutputLock);
3948 // TODO: need to track errors for tighter bounds on expected frame number.
3949 if (r.hasInputBuffer) {
3950 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003951 SET_ERR("Reprocess shutter notification out-of-order. Expected "
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003952 "notification for frame %d, got frame %d",
3953 mNextReprocessShutterFrameNumber, msg.frame_number);
3954 return;
3955 }
3956 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003957 } else if (r.zslCapture && r.stillCapture) {
3958 if (msg.frame_number < mNextZslStillShutterFrameNumber) {
3959 SET_ERR("ZSL still capture shutter notification out-of-order. Expected "
3960 "notification for frame %d, got frame %d",
3961 mNextZslStillShutterFrameNumber, msg.frame_number);
3962 return;
3963 }
3964 mNextZslStillShutterFrameNumber = msg.frame_number + 1;
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003965 } else {
3966 if (msg.frame_number < mNextShutterFrameNumber) {
3967 SET_ERR("Shutter notification out-of-order. Expected "
3968 "notification for frame %d, got frame %d",
3969 mNextShutterFrameNumber, msg.frame_number);
3970 return;
3971 }
3972 mNextShutterFrameNumber = msg.frame_number + 1;
3973 }
3974 }
3975
Shuzhen Wang4a472662017-02-26 23:29:04 -08003976 r.shutterTimestamp = msg.timestamp;
3977 if (r.hasCallback) {
3978 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003979 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003980 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003981 // Call listener, if any
3982 if (listener != NULL) {
3983 listener->notifyShutter(r.resultExtras, msg.timestamp);
3984 }
3985 // send pending result and buffers
3986 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3987 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003988 r.hasInputBuffer, r.zslCapture && r.stillCapture,
3989 r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003990 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003991 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003992 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003993 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3994 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003995 r.pendingOutputBuffers.clear();
3996
3997 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003998 }
3999 }
4000 if (idx < 0) {
4001 SET_ERR("Shutter notification for non-existent frame number %d",
4002 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004003 }
4004}
4005
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004006CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07004007 ALOGV("%s", __FUNCTION__);
4008
Igor Murashkin1e479c02013-09-06 16:55:14 -07004009 CameraMetadata retVal;
4010
4011 if (mRequestThread != NULL) {
4012 retVal = mRequestThread->getLatestRequest();
4013 }
4014
Igor Murashkin1e479c02013-09-06 16:55:14 -07004015 return retVal;
4016}
4017
Jianing Weicb0652e2014-03-12 18:29:36 -07004018
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004019void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004020 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
4021 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
4022
4023 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
4024 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004025}
4026
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004027/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004028 * HalInterface inner class methods
4029 */
4030
Yifan Hongf79b5542017-04-11 14:44:25 -07004031Camera3Device::HalInterface::HalInterface(
4032 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004033 std::shared_ptr<RequestMetadataQueue> queue,
4034 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004035 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004036 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08004037 mUseHalBufManager(useHalBufManager),
4038 mIsReconfigurationQuerySupported(true) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004039 // Check with hardware service manager if we can downcast these interfaces
4040 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004041 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
4042 if (castResult_3_5.isOk()) {
4043 mHidlSession_3_5 = castResult_3_5;
4044 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004045 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4046 if (castResult_3_4.isOk()) {
4047 mHidlSession_3_4 = castResult_3_4;
4048 }
4049 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
4050 if (castResult_3_3.isOk()) {
4051 mHidlSession_3_3 = castResult_3_3;
4052 }
4053}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004054
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004055Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004056
4057Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004058 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004059 mRequestMetadataQueue(other.mRequestMetadataQueue),
4060 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004061
4062bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004063 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004064}
4065
4066void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00004067 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00004068 mHidlSession_3_4.clear();
4069 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004070 mHidlSession.clear();
4071}
4072
4073status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
4074 camera3_request_template_t templateId,
4075 /*out*/ camera_metadata_t **requestTemplate) {
4076 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
4077 if (!valid()) return INVALID_OPERATION;
4078 status_t res = OK;
4079
Emilian Peev31abd0a2017-05-11 18:37:46 +01004080 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004081
4082 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01004083 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004084 status = s;
4085 if (status == common::V1_0::Status::OK) {
4086 const camera_metadata *r =
4087 reinterpret_cast<const camera_metadata_t*>(request.data());
4088 size_t expectedSize = request.size();
4089 int ret = validate_camera_metadata_structure(r, &expectedSize);
4090 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
4091 *requestTemplate = clone_camera_metadata(r);
4092 if (*requestTemplate == nullptr) {
4093 ALOGE("%s: Unable to clone camera metadata received from HAL",
4094 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004095 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004096 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004097 } else {
4098 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
4099 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004100 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004101 }
4102 };
4103 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004104 RequestTemplate id;
4105 switch (templateId) {
4106 case CAMERA3_TEMPLATE_PREVIEW:
4107 id = RequestTemplate::PREVIEW;
4108 break;
4109 case CAMERA3_TEMPLATE_STILL_CAPTURE:
4110 id = RequestTemplate::STILL_CAPTURE;
4111 break;
4112 case CAMERA3_TEMPLATE_VIDEO_RECORD:
4113 id = RequestTemplate::VIDEO_RECORD;
4114 break;
4115 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
4116 id = RequestTemplate::VIDEO_SNAPSHOT;
4117 break;
4118 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
4119 id = RequestTemplate::ZERO_SHUTTER_LAG;
4120 break;
4121 case CAMERA3_TEMPLATE_MANUAL:
4122 id = RequestTemplate::MANUAL;
4123 break;
4124 default:
4125 // Unknown template ID, or this HAL is too old to support it
4126 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004127 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004128 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004129
Emilian Peev31abd0a2017-05-11 18:37:46 +01004130 if (!err.isOk()) {
4131 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4132 res = DEAD_OBJECT;
4133 } else {
4134 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004135 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004136
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004137 return res;
4138}
4139
Emilian Peev4ec17882019-01-24 17:16:58 -08004140bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4141 CameraMetadata& newSessionParams) {
4142 // We do reconfiguration by default;
4143 bool ret = true;
4144 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4145 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4146 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4147 oldSessionParams.getAndLock());
4148 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4149 newSessionParams.getAndLock());
4150 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4151 get_camera_metadata_size(oldSessioMeta));
4152 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4153 get_camera_metadata_size(newSessioMeta));
4154 hardware::camera::common::V1_0::Status callStatus;
4155 bool required;
4156 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4157 bool requiredFlag) {
4158 callStatus = s;
4159 required = requiredFlag;
4160 };
4161 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4162 oldSessionParams.unlock(oldSessioMeta);
4163 newSessionParams.unlock(newSessioMeta);
4164 if (err.isOk()) {
4165 switch (callStatus) {
4166 case hardware::camera::common::V1_0::Status::OK:
4167 ret = required;
4168 break;
4169 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4170 mIsReconfigurationQuerySupported = false;
4171 ret = true;
4172 break;
4173 default:
4174 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4175 ret = true;
4176 }
4177 } else {
4178 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4179 ret = true;
4180 }
4181 }
4182
4183 return ret;
4184}
4185
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004186status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004187 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004188 ATRACE_NAME("CameraHal::configureStreams");
4189 if (!valid()) return INVALID_OPERATION;
4190 status_t res = OK;
4191
Emilian Peev31abd0a2017-05-11 18:37:46 +01004192 // Convert stream config to HIDL
4193 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004194 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4195 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4196 requestedConfiguration3_2.streams.resize(config->num_streams);
4197 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004198 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004199 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4200 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004201 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004202
Emilian Peev31abd0a2017-05-11 18:37:46 +01004203 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4204 cam3stream->setBufferFreedListener(this);
4205 int streamId = cam3stream->getId();
4206 StreamType streamType;
4207 switch (src->stream_type) {
4208 case CAMERA3_STREAM_OUTPUT:
4209 streamType = StreamType::OUTPUT;
4210 break;
4211 case CAMERA3_STREAM_INPUT:
4212 streamType = StreamType::INPUT;
4213 break;
4214 default:
4215 ALOGE("%s: Stream %d: Unsupported stream type %d",
4216 __FUNCTION__, streamId, config->streams[i]->stream_type);
4217 return BAD_VALUE;
4218 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004219 dst3_2.id = streamId;
4220 dst3_2.streamType = streamType;
4221 dst3_2.width = src->width;
4222 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004223 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004224 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07004225 // For HidlSession version 3.5 or newer, the format and dataSpace sent
4226 // to HAL are original, not the overriden ones.
4227 if (mHidlSession_3_5 != nullptr) {
4228 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
4229 cam3stream->getOriginalFormat() : src->format);
4230 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
4231 cam3stream->getOriginalDataSpace() : src->data_space);
4232 } else {
4233 dst3_2.format = mapToPixelFormat(src->format);
4234 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4235 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004236 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004237 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004238 if (src->physical_camera_id != nullptr) {
4239 dst3_4.physicalCameraId = src->physical_camera_id;
4240 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004241
4242 activeStreams.insert(streamId);
4243 // Create Buffer ID map if necessary
4244 if (mBufferIdMaps.count(streamId) == 0) {
4245 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4246 }
4247 }
4248 // remove BufferIdMap for deleted streams
4249 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4250 int streamId = it->first;
4251 bool active = activeStreams.count(streamId) > 0;
4252 if (!active) {
4253 it = mBufferIdMaps.erase(it);
4254 } else {
4255 ++it;
4256 }
4257 }
4258
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004259 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004260 res = mapToStreamConfigurationMode(
4261 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004262 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004263 if (res != OK) {
4264 return res;
4265 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004266 requestedConfiguration3_2.operationMode = operationMode;
4267 requestedConfiguration3_4.operationMode = operationMode;
4268 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004269 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4270 get_camera_metadata_size(sessionParams));
4271
Emilian Peev31abd0a2017-05-11 18:37:46 +01004272 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004273 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004274 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004275 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004276
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004277 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004278 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4279 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004280 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004281 };
4282
4283 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4284 (hardware::Return<void>& err) -> status_t {
4285 if (!err.isOk()) {
4286 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4287 return DEAD_OBJECT;
4288 }
4289 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4290 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4291 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4292 }
4293 return OK;
4294 };
4295
Shuzhen Wang92653952019-05-07 15:11:43 -07004296 // See which version of HAL we have
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004297 if (mHidlSession_3_5 != nullptr) {
4298 ALOGV("%s: v3.5 device found", __FUNCTION__);
4299 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4300 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4301 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4302 auto err = mHidlSession_3_5->configureStreams_3_5(
4303 requestedConfiguration3_5, configStream34Cb);
4304 res = postprocConfigStream34(err);
4305 if (res != OK) {
4306 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004307 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004308 } else if (mHidlSession_3_4 != nullptr) {
4309 // We do; use v3.4 for the call
4310 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004311 auto err = mHidlSession_3_4->configureStreams_3_4(
4312 requestedConfiguration3_4, configStream34Cb);
4313 res = postprocConfigStream34(err);
4314 if (res != OK) {
4315 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004316 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004317 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004318 // We do; use v3.3 for the call
4319 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004320 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004321 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004322 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004323 finalConfiguration = halConfiguration;
4324 status = s;
4325 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004326 if (!err.isOk()) {
4327 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4328 return DEAD_OBJECT;
4329 }
4330 } else {
4331 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4332 ALOGV("%s: v3.2 device found", __FUNCTION__);
4333 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004334 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004335 [&status, &finalConfiguration_3_2]
4336 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4337 finalConfiguration_3_2 = halConfiguration;
4338 status = s;
4339 });
4340 if (!err.isOk()) {
4341 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4342 return DEAD_OBJECT;
4343 }
4344 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4345 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4346 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4347 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004348 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004349 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004350 }
4351
4352 if (status != common::V1_0::Status::OK ) {
4353 return CameraProviderManager::mapToStatusT(status);
4354 }
4355
4356 // And convert output stream configuration from HIDL
4357
4358 for (size_t i = 0; i < config->num_streams; i++) {
4359 camera3_stream_t *dst = config->streams[i];
4360 int streamId = Camera3Stream::cast(dst)->getId();
4361
4362 // Start scan at i, with the assumption that the stream order matches
4363 size_t realIdx = i;
4364 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004365 size_t halStreamCount = finalConfiguration.streams.size();
4366 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004367 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004368 found = true;
4369 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004370 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004371 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004372 }
4373 if (!found) {
4374 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4375 __FUNCTION__, streamId);
4376 return INVALID_OPERATION;
4377 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004378 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004379
Emilian Peev710c1422017-08-30 11:19:38 +01004380 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004381 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4382 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4383
Yin-Chia Yeh90667662019-07-01 15:45:00 -07004384 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07004385 dstStream->setFormatOverride(false);
4386 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004387 if (dst->format != overrideFormat) {
4388 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4389 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004390 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004391 if (dst->data_space != overrideDataSpace) {
4392 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4393 streamId, dst->format);
4394 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004395 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07004396 bool needFormatOverride =
4397 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
4398 bool needDataspaceOverride =
4399 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004400 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07004401 dstStream->setFormatOverride(needFormatOverride);
4402 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004403 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004404 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004405 }
4406
Emilian Peev31abd0a2017-05-11 18:37:46 +01004407 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004408 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004409 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004410 __FUNCTION__, streamId);
4411 return INVALID_OPERATION;
4412 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004413 dstStream->setUsage(
4414 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004415 } else {
4416 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004417 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004418 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4419 __FUNCTION__, streamId);
4420 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004421 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004422 dstStream->setUsage(
4423 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004424 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004425 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004426 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004427
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004428 return res;
4429}
4430
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004431status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004432 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004433 /*out*/std::vector<native_handle_t*>* handlesCreated,
4434 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004435 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004436 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
4437 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
4438 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004439 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004440 }
4441
4442 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004443
4444 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004445
4446 {
4447 std::lock_guard<std::mutex> lock(mInflightLock);
4448 if (request->input_buffer != nullptr) {
4449 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4450 buffer_handle_t buf = *(request->input_buffer->buffer);
4451 auto pair = getBufferId(buf, streamId);
4452 bool isNewBuffer = pair.first;
4453 uint64_t bufferId = pair.second;
4454 captureRequest->inputBuffer.streamId = streamId;
4455 captureRequest->inputBuffer.bufferId = bufferId;
4456 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4457 captureRequest->inputBuffer.status = BufferStatus::OK;
4458 native_handle_t *acquireFence = nullptr;
4459 if (request->input_buffer->acquire_fence != -1) {
4460 acquireFence = native_handle_create(1,0);
4461 acquireFence->data[0] = request->input_buffer->acquire_fence;
4462 handlesCreated->push_back(acquireFence);
4463 }
4464 captureRequest->inputBuffer.acquireFence = acquireFence;
4465 captureRequest->inputBuffer.releaseFence = nullptr;
4466
4467 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004468 request->input_buffer->buffer);
4469 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004470 } else {
4471 captureRequest->inputBuffer.streamId = -1;
4472 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4473 }
4474
4475 captureRequest->outputBuffers.resize(request->num_output_buffers);
4476 for (size_t i = 0; i < request->num_output_buffers; i++) {
4477 const camera3_stream_buffer_t *src = request->output_buffers + i;
4478 StreamBuffer &dst = captureRequest->outputBuffers[i];
4479 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004480 if (src->buffer != nullptr) {
4481 buffer_handle_t buf = *(src->buffer);
4482 auto pair = getBufferId(buf, streamId);
4483 bool isNewBuffer = pair.first;
4484 dst.bufferId = pair.second;
4485 dst.buffer = isNewBuffer ? buf : nullptr;
4486 native_handle_t *acquireFence = nullptr;
4487 if (src->acquire_fence != -1) {
4488 acquireFence = native_handle_create(1,0);
4489 acquireFence->data[0] = src->acquire_fence;
4490 handlesCreated->push_back(acquireFence);
4491 }
4492 dst.acquireFence = acquireFence;
4493 } else if (mUseHalBufManager) {
4494 // HAL buffer management path
4495 dst.bufferId = BUFFER_ID_NO_BUFFER;
4496 dst.buffer = nullptr;
4497 dst.acquireFence = nullptr;
4498 } else {
4499 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4500 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004501 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004502 dst.streamId = streamId;
4503 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004504 dst.releaseFence = nullptr;
4505
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004506 // Output buffers are empty when using HAL buffer manager
4507 if (!mUseHalBufManager) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004508 pushInflightBufferLocked(captureRequest->frameNumber, streamId, src->buffer);
4509 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004510 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004511 }
4512 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004513 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004514}
4515
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004516void Camera3Device::HalInterface::cleanupNativeHandles(
4517 std::vector<native_handle_t*> *handles, bool closeFd) {
4518 if (handles == nullptr) {
4519 return;
4520 }
4521 if (closeFd) {
4522 for (auto& handle : *handles) {
4523 native_handle_close(handle);
4524 }
4525 }
4526 for (auto& handle : *handles) {
4527 native_handle_delete(handle);
4528 }
4529 handles->clear();
4530 return;
4531}
4532
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004533status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4534 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4535 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4536 if (!valid()) return INVALID_OPERATION;
4537
Emilian Peevaebbe412018-01-15 13:53:24 +00004538 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4539 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4540 if (castResult_3_4.isOk()) {
4541 hidlSession_3_4 = castResult_3_4;
4542 }
4543
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004544 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004545 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004546 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004547 if (hidlSession_3_4 != nullptr) {
4548 captureRequests_3_4.resize(batchSize);
4549 } else {
4550 captureRequests.resize(batchSize);
4551 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004552 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004553 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004554
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004555 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004556 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004557 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004558 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004559 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00004560 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004561 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
4562 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004563 }
4564 if (res != OK) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004565 popInflightBuffers(inflightBuffers);
4566 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004567 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004568 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004569 }
4570
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004571 std::vector<device::V3_2::BufferCache> cachesToRemove;
4572 {
4573 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4574 for (auto& pair : mFreedBuffers) {
4575 // The stream might have been removed since onBufferFreed
4576 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4577 cachesToRemove.push_back({pair.first, pair.second});
4578 }
4579 }
4580 mFreedBuffers.clear();
4581 }
4582
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004583 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4584 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004585
4586 // Write metadata to FMQ.
4587 for (size_t i = 0; i < batchSize; i++) {
4588 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004589 device::V3_2::CaptureRequest* captureRequest;
4590 if (hidlSession_3_4 != nullptr) {
4591 captureRequest = &captureRequests_3_4[i].v3_2;
4592 } else {
4593 captureRequest = &captureRequests[i];
4594 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004595
4596 if (request->settings != nullptr) {
4597 size_t settingsSize = get_camera_metadata_size(request->settings);
4598 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4599 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4600 captureRequest->settings.resize(0);
4601 captureRequest->fmqSettingsSize = settingsSize;
4602 } else {
4603 if (mRequestMetadataQueue != nullptr) {
4604 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4605 }
4606 captureRequest->settings.setToExternal(
4607 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4608 get_camera_metadata_size(request->settings));
4609 captureRequest->fmqSettingsSize = 0u;
4610 }
4611 } else {
4612 // A null request settings maps to a size-0 CameraMetadata
4613 captureRequest->settings.resize(0);
4614 captureRequest->fmqSettingsSize = 0u;
4615 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004616
4617 if (hidlSession_3_4 != nullptr) {
4618 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4619 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004620 if (request->physcam_settings != nullptr) {
4621 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4622 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4623 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4624 settingsSize)) {
4625 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4626 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4627 settingsSize;
4628 } else {
4629 if (mRequestMetadataQueue != nullptr) {
4630 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4631 }
4632 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4633 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4634 request->physcam_settings[j])),
4635 get_camera_metadata_size(request->physcam_settings[j]));
4636 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004637 }
Emilian Peev00420d22018-02-05 21:33:13 +00004638 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004639 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004640 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004641 }
4642 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4643 request->physcam_id[j];
4644 }
4645 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004646 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004647
4648 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004649 auto resultCallback =
4650 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4651 status = s;
4652 *numRequestProcessed = n;
4653 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004654 if (hidlSession_3_4 != nullptr) {
4655 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004656 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004657 } else {
4658 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004659 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004660 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004661 if (!err.isOk()) {
4662 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004663 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004664 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004665
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004666 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4667 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4668 __FUNCTION__, *numRequestProcessed, batchSize);
4669 status = common::V1_0::Status::INTERNAL_ERROR;
4670 }
4671
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004672 res = CameraProviderManager::mapToStatusT(status);
4673 if (res == OK) {
4674 if (mHidlSession->isRemote()) {
4675 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
4676 // sent to camera HAL processes)
4677 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
4678 } else {
4679 // In passthrough mode the FDs are now owned by HAL
4680 cleanupNativeHandles(&handlesCreated);
4681 }
4682 } else {
4683 popInflightBuffers(inflightBuffers);
4684 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004685 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004686 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004687}
4688
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004689status_t Camera3Device::HalInterface::flush() {
4690 ATRACE_NAME("CameraHal::flush");
4691 if (!valid()) return INVALID_OPERATION;
4692 status_t res = OK;
4693
Emilian Peev31abd0a2017-05-11 18:37:46 +01004694 auto err = mHidlSession->flush();
4695 if (!err.isOk()) {
4696 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4697 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004698 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004699 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004700 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004701
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004702 return res;
4703}
4704
Emilian Peev31abd0a2017-05-11 18:37:46 +01004705status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004706 ATRACE_NAME("CameraHal::dump");
4707 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004708
Emilian Peev31abd0a2017-05-11 18:37:46 +01004709 // Handled by CameraProviderManager::dump
4710
4711 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004712}
4713
4714status_t Camera3Device::HalInterface::close() {
4715 ATRACE_NAME("CameraHal::close()");
4716 if (!valid()) return INVALID_OPERATION;
4717 status_t res = OK;
4718
Emilian Peev31abd0a2017-05-11 18:37:46 +01004719 auto err = mHidlSession->close();
4720 // Interface will be dead shortly anyway, so don't log errors
4721 if (!err.isOk()) {
4722 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004723 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004724
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004725 return res;
4726}
4727
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004728void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4729 ATRACE_NAME("CameraHal::signalPipelineDrain");
4730 if (!valid() || mHidlSession_3_5 == nullptr) {
4731 ALOGE("%s called on invalid camera!", __FUNCTION__);
4732 return;
4733 }
4734
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004735 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004736 if (!err.isOk()) {
4737 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4738 return;
4739 }
4740}
4741
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004742void Camera3Device::HalInterface::getInflightBufferKeys(
4743 std::vector<std::pair<int32_t, int32_t>>* out) {
4744 std::lock_guard<std::mutex> lock(mInflightLock);
4745 out->clear();
4746 out->reserve(mInflightBufferMap.size());
4747 for (auto& pair : mInflightBufferMap) {
4748 uint64_t key = pair.first;
4749 int32_t streamId = key & 0xFFFFFFFF;
4750 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4751 out->push_back(std::make_pair(frameNumber, streamId));
4752 }
4753 return;
4754}
4755
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004756void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4757 std::vector<uint64_t>* out) {
4758 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4759 out->clear();
4760 out->reserve(mRequestedBuffers.size());
4761 for (auto& pair : mRequestedBuffers) {
4762 out->push_back(pair.first);
4763 }
4764 return;
4765}
4766
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004767status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004768 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004769 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004770 mInflightBufferMap[key] = buffer;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004771 return OK;
4772}
4773
4774status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004775 int32_t frameNumber, int32_t streamId,
4776 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004777 std::lock_guard<std::mutex> lock(mInflightLock);
4778
4779 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4780 auto it = mInflightBufferMap.find(key);
4781 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004782 if (buffer != nullptr) {
4783 *buffer = it->second;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004784 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004785 mInflightBufferMap.erase(it);
4786 return OK;
4787}
4788
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004789void Camera3Device::HalInterface::popInflightBuffers(
4790 const std::vector<std::pair<int32_t, int32_t>>& buffers) {
4791 for (const auto& pair : buffers) {
4792 int32_t frameNumber = pair.first;
4793 int32_t streamId = pair.second;
4794 popInflightBuffer(frameNumber, streamId, nullptr);
4795 }
4796}
4797
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004798status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004799 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004800 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004801 auto pair = mRequestedBuffers.insert({bufferId, {streamId, buf}});
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004802 if (!pair.second) {
4803 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4804 __FUNCTION__, bufferId);
4805 return BAD_VALUE;
4806 }
4807 return OK;
4808}
4809
4810// Find and pop a buffer_handle_t based on bufferId
4811status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004812 uint64_t bufferId,
4813 /*out*/ buffer_handle_t** buffer,
4814 /*optional out*/ int32_t* streamId) {
4815 if (buffer == nullptr) {
4816 ALOGE("%s: buffer (%p) must not be null", __FUNCTION__, buffer);
4817 return BAD_VALUE;
4818 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004819 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4820 auto it = mRequestedBuffers.find(bufferId);
4821 if (it == mRequestedBuffers.end()) {
4822 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4823 __FUNCTION__, bufferId);
4824 return BAD_VALUE;
4825 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004826 *buffer = it->second.second;
4827 if (streamId != nullptr) {
4828 *streamId = it->second.first;
4829 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004830 mRequestedBuffers.erase(it);
4831 return OK;
4832}
4833
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004834std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4835 const buffer_handle_t& buf, int streamId) {
4836 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4837
4838 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4839 auto it = bIdMap.find(buf);
4840 if (it == bIdMap.end()) {
4841 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004842 ALOGV("stream %d now have %zu buffer caches, buf %p",
4843 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004844 return std::make_pair(true, mNextBufferId - 1);
4845 } else {
4846 return std::make_pair(false, it->second);
4847 }
4848}
4849
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004850void Camera3Device::HalInterface::onBufferFreed(
4851 int streamId, const native_handle_t* handle) {
4852 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4853 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4854 auto mapIt = mBufferIdMaps.find(streamId);
4855 if (mapIt == mBufferIdMaps.end()) {
4856 // streamId might be from a deleted stream here
4857 ALOGI("%s: stream %d has been removed",
4858 __FUNCTION__, streamId);
4859 return;
4860 }
4861 BufferIdMap& bIdMap = mapIt->second;
4862 auto it = bIdMap.find(handle);
4863 if (it == bIdMap.end()) {
4864 ALOGW("%s: cannot find buffer %p in stream %d",
4865 __FUNCTION__, handle, streamId);
4866 return;
4867 } else {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004868 bufferId = it->second;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004869 bIdMap.erase(it);
4870 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4871 __FUNCTION__, streamId, bIdMap.size(), handle);
4872 }
4873 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4874}
4875
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004876void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
4877 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4878 auto mapIt = mBufferIdMaps.find(streamId);
4879 if (mapIt == mBufferIdMaps.end()) {
4880 ALOGE("%s: streamId %d not found!", __FUNCTION__, streamId);
4881 return;
4882 }
4883
4884 BufferIdMap& bIdMap = mapIt->second;
4885 for (const auto& it : bIdMap) {
4886 uint64_t bufferId = it.second;
4887 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4888 }
4889 bIdMap.clear();
4890}
4891
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004892/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004893 * RequestThread inner class methods
4894 */
4895
4896Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004897 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004898 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4899 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004900 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004901 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004902 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004903 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004904 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004905 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004906 mReconfigured(false),
4907 mDoPause(false),
4908 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004909 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004910 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004911 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004912 mCurrentAfTriggerId(0),
4913 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004914 mRepeatingLastFrameNumber(
4915 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004916 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004917 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004918 mRequestLatency(kRequestLatencyBinSize),
4919 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004920 mLatestSessionParams(sessionParamKeys.size()),
4921 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004922 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004923}
4924
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004925Camera3Device::RequestThread::~RequestThread() {}
4926
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004927void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004928 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004929 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004930 Mutex::Autolock l(mRequestLock);
4931 mListener = listener;
4932}
4933
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004934void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4935 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004936 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004937 Mutex::Autolock l(mRequestLock);
4938 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004939 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004940 // Prepare video stream for high speed recording.
4941 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004942 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004943}
4944
Jianing Wei90e59c92014-03-12 18:29:36 -07004945status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004946 List<sp<CaptureRequest> > &requests,
4947 /*out*/
4948 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004949 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004950 Mutex::Autolock l(mRequestLock);
4951 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4952 ++it) {
4953 mRequestQueue.push_back(*it);
4954 }
4955
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004956 if (lastFrameNumber != NULL) {
4957 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4958 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4959 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4960 *lastFrameNumber);
4961 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004962
Jianing Wei90e59c92014-03-12 18:29:36 -07004963 unpauseForNewRequests();
4964
4965 return OK;
4966}
4967
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004968
4969status_t Camera3Device::RequestThread::queueTrigger(
4970 RequestTrigger trigger[],
4971 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004972 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004973 Mutex::Autolock l(mTriggerMutex);
4974 status_t ret;
4975
4976 for (size_t i = 0; i < count; ++i) {
4977 ret = queueTriggerLocked(trigger[i]);
4978
4979 if (ret != OK) {
4980 return ret;
4981 }
4982 }
4983
4984 return OK;
4985}
4986
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004987const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4988 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004989 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004990 if (d != nullptr) return d->mId;
4991 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004992}
4993
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004994status_t Camera3Device::RequestThread::queueTriggerLocked(
4995 RequestTrigger trigger) {
4996
4997 uint32_t tag = trigger.metadataTag;
4998 ssize_t index = mTriggerMap.indexOfKey(tag);
4999
5000 switch (trigger.getTagType()) {
5001 case TYPE_BYTE:
5002 // fall-through
5003 case TYPE_INT32:
5004 break;
5005 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005006 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
5007 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005008 return INVALID_OPERATION;
5009 }
5010
5011 /**
5012 * Collect only the latest trigger, since we only have 1 field
5013 * in the request settings per trigger tag, and can't send more than 1
5014 * trigger per request.
5015 */
5016 if (index != NAME_NOT_FOUND) {
5017 mTriggerMap.editValueAt(index) = trigger;
5018 } else {
5019 mTriggerMap.add(tag, trigger);
5020 }
5021
5022 return OK;
5023}
5024
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005025status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005026 const RequestList &requests,
5027 /*out*/
5028 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005029 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005030 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005031 if (lastFrameNumber != NULL) {
5032 *lastFrameNumber = mRepeatingLastFrameNumber;
5033 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005034 mRepeatingRequests.clear();
5035 mRepeatingRequests.insert(mRepeatingRequests.begin(),
5036 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005037
5038 unpauseForNewRequests();
5039
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005040 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005041 return OK;
5042}
5043
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07005044bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005045 if (mRepeatingRequests.empty()) {
5046 return false;
5047 }
5048 int32_t requestId = requestIn->mResultExtras.requestId;
5049 const RequestList &repeatRequests = mRepeatingRequests;
5050 // All repeating requests are guaranteed to have same id so only check first quest
5051 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
5052 return (firstRequest->mResultExtras.requestId == requestId);
5053}
5054
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005055status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005056 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005057 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005058 return clearRepeatingRequestsLocked(lastFrameNumber);
5059
5060}
5061
5062status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005063 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005064 if (lastFrameNumber != NULL) {
5065 *lastFrameNumber = mRepeatingLastFrameNumber;
5066 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005067 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005068 return OK;
5069}
5070
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005071status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005072 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005073 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005074 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005075 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005076
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005077 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005078
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005079 // Send errors for all requests pending in the request queue, including
5080 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005081 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005082 if (listener != NULL) {
5083 for (RequestList::iterator it = mRequestQueue.begin();
5084 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005085 // Abort the input buffers for reprocess requests.
5086 if ((*it)->mInputStream != NULL) {
5087 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07005088 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
5089 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005090 if (res != OK) {
5091 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
5092 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5093 } else {
5094 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
5095 if (res != OK) {
5096 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
5097 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5098 }
5099 }
5100 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005101 // Set the frame number this request would have had, if it
5102 // had been submitted; this frame number will not be reused.
5103 // The requestId and burstId fields were set when the request was
5104 // submitted originally (in convertMetadataListToRequestListLocked)
5105 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005106 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005107 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005108 }
5109 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005110 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08005111
5112 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005113 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005114 if (lastFrameNumber != NULL) {
5115 *lastFrameNumber = mRepeatingLastFrameNumber;
5116 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005117 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005118 return OK;
5119}
5120
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005121status_t Camera3Device::RequestThread::flush() {
5122 ATRACE_CALL();
5123 Mutex::Autolock l(mFlushLock);
5124
Emilian Peev08dd2452017-04-06 16:55:14 +01005125 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005126}
5127
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005128void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005129 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005130 Mutex::Autolock l(mPauseLock);
5131 mDoPause = paused;
5132 mDoPauseSignal.signal();
5133}
5134
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005135status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
5136 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005137 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005138 Mutex::Autolock l(mLatestRequestMutex);
5139 status_t res;
5140 while (mLatestRequestId != requestId) {
5141 nsecs_t startTime = systemTime();
5142
5143 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
5144 if (res != OK) return res;
5145
5146 timeout -= (systemTime() - startTime);
5147 }
5148
5149 return OK;
5150}
5151
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005152void Camera3Device::RequestThread::requestExit() {
5153 // Call parent to set up shutdown
5154 Thread::requestExit();
5155 // The exit from any possible waits
5156 mDoPauseSignal.signal();
5157 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07005158
5159 mRequestLatency.log("ProcessCaptureRequest latency histogram");
5160 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005161}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005162
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005163void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005164 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005165 bool surfaceAbandoned = false;
5166 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005167 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005168 {
5169 Mutex::Autolock l(mRequestLock);
5170 // Check all streams needed by repeating requests are still valid. Otherwise, stop
5171 // repeating requests.
5172 for (const auto& request : mRepeatingRequests) {
5173 for (const auto& s : request->mOutputStreams) {
5174 if (s->isAbandoned()) {
5175 surfaceAbandoned = true;
5176 clearRepeatingRequestsLocked(&lastFrameNumber);
5177 break;
5178 }
5179 }
5180 if (surfaceAbandoned) {
5181 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005182 }
5183 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005184 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005185 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005186
5187 if (listener != NULL && surfaceAbandoned) {
5188 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005189 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005190}
5191
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005192bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005193 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005194 status_t res;
5195 size_t batchSize = mNextRequests.size();
5196 std::vector<camera3_capture_request_t*> requests(batchSize);
5197 uint32_t numRequestProcessed = 0;
5198 for (size_t i = 0; i < batchSize; i++) {
5199 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07005200 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005201 }
5202
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005203 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
5204
5205 bool triggerRemoveFailed = false;
5206 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
5207 for (size_t i = 0; i < numRequestProcessed; i++) {
5208 NextRequest& nextRequest = mNextRequests.editItemAt(i);
5209 nextRequest.submitted = true;
5210
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005211 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00005212
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005213 if (!triggerRemoveFailed) {
5214 // Remove any previously queued triggers (after unlock)
5215 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5216 if (removeTriggerRes != OK) {
5217 triggerRemoveFailed = true;
5218 triggerFailedRequest = nextRequest;
5219 }
5220 }
5221 }
5222
5223 if (triggerRemoveFailed) {
5224 SET_ERR("RequestThread: Unable to remove triggers "
5225 "(capture request %d, HAL device: %s (%d)",
5226 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5227 cleanUpFailedRequests(/*sendRequestError*/ false);
5228 return false;
5229 }
5230
5231 if (res != OK) {
5232 // Should only get a failure here for malformed requests or device-level
5233 // errors, so consider all errors fatal. Bad metadata failures should
5234 // come through notify.
5235 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5236 mNextRequests[numRequestProcessed].halRequest.frame_number,
5237 strerror(-res), res);
5238 cleanUpFailedRequests(/*sendRequestError*/ false);
5239 return false;
5240 }
5241 return true;
5242}
5243
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005244nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5245 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5246 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5247 find_camera_metadata_ro_entry(request,
5248 ANDROID_CONTROL_AE_MODE,
5249 &e);
5250 if (e.count == 0) return maxExpectedDuration;
5251
5252 switch (e.data.u8[0]) {
5253 case ANDROID_CONTROL_AE_MODE_OFF:
5254 find_camera_metadata_ro_entry(request,
5255 ANDROID_SENSOR_EXPOSURE_TIME,
5256 &e);
5257 if (e.count > 0) {
5258 maxExpectedDuration = e.data.i64[0];
5259 }
5260 find_camera_metadata_ro_entry(request,
5261 ANDROID_SENSOR_FRAME_DURATION,
5262 &e);
5263 if (e.count > 0) {
5264 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5265 }
5266 break;
5267 default:
5268 find_camera_metadata_ro_entry(request,
5269 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5270 &e);
5271 if (e.count > 1) {
5272 maxExpectedDuration = 1e9 / e.data.u8[0];
5273 }
5274 break;
5275 }
5276
5277 return maxExpectedDuration;
5278}
5279
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005280bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5281 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5282 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5283 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5284 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5285 return true;
5286 }
5287
5288 return false;
5289}
5290
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005291void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
5292 // Update the latest request sent to HAL
5293 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5294 Mutex::Autolock al(mLatestRequestMutex);
5295
5296 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5297 mLatestRequest.acquire(cloned);
5298
5299 mLatestPhysicalRequest.clear();
5300 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
5301 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
5302 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
5303 CameraMetadata(cloned));
5304 }
5305
5306 sp<Camera3Device> parent = mParent.promote();
5307 if (parent != NULL) {
5308 parent->monitorMetadata(TagMonitor::REQUEST,
5309 nextRequest.halRequest.frame_number,
5310 0, mLatestRequest, mLatestPhysicalRequest);
5311 }
5312 }
5313
5314 if (nextRequest.halRequest.settings != NULL) {
5315 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5316 nextRequest.halRequest.settings);
5317 }
5318
5319 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5320}
5321
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005322bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5323 ATRACE_CALL();
5324 bool updatesDetected = false;
5325
Emilian Peev4ec17882019-01-24 17:16:58 -08005326 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005327 for (auto tag : mSessionParamKeys) {
5328 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005329 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005330
5331 if (entry.count > 0) {
5332 bool isDifferent = false;
5333 if (lastEntry.count > 0) {
5334 // Have a last value, compare to see if changed
5335 if (lastEntry.type == entry.type &&
5336 lastEntry.count == entry.count) {
5337 // Same type and count, compare values
5338 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5339 size_t entryBytes = bytesPerValue * lastEntry.count;
5340 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5341 if (cmp != 0) {
5342 isDifferent = true;
5343 }
5344 } else {
5345 // Count or type has changed
5346 isDifferent = true;
5347 }
5348 } else {
5349 // No last entry, so always consider to be different
5350 isDifferent = true;
5351 }
5352
5353 if (isDifferent) {
5354 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005355 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5356 updatesDetected = true;
5357 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005358 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005359 }
5360 } else if (lastEntry.count > 0) {
5361 // Value has been removed
5362 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005363 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005364 updatesDetected = true;
5365 }
5366 }
5367
Emilian Peev4ec17882019-01-24 17:16:58 -08005368 bool reconfigureRequired;
5369 if (updatesDetected) {
5370 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5371 updatedParams);
5372 mLatestSessionParams = updatedParams;
5373 } else {
5374 reconfigureRequired = false;
5375 }
5376
5377 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005378}
5379
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005380bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005381 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005382 status_t res;
Jayant Chowdhary37eca242019-11-18 08:55:56 -08005383 // Any function called from threadLoop() must not hold mInterfaceLock since
5384 // it could lead to deadlocks (disconnect() -> hold mInterfaceMutex -> wait for request thread
5385 // to finish -> request thread waits on mInterfaceMutex) http://b/143513518
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005386
5387 // Handle paused state.
5388 if (waitIfPaused()) {
5389 return true;
5390 }
5391
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005392 // Wait for the next batch of requests.
5393 waitForNextRequestBatch();
5394 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005395 return true;
5396 }
5397
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005398 // Get the latest request ID, if any
5399 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005400 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005401 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005402 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005403 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005404 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005405 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5406 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005407 }
5408
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005409 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5410 // or a single request from streaming or burst. In either case the first element
5411 // should contain the latest camera settings that we need to check for any session
5412 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005413 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005414 res = OK;
5415
5416 //Input stream buffers are already acquired at this point so an input stream
5417 //will not be able to move to idle state unless we force it.
5418 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5419 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5420 if (res != OK) {
5421 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5422 cleanUpFailedRequests(/*sendRequestError*/ false);
5423 return false;
5424 }
5425 }
5426
5427 if (res == OK) {
5428 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5429 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005430 sp<Camera3Device> parent = mParent.promote();
5431 if (parent != nullptr) {
5432 parent->pauseStateNotify(true);
5433 }
5434
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005435 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5436
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005437 if (parent != nullptr) {
5438 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5439 }
5440
5441 statusTracker->markComponentActive(mStatusId);
5442 setPaused(false);
5443 }
5444
5445 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5446 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5447 if (res != OK) {
5448 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5449 cleanUpFailedRequests(/*sendRequestError*/ false);
5450 return false;
5451 }
5452 }
5453 }
5454 }
5455
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005456 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005457 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005458 if (res == TIMED_OUT) {
5459 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005460 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005461 // Check if any stream is abandoned.
5462 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005463 return true;
5464 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005465 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005466 return false;
5467 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005468
Zhijun Hecc27e112013-10-03 16:12:43 -07005469 // Inform waitUntilRequestProcessed thread of a new request ID
5470 {
5471 Mutex::Autolock al(mLatestRequestMutex);
5472
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005473 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005474 mLatestRequestSignal.signal();
5475 }
5476
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005477 // Submit a batch of requests to HAL.
5478 // Use flush lock only when submitting multilple requests in a batch.
5479 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5480 // which may take a long time to finish so synchronizing flush() and
5481 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5482 // For now, only synchronize for high speed recording and we should figure something out for
5483 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005484 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005485
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005486 if (useFlushLock) {
5487 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005488 }
5489
Zhijun Hef0645c12016-08-02 00:58:11 -07005490 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005491 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005492
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005493 sp<Camera3Device> parent = mParent.promote();
5494 if (parent != nullptr) {
5495 parent->mRequestBufferSM.onSubmittingRequest();
5496 }
5497
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005498 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005499 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07005500 submitRequestSuccess = sendRequestsBatch();
5501
Shuzhen Wang686f6442017-06-20 16:16:04 -07005502 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5503 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005504
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005505 if (useFlushLock) {
5506 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005507 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005508
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005509 // Unset as current request
5510 {
5511 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005512 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005513 }
5514
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005515 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005516}
5517
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005518status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005519 ATRACE_CALL();
5520
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005521 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005522 for (size_t i = 0; i < mNextRequests.size(); i++) {
5523 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005524 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5525 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5526 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5527
5528 // Prepare a request to HAL
5529 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5530
5531 // Insert any queued triggers (before metadata is locked)
5532 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005533 if (res < 0) {
5534 SET_ERR("RequestThread: Unable to insert triggers "
5535 "(capture request %d, HAL device: %s (%d)",
5536 halRequest->frame_number, strerror(-res), res);
5537 return INVALID_OPERATION;
5538 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005539
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005540 int triggerCount = res;
5541 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5542 mPrevTriggers = triggerCount;
5543
5544 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005545 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5546 // Request settings are all the same within one batch, so only treat the first
5547 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005548 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005549 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005550 /**
5551 * HAL workaround:
5552 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5553 */
5554 res = addDummyTriggerIds(captureRequest);
5555 if (res != OK) {
5556 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5557 "(capture request %d, HAL device: %s (%d)",
5558 halRequest->frame_number, strerror(-res), res);
5559 return INVALID_OPERATION;
5560 }
5561
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005562 {
5563 // Correct metadata regions for distortion correction if enabled
5564 sp<Camera3Device> parent = mParent.promote();
5565 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07005566 List<PhysicalCameraSettings>::iterator it;
5567 for (it = captureRequest->mSettingsList.begin();
5568 it != captureRequest->mSettingsList.end(); it++) {
5569 if (parent->mDistortionMappers.find(it->cameraId) ==
5570 parent->mDistortionMappers.end()) {
5571 continue;
5572 }
5573 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
5574 &(it->metadata));
5575 if (res != OK) {
5576 SET_ERR("RequestThread: Unable to correct capture requests "
5577 "for lens distortion for request %d: %s (%d)",
5578 halRequest->frame_number, strerror(-res), res);
5579 return INVALID_OPERATION;
5580 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005581 }
5582 }
5583 }
5584
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005585 /**
5586 * The request should be presorted so accesses in HAL
5587 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5588 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005589 captureRequest->mSettingsList.begin()->metadata.sort();
5590 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005591 mPrevRequest = captureRequest;
5592 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5593
5594 IF_ALOGV() {
5595 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5596 find_camera_metadata_ro_entry(
5597 halRequest->settings,
5598 ANDROID_CONTROL_AF_TRIGGER,
5599 &e
5600 );
5601 if (e.count > 0) {
5602 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5603 __FUNCTION__,
5604 halRequest->frame_number,
5605 e.data.u8[0]);
5606 }
5607 }
5608 } else {
5609 // leave request.settings NULL to indicate 'reuse latest given'
5610 ALOGVV("%s: Request settings are REUSED",
5611 __FUNCTION__);
5612 }
5613
Emilian Peevaebbe412018-01-15 13:53:24 +00005614 if (captureRequest->mSettingsList.size() > 1) {
5615 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5616 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005617 if (newRequest) {
5618 halRequest->physcam_settings =
5619 new const camera_metadata* [halRequest->num_physcam_settings];
5620 } else {
5621 halRequest->physcam_settings = nullptr;
5622 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005623 auto it = ++captureRequest->mSettingsList.begin();
5624 size_t i = 0;
5625 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5626 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005627 if (newRequest) {
5628 it->metadata.sort();
5629 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5630 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005631 }
5632 }
5633
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005634 uint32_t totalNumBuffers = 0;
5635
5636 // Fill in buffers
5637 if (captureRequest->mInputStream != NULL) {
5638 halRequest->input_buffer = &captureRequest->mInputBuffer;
5639 totalNumBuffers += 1;
5640 } else {
5641 halRequest->input_buffer = NULL;
5642 }
5643
5644 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5645 captureRequest->mOutputStreams.size());
5646 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005647 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005648
5649 sp<Camera3Device> parent = mParent.promote();
5650 if (parent == NULL) {
5651 // Should not happen, and nowhere to send errors to, so just log it
5652 CLOGE("RequestThread: Parent is gone");
5653 return INVALID_OPERATION;
5654 }
5655 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5656
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005657 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005658 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005659 sp<Camera3OutputStreamInterface> outputStream =
5660 captureRequest->mOutputStreams.editItemAt(j);
5661 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005662
5663 // Prepare video buffers for high speed recording on the first video request.
5664 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5665 // Only try to prepare video stream on the first video request.
5666 mPrepareVideoStream = false;
5667
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005668 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5669 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005670 while (res == NOT_ENOUGH_DATA) {
5671 res = outputStream->prepareNextBuffer();
5672 }
5673 if (res != OK) {
5674 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5675 __FUNCTION__, strerror(-res), res);
5676 outputStream->cancelPrepare();
5677 }
5678 }
5679
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005680 std::vector<size_t> uniqueSurfaceIds;
5681 res = outputStream->getUniqueSurfaceIds(
5682 captureRequest->mOutputSurfaces[streamId],
5683 &uniqueSurfaceIds);
5684 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5685 if (res != OK && res != INVALID_OPERATION) {
5686 ALOGE("%s: failed to query stream %d unique surface IDs",
5687 __FUNCTION__, streamId);
5688 return res;
5689 }
5690 if (res == OK) {
5691 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5692 }
5693
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005694 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005695 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005696 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005697 return TIMED_OUT;
5698 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005699 // HAL will request buffer through requestStreamBuffer API
5700 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5701 buffer.stream = outputStream->asHalStream();
5702 buffer.buffer = nullptr;
5703 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5704 buffer.acquire_fence = -1;
5705 buffer.release_fence = -1;
5706 } else {
5707 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5708 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005709 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005710 if (res != OK) {
5711 // Can't get output buffer from gralloc queue - this could be due to
5712 // abandoned queue or other consumer misbehavior, so not a fatal
5713 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005714 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005715 " %s (%d)", strerror(-res), res);
5716
5717 return TIMED_OUT;
5718 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005719 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005720
5721 {
5722 sp<Camera3Device> parent = mParent.promote();
5723 if (parent != nullptr) {
5724 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5725 for (const auto& settings : captureRequest->mSettingsList) {
5726 if ((streamCameraId.isEmpty() &&
5727 parent->getId() == settings.cameraId.c_str()) ||
5728 streamCameraId == settings.cameraId.c_str()) {
5729 outputStream->fireBufferRequestForFrameNumber(
5730 captureRequest->mResultExtras.frameNumber,
5731 settings.metadata);
5732 }
5733 }
5734 }
5735 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005736
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005737 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5738
5739 if (!physicalCameraId.isEmpty()) {
5740 // Physical stream isn't supported for input request.
5741 if (halRequest->input_buffer) {
5742 CLOGE("Physical stream is not supported for input request");
5743 return INVALID_OPERATION;
5744 }
5745 requestedPhysicalCameras.insert(physicalCameraId);
5746 }
5747 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005748 }
5749 totalNumBuffers += halRequest->num_output_buffers;
5750
5751 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005752 // If this request list is for constrained high speed recording (not
5753 // preview), and the current request is not the last one in the batch,
5754 // do not send callback to the app.
5755 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005756 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005757 hasCallback = false;
5758 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005759 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005760 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005761 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5762 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5763 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5764 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5765 isStillCapture = true;
5766 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5767 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005768
5769 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5770 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5771 isZslCapture = true;
5772 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005773 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005774 res = parent->registerInFlight(halRequest->frame_number,
5775 totalNumBuffers, captureRequest->mResultExtras,
5776 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005777 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005778 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005779 requestedPhysicalCameras, isStillCapture, isZslCapture,
5780 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5781 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005782 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5783 ", burstId = %" PRId32 ".",
5784 __FUNCTION__,
5785 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5786 captureRequest->mResultExtras.burstId);
5787 if (res != OK) {
5788 SET_ERR("RequestThread: Unable to register new in-flight request:"
5789 " %s (%d)", strerror(-res), res);
5790 return INVALID_OPERATION;
5791 }
5792 }
5793
5794 return OK;
5795}
5796
Igor Murashkin1e479c02013-09-06 16:55:14 -07005797CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005798 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005799 Mutex::Autolock al(mLatestRequestMutex);
5800
5801 ALOGV("RequestThread::%s", __FUNCTION__);
5802
5803 return mLatestRequest;
5804}
5805
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005806bool Camera3Device::RequestThread::isStreamPending(
5807 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005808 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005809 Mutex::Autolock l(mRequestLock);
5810
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005811 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005812 if (!nextRequest.submitted) {
5813 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5814 if (stream == s) return true;
5815 }
5816 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005817 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005818 }
5819
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005820 for (const auto& request : mRequestQueue) {
5821 for (const auto& s : request->mOutputStreams) {
5822 if (stream == s) return true;
5823 }
5824 if (stream == request->mInputStream) return true;
5825 }
5826
5827 for (const auto& request : mRepeatingRequests) {
5828 for (const auto& s : request->mOutputStreams) {
5829 if (stream == s) return true;
5830 }
5831 if (stream == request->mInputStream) return true;
5832 }
5833
5834 return false;
5835}
Jianing Weicb0652e2014-03-12 18:29:36 -07005836
Emilian Peev40ead602017-09-26 15:46:36 +01005837bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5838 ATRACE_CALL();
5839 Mutex::Autolock l(mRequestLock);
5840
5841 for (const auto& nextRequest : mNextRequests) {
5842 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5843 if (s.first == streamId) {
5844 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5845 if (it != s.second.end()) {
5846 return true;
5847 }
5848 }
5849 }
5850 }
5851
5852 for (const auto& request : mRequestQueue) {
5853 for (const auto& s : request->mOutputSurfaces) {
5854 if (s.first == streamId) {
5855 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5856 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005857 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005858 }
5859 }
5860 }
5861 }
5862
5863 for (const auto& request : mRepeatingRequests) {
5864 for (const auto& s : request->mOutputSurfaces) {
5865 if (s.first == streamId) {
5866 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5867 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005868 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005869 }
5870 }
5871 }
5872 }
5873
5874 return false;
5875}
5876
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005877void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5878 if (!mUseHalBufManager) {
5879 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5880 return;
5881 }
5882
5883 Mutex::Autolock pl(mPauseLock);
5884 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005885 mInterface->signalPipelineDrain(streamIds);
5886 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005887 }
5888 // If request thread is still busy, wait until paused then notify HAL
5889 mNotifyPipelineDrain = true;
5890 mStreamIdsToBeDrained = streamIds;
5891}
5892
Yin-Chia Yehfe70f2d2020-07-28 00:17:58 -07005893void Camera3Device::RequestThread::resetPipelineDrain() {
5894 Mutex::Autolock pl(mPauseLock);
5895 mNotifyPipelineDrain = false;
5896 mStreamIdsToBeDrained.clear();
5897}
5898
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005899nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005900 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005901 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005902 return mExpectedInflightDuration > kMinInflightDuration ?
5903 mExpectedInflightDuration : kMinInflightDuration;
5904}
5905
Emilian Peevaebbe412018-01-15 13:53:24 +00005906void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5907 camera3_capture_request_t *halRequest) {
5908 if ((request == nullptr) || (halRequest == nullptr)) {
5909 ALOGE("%s: Invalid request!", __FUNCTION__);
5910 return;
5911 }
5912
5913 if (halRequest->num_physcam_settings > 0) {
5914 if (halRequest->physcam_id != nullptr) {
5915 delete [] halRequest->physcam_id;
5916 halRequest->physcam_id = nullptr;
5917 }
5918 if (halRequest->physcam_settings != nullptr) {
5919 auto it = ++(request->mSettingsList.begin());
5920 size_t i = 0;
5921 for (; it != request->mSettingsList.end(); it++, i++) {
5922 it->metadata.unlock(halRequest->physcam_settings[i]);
5923 }
5924 delete [] halRequest->physcam_settings;
5925 halRequest->physcam_settings = nullptr;
5926 }
5927 }
5928}
5929
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005930void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5931 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005932 return;
5933 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005934
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005935 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005936 // Skip the ones that have been submitted successfully.
5937 if (nextRequest.submitted) {
5938 continue;
5939 }
5940
5941 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5942 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5943 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5944
5945 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005946 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005947 }
5948
Emilian Peevaebbe412018-01-15 13:53:24 +00005949 cleanupPhysicalSettings(captureRequest, halRequest);
5950
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005951 if (captureRequest->mInputStream != NULL) {
5952 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5953 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5954 }
5955
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005956 // No output buffer can be returned when using HAL buffer manager
5957 if (!mUseHalBufManager) {
5958 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5959 //Buffers that failed processing could still have
5960 //valid acquire fence.
5961 int acquireFence = (*outputBuffers)[i].acquire_fence;
5962 if (0 <= acquireFence) {
5963 close(acquireFence);
5964 outputBuffers->editItemAt(i).acquire_fence = -1;
5965 }
5966 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5967 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5968 /*timestampIncreasing*/true, std::vector<size_t> (),
5969 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005970 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005971 }
5972
5973 if (sendRequestError) {
5974 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005975 sp<NotificationListener> listener = mListener.promote();
5976 if (listener != NULL) {
5977 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005978 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005979 captureRequest->mResultExtras);
5980 }
5981 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005982
5983 // Remove yet-to-be submitted inflight request from inflightMap
5984 {
5985 sp<Camera3Device> parent = mParent.promote();
5986 if (parent != NULL) {
5987 Mutex::Autolock l(parent->mInFlightLock);
5988 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5989 if (idx >= 0) {
5990 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5991 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5992 parent->removeInFlightMapEntryLocked(idx);
5993 }
5994 }
5995 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005996 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005997
5998 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005999 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006000}
6001
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006002void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006003 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006004 // Optimized a bit for the simple steady-state case (single repeating
6005 // request), to avoid putting that request in the queue temporarily.
6006 Mutex::Autolock l(mRequestLock);
6007
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006008 assert(mNextRequests.empty());
6009
6010 NextRequest nextRequest;
6011 nextRequest.captureRequest = waitForNextRequestLocked();
6012 if (nextRequest.captureRequest == nullptr) {
6013 return;
6014 }
6015
6016 nextRequest.halRequest = camera3_capture_request_t();
6017 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006018 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006019
6020 // Wait for additional requests
6021 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
6022
6023 for (size_t i = 1; i < batchSize; i++) {
6024 NextRequest additionalRequest;
6025 additionalRequest.captureRequest = waitForNextRequestLocked();
6026 if (additionalRequest.captureRequest == nullptr) {
6027 break;
6028 }
6029
6030 additionalRequest.halRequest = camera3_capture_request_t();
6031 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006032 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006033 }
6034
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006035 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006036 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006037 mNextRequests.size(), batchSize);
6038 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006039 }
6040
6041 return;
6042}
6043
6044sp<Camera3Device::CaptureRequest>
6045 Camera3Device::RequestThread::waitForNextRequestLocked() {
6046 status_t res;
6047 sp<CaptureRequest> nextRequest;
6048
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006049 while (mRequestQueue.empty()) {
6050 if (!mRepeatingRequests.empty()) {
6051 // Always atomically enqueue all requests in a repeating request
6052 // list. Guarantees a complete in-sequence set of captures to
6053 // application.
6054 const RequestList &requests = mRepeatingRequests;
6055 RequestList::const_iterator firstRequest =
6056 requests.begin();
6057 nextRequest = *firstRequest;
6058 mRequestQueue.insert(mRequestQueue.end(),
6059 ++firstRequest,
6060 requests.end());
6061 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07006062
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006063 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07006064
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006065 break;
6066 }
6067
6068 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
6069
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006070 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
6071 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006072 Mutex::Autolock pl(mPauseLock);
6073 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006074 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006075 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006076 if (mNotifyPipelineDrain) {
6077 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6078 mNotifyPipelineDrain = false;
6079 mStreamIdsToBeDrained.clear();
6080 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006081 // Let the tracker know
6082 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6083 if (statusTracker != 0) {
6084 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6085 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006086 sp<Camera3Device> parent = mParent.promote();
6087 if (parent != nullptr) {
6088 parent->mRequestBufferSM.onRequestThreadPaused();
6089 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006090 }
6091 // Stop waiting for now and let thread management happen
6092 return NULL;
6093 }
6094 }
6095
6096 if (nextRequest == NULL) {
6097 // Don't have a repeating request already in hand, so queue
6098 // must have an entry now.
6099 RequestList::iterator firstRequest =
6100 mRequestQueue.begin();
6101 nextRequest = *firstRequest;
6102 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07006103 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
6104 sp<NotificationListener> listener = mListener.promote();
6105 if (listener != NULL) {
6106 listener->notifyRequestQueueEmpty();
6107 }
6108 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006109 }
6110
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006111 // In case we've been unpaused by setPaused clearing mDoPause, need to
6112 // update internal pause state (capture/setRepeatingRequest unpause
6113 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006114 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006115 if (mPaused) {
6116 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
6117 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6118 if (statusTracker != 0) {
6119 statusTracker->markComponentActive(mStatusId);
6120 }
6121 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006122 mPaused = false;
6123
6124 // Check if we've reconfigured since last time, and reset the preview
6125 // request if so. Can't use 'NULL request == repeat' across configure calls.
6126 if (mReconfigured) {
6127 mPrevRequest.clear();
6128 mReconfigured = false;
6129 }
6130
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006131 if (nextRequest != NULL) {
6132 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006133 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
6134 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006135
6136 // Since RequestThread::clear() removes buffers from the input stream,
6137 // get the right buffer here before unlocking mRequestLock
6138 if (nextRequest->mInputStream != NULL) {
6139 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
6140 if (res != OK) {
6141 // Can't get input buffer from gralloc queue - this could be due to
6142 // disconnected queue or other producer misbehavior, so not a fatal
6143 // error
6144 ALOGE("%s: Can't get input buffer, skipping request:"
6145 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006146
6147 sp<NotificationListener> listener = mListener.promote();
6148 if (listener != NULL) {
6149 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006150 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006151 nextRequest->mResultExtras);
6152 }
6153 return NULL;
6154 }
6155 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006156 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07006157
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006158 return nextRequest;
6159}
6160
6161bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006162 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006163 status_t res;
6164 Mutex::Autolock l(mPauseLock);
6165 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006166 if (mPaused == false) {
6167 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006168 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006169 if (mNotifyPipelineDrain) {
6170 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6171 mNotifyPipelineDrain = false;
6172 mStreamIdsToBeDrained.clear();
6173 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006174 // Let the tracker know
6175 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6176 if (statusTracker != 0) {
6177 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6178 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006179 sp<Camera3Device> parent = mParent.promote();
6180 if (parent != nullptr) {
6181 parent->mRequestBufferSM.onRequestThreadPaused();
6182 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006183 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006184
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006185 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006186 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006187 return true;
6188 }
6189 }
6190 // We don't set mPaused to false here, because waitForNextRequest needs
6191 // to further manage the paused state in case of starvation.
6192 return false;
6193}
6194
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006195void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006196 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006197 // With work to do, mark thread as unpaused.
6198 // If paused by request (setPaused), don't resume, to avoid
6199 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006200 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006201 Mutex::Autolock p(mPauseLock);
6202 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006203 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6204 if (mPaused) {
6205 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6206 if (statusTracker != 0) {
6207 statusTracker->markComponentActive(mStatusId);
6208 }
6209 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006210 mPaused = false;
6211 }
6212}
6213
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006214void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6215 sp<Camera3Device> parent = mParent.promote();
6216 if (parent != NULL) {
6217 va_list args;
6218 va_start(args, fmt);
6219
6220 parent->setErrorStateV(fmt, args);
6221
6222 va_end(args);
6223 }
6224}
6225
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006226status_t Camera3Device::RequestThread::insertTriggers(
6227 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006228 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006229 Mutex::Autolock al(mTriggerMutex);
6230
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006231 sp<Camera3Device> parent = mParent.promote();
6232 if (parent == NULL) {
6233 CLOGE("RequestThread: Parent is gone");
6234 return DEAD_OBJECT;
6235 }
6236
Emilian Peevaebbe412018-01-15 13:53:24 +00006237 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006238 size_t count = mTriggerMap.size();
6239
6240 for (size_t i = 0; i < count; ++i) {
6241 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006242 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006243
6244 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6245 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6246 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006247 if (isAeTrigger) {
6248 request->mResultExtras.precaptureTriggerId = triggerId;
6249 mCurrentPreCaptureTriggerId = triggerId;
6250 } else {
6251 request->mResultExtras.afTriggerId = triggerId;
6252 mCurrentAfTriggerId = triggerId;
6253 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006254 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006255 }
6256
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006257 camera_metadata_entry entry = metadata.find(tag);
6258
6259 if (entry.count > 0) {
6260 /**
6261 * Already has an entry for this trigger in the request.
6262 * Rewrite it with our requested trigger value.
6263 */
6264 RequestTrigger oldTrigger = trigger;
6265
6266 oldTrigger.entryValue = entry.data.u8[0];
6267
6268 mTriggerReplacedMap.add(tag, oldTrigger);
6269 } else {
6270 /**
6271 * More typical, no trigger entry, so we just add it
6272 */
6273 mTriggerRemovedMap.add(tag, trigger);
6274 }
6275
6276 status_t res;
6277
6278 switch (trigger.getTagType()) {
6279 case TYPE_BYTE: {
6280 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6281 res = metadata.update(tag,
6282 &entryValue,
6283 /*count*/1);
6284 break;
6285 }
6286 case TYPE_INT32:
6287 res = metadata.update(tag,
6288 &trigger.entryValue,
6289 /*count*/1);
6290 break;
6291 default:
6292 ALOGE("%s: Type not supported: 0x%x",
6293 __FUNCTION__,
6294 trigger.getTagType());
6295 return INVALID_OPERATION;
6296 }
6297
6298 if (res != OK) {
6299 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6300 ", value %d", __FUNCTION__, trigger.getTagName(),
6301 trigger.entryValue);
6302 return res;
6303 }
6304
6305 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6306 trigger.getTagName(),
6307 trigger.entryValue);
6308 }
6309
6310 mTriggerMap.clear();
6311
6312 return count;
6313}
6314
6315status_t Camera3Device::RequestThread::removeTriggers(
6316 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006317 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006318 Mutex::Autolock al(mTriggerMutex);
6319
Emilian Peevaebbe412018-01-15 13:53:24 +00006320 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006321
6322 /**
6323 * Replace all old entries with their old values.
6324 */
6325 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6326 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6327
6328 status_t res;
6329
6330 uint32_t tag = trigger.metadataTag;
6331 switch (trigger.getTagType()) {
6332 case TYPE_BYTE: {
6333 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6334 res = metadata.update(tag,
6335 &entryValue,
6336 /*count*/1);
6337 break;
6338 }
6339 case TYPE_INT32:
6340 res = metadata.update(tag,
6341 &trigger.entryValue,
6342 /*count*/1);
6343 break;
6344 default:
6345 ALOGE("%s: Type not supported: 0x%x",
6346 __FUNCTION__,
6347 trigger.getTagType());
6348 return INVALID_OPERATION;
6349 }
6350
6351 if (res != OK) {
6352 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6353 ", trigger value %d", __FUNCTION__,
6354 trigger.getTagName(), trigger.entryValue);
6355 return res;
6356 }
6357 }
6358 mTriggerReplacedMap.clear();
6359
6360 /**
6361 * Remove all new entries.
6362 */
6363 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6364 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6365 status_t res = metadata.erase(trigger.metadataTag);
6366
6367 if (res != OK) {
6368 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6369 ", trigger value %d", __FUNCTION__,
6370 trigger.getTagName(), trigger.entryValue);
6371 return res;
6372 }
6373 }
6374 mTriggerRemovedMap.clear();
6375
6376 return OK;
6377}
6378
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006379status_t Camera3Device::RequestThread::addDummyTriggerIds(
6380 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006381 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006382 static const int32_t dummyTriggerId = 1;
6383 status_t res;
6384
Emilian Peevaebbe412018-01-15 13:53:24 +00006385 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006386
6387 // If AF trigger is active, insert a dummy AF trigger ID if none already
6388 // exists
6389 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6390 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6391 if (afTrigger.count > 0 &&
6392 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6393 afId.count == 0) {
6394 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6395 if (res != OK) return res;
6396 }
6397
6398 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6399 // if none already exists
6400 camera_metadata_entry pcTrigger =
6401 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6402 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6403 if (pcTrigger.count > 0 &&
6404 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6405 pcId.count == 0) {
6406 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6407 &dummyTriggerId, 1);
6408 if (res != OK) return res;
6409 }
6410
6411 return OK;
6412}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006413
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006414/**
6415 * PreparerThread inner class methods
6416 */
6417
6418Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006419 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006420 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006421}
6422
6423Camera3Device::PreparerThread::~PreparerThread() {
6424 Thread::requestExitAndWait();
6425 if (mCurrentStream != nullptr) {
6426 mCurrentStream->cancelPrepare();
6427 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6428 mCurrentStream.clear();
6429 }
6430 clear();
6431}
6432
Ruben Brunkc78ac262015-08-13 17:58:46 -07006433status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006434 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006435 status_t res;
6436
6437 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006438 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006439
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006440 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006441 if (res == OK) {
6442 // No preparation needed, fire listener right off
6443 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006444 if (listener != NULL) {
6445 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006446 }
6447 return OK;
6448 } else if (res != NOT_ENOUGH_DATA) {
6449 return res;
6450 }
6451
6452 // Need to prepare, start up thread if necessary
6453 if (!mActive) {
6454 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6455 // isn't running
6456 Thread::requestExitAndWait();
6457 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6458 if (res != OK) {
6459 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006460 if (listener != NULL) {
6461 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006462 }
6463 return res;
6464 }
6465 mCancelNow = false;
6466 mActive = true;
6467 ALOGV("%s: Preparer stream started", __FUNCTION__);
6468 }
6469
6470 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006471 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006472 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6473
6474 return OK;
6475}
6476
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006477void Camera3Device::PreparerThread::pause() {
6478 ATRACE_CALL();
6479
6480 Mutex::Autolock l(mLock);
6481
6482 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6483 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6484 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6485 int currentMaxCount = mCurrentMaxCount;
6486 mPendingStreams.clear();
6487 mCancelNow = true;
6488 while (mActive) {
6489 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6490 if (res == TIMED_OUT) {
6491 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6492 return;
6493 } else if (res != OK) {
6494 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6495 return;
6496 }
6497 }
6498
6499 //Check whether the prepare thread was able to complete the current
6500 //stream. In case work is still pending emplace it along with the rest
6501 //of the streams in the pending list.
6502 if (currentStream != nullptr) {
6503 if (!mCurrentPrepareComplete) {
6504 pendingStreams.emplace(currentMaxCount, currentStream);
6505 }
6506 }
6507
6508 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6509 for (const auto& it : mPendingStreams) {
6510 it.second->cancelPrepare();
6511 }
6512}
6513
6514status_t Camera3Device::PreparerThread::resume() {
6515 ATRACE_CALL();
6516 status_t res;
6517
6518 Mutex::Autolock l(mLock);
6519 sp<NotificationListener> listener = mListener.promote();
6520
6521 if (mActive) {
6522 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6523 return NO_INIT;
6524 }
6525
6526 auto it = mPendingStreams.begin();
6527 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006528 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006529 if (res == OK) {
6530 if (listener != NULL) {
6531 listener->notifyPrepared(it->second->getId());
6532 }
6533 it = mPendingStreams.erase(it);
6534 } else if (res != NOT_ENOUGH_DATA) {
6535 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6536 res, strerror(-res));
6537 it = mPendingStreams.erase(it);
6538 } else {
6539 it++;
6540 }
6541 }
6542
6543 if (mPendingStreams.empty()) {
6544 return OK;
6545 }
6546
6547 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6548 if (res != OK) {
6549 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6550 __FUNCTION__, res, strerror(-res));
6551 return res;
6552 }
6553 mCancelNow = false;
6554 mActive = true;
6555 ALOGV("%s: Preparer stream started", __FUNCTION__);
6556
6557 return OK;
6558}
6559
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006560status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006561 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006562 Mutex::Autolock l(mLock);
6563
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006564 for (const auto& it : mPendingStreams) {
6565 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006566 }
6567 mPendingStreams.clear();
6568 mCancelNow = true;
6569
6570 return OK;
6571}
6572
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006573void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006574 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006575 Mutex::Autolock l(mLock);
6576 mListener = listener;
6577}
6578
6579bool Camera3Device::PreparerThread::threadLoop() {
6580 status_t res;
6581 {
6582 Mutex::Autolock l(mLock);
6583 if (mCurrentStream == nullptr) {
6584 // End thread if done with work
6585 if (mPendingStreams.empty()) {
6586 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6587 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6588 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6589 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006590 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006591 return false;
6592 }
6593
6594 // Get next stream to prepare
6595 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006596 mCurrentStream = it->second;
6597 mCurrentMaxCount = it->first;
6598 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006599 mPendingStreams.erase(it);
6600 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6601 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6602 } else if (mCancelNow) {
6603 mCurrentStream->cancelPrepare();
6604 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6605 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6606 mCurrentStream.clear();
6607 mCancelNow = false;
6608 return true;
6609 }
6610 }
6611
6612 res = mCurrentStream->prepareNextBuffer();
6613 if (res == NOT_ENOUGH_DATA) return true;
6614 if (res != OK) {
6615 // Something bad happened; try to recover by cancelling prepare and
6616 // signalling listener anyway
6617 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6618 mCurrentStream->getId(), res, strerror(-res));
6619 mCurrentStream->cancelPrepare();
6620 }
6621
6622 // This stream has finished, notify listener
6623 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006624 sp<NotificationListener> listener = mListener.promote();
6625 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006626 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6627 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006628 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006629 }
6630
6631 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6632 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006633 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006634
6635 return true;
6636}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006637
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006638status_t Camera3Device::RequestBufferStateMachine::initialize(
6639 sp<camera3::StatusTracker> statusTracker) {
6640 if (statusTracker == nullptr) {
6641 ALOGE("%s: statusTracker is null", __FUNCTION__);
6642 return BAD_VALUE;
6643 }
6644
6645 std::lock_guard<std::mutex> lock(mLock);
6646 mStatusTracker = statusTracker;
6647 mRequestBufferStatusId = statusTracker->addComponent();
6648 return OK;
6649}
6650
6651bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6652 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006653 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006654 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006655 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006656 return true;
6657 }
6658 return false;
6659}
6660
6661void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6662 std::lock_guard<std::mutex> lock(mLock);
6663 if (!mRequestBufferOngoing) {
6664 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6665 return;
6666 }
6667 mRequestBufferOngoing = false;
6668 if (mStatus == RB_STATUS_PENDING_STOP) {
6669 checkSwitchToStopLocked();
6670 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006671 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006672}
6673
6674void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6675 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006676 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006677 return;
6678}
6679
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006680void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006681 std::lock_guard<std::mutex> lock(mLock);
6682 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006683 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6684 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006685 mInflightMapEmpty = false;
6686 if (mStatus == RB_STATUS_STOPPED) {
6687 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006688 }
6689 return;
6690}
6691
6692void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6693 std::lock_guard<std::mutex> lock(mLock);
6694 mRequestThreadPaused = true;
6695 if (mStatus == RB_STATUS_PENDING_STOP) {
6696 checkSwitchToStopLocked();
6697 }
6698 return;
6699}
6700
6701void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6702 std::lock_guard<std::mutex> lock(mLock);
6703 mInflightMapEmpty = true;
6704 if (mStatus == RB_STATUS_PENDING_STOP) {
6705 checkSwitchToStopLocked();
6706 }
6707 return;
6708}
6709
6710void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6711 std::lock_guard<std::mutex> lock(mLock);
6712 if (!checkSwitchToStopLocked()) {
6713 mStatus = RB_STATUS_PENDING_STOP;
6714 }
6715 return;
6716}
6717
6718void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6719 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6720 if (statusTracker != nullptr) {
6721 if (active) {
6722 statusTracker->markComponentActive(mRequestBufferStatusId);
6723 } else {
6724 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6725 }
6726 }
6727}
6728
6729bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6730 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6731 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006732 return true;
6733 }
6734 return false;
6735}
6736
Shuzhen Wang268a1362018-10-16 16:32:59 -07006737status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6738 CameraMetadata& resultMetadata) {
6739 status_t res = OK;
6740 if (!mNeedFixupMonochromeTags) {
6741 return res;
6742 }
6743
6744 // Remove tags that are not applicable to monochrome camera.
6745 int32_t tagsToRemove[] = {
6746 ANDROID_SENSOR_GREEN_SPLIT,
6747 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6748 ANDROID_COLOR_CORRECTION_MODE,
6749 ANDROID_COLOR_CORRECTION_TRANSFORM,
6750 ANDROID_COLOR_CORRECTION_GAINS,
6751 };
6752 for (auto tag : tagsToRemove) {
6753 res = resultMetadata.erase(tag);
6754 if (res != OK) {
6755 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6756 return res;
6757 }
6758 }
6759
6760 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6761 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6762 for (size_t i = 1; i < blEntry.count; i++) {
6763 blEntry.data.f[i] = blEntry.data.f[0];
6764 }
6765
6766 // ANDROID_SENSOR_NOISE_PROFILE
6767 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6768 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6769 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6770 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6771 if (res != OK) {
6772 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6773 __FUNCTION__, strerror(-res), res);
6774 return res;
6775 }
6776 }
6777
6778 // ANDROID_STATISTICS_LENS_SHADING_MAP
6779 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6780 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6781 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6782 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6783 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6784 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6785 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6786 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6787 }
6788 }
6789
6790 // ANDROID_TONEMAP_CURVE_BLUE
6791 // ANDROID_TONEMAP_CURVE_GREEN
6792 // ANDROID_TONEMAP_CURVE_RED
6793 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6794 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6795 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6796 if (tcbEntry.count > 0
6797 && tcbEntry.count == tcgEntry.count
6798 && tcbEntry.count == tcrEntry.count) {
6799 for (size_t i = 0; i < tcbEntry.count; i++) {
6800 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6801 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6802 }
6803 }
6804
6805 return res;
6806}
6807
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006808}; // namespace android