blob: 4227a3b9de263aeb16ab13e6d6dffa20f4515c18 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080052#include <android/hardware/camera2/ICameraDeviceUser.h>
53
Igor Murashkinff3e31d2013-10-23 16:40:06 -070054#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070055#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070056#include "device3/Camera3Device.h"
57#include "device3/Camera3OutputStream.h"
58#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070059#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070060#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070061#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070062#include "utils/CameraThreadState.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080063
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080064#include <tuple>
65
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080066using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080067using namespace android::hardware::camera;
68using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080069
70namespace android {
71
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080072Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080073 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080074 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070075 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070076 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070077 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070078 mUsePartialResult(false),
79 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080080 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070081 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070082 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070083 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070084 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070085 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070086 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000087 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010088 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070089 mLastTemplateId(-1),
90 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080091{
92 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080093 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080094}
95
96Camera3Device::~Camera3Device()
97{
98 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080099 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700100 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800101}
102
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800103const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800104 return mId;
105}
106
Emilian Peevbd8c5032018-02-14 23:05:40 +0000107status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800108 ATRACE_CALL();
109 Mutex::Autolock il(mInterfaceLock);
110 Mutex::Autolock l(mLock);
111
112 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
113 if (mStatus != STATUS_UNINITIALIZED) {
114 CLOGE("Already initialized!");
115 return INVALID_OPERATION;
116 }
117 if (manager == nullptr) return INVALID_OPERATION;
118
119 sp<ICameraDeviceSession> session;
120 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800121 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800122 /*out*/ &session);
123 ATRACE_END();
124 if (res != OK) {
125 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
126 return res;
127 }
128
Steven Moreland5ff9c912017-03-09 23:13:00 -0800129 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800130 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700131 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800132 session->close();
133 return res;
134 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800135
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700136 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700137 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700138 if (isLogical) {
139 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700140 res = manager->getCameraCharacteristics(
141 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700142 if (res != OK) {
143 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
144 physicalId.c_str(), strerror(-res), res);
145 session->close();
146 return res;
147 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700148
149 if (DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId])) {
150 mDistortionMappers[physicalId].setupStaticInfo(mPhysicalDeviceInfoMap[physicalId]);
151 if (res != OK) {
152 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
153 "correction", physicalId.c_str());
154 session->close();
155 return res;
156 }
157 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700158 }
159 }
160
Yifan Hongf79b5542017-04-11 14:44:25 -0700161 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700162 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
163 [&queue](const auto& descriptor) {
164 queue = std::make_shared<RequestMetadataQueue>(descriptor);
165 if (!queue->isValid() || queue->availableToWrite() <= 0) {
166 ALOGE("HAL returns empty request metadata fmq, not use it");
167 queue = nullptr;
168 // don't use the queue onwards.
169 }
170 });
171 if (!requestQueueRet.isOk()) {
172 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
173 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700174 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700175 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700176
177 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700178 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700179 [&resQueue](const auto& descriptor) {
180 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
181 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700182 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700183 resQueue = nullptr;
184 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700185 }
186 });
187 if (!resultQueueRet.isOk()) {
188 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
189 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700190 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700191 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700192 IF_ALOGV() {
193 session->interfaceChain([](
194 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
195 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800196 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700197 ALOGV(" %s", iface.c_str());
198 }
199 });
200 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700201
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800202 camera_metadata_entry bufMgrMode =
203 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
204 if (bufMgrMode.count > 0) {
205 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
206 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
207 }
208
209 mInterface = new HalInterface(session, queue, mUseHalBufManager);
Emilian Peev71c73a22017-03-21 16:35:51 +0000210 std::string providerType;
211 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000212 mTagMonitor.initialize(mVendorTagId);
213 if (!monitorTags.isEmpty()) {
214 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
215 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800216
Shuzhen Wang268a1362018-10-16 16:32:59 -0700217 // Metadata tags needs fixup for monochrome camera device version less
218 // than 3.5.
219 hardware::hidl_version maxVersion{0,0};
220 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
221 if (res != OK) {
222 ALOGE("%s: Error in getting camera device version id: %s (%d)",
223 __FUNCTION__, strerror(-res), res);
224 return res;
225 }
226 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
227 maxVersion.get_major(), maxVersion.get_minor());
228
229 bool isMonochrome = false;
230 camera_metadata_entry_t entry = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
231 for (size_t i = 0; i < entry.count; i++) {
232 uint8_t capability = entry.data.u8[i];
233 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
234 isMonochrome = true;
235 }
236 }
237 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
238
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800239 return initializeCommonLocked();
240}
241
242status_t Camera3Device::initializeCommonLocked() {
243
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700244 /** Start up status tracker thread */
245 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800246 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700247 if (res != OK) {
248 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
249 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800250 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700251 mStatusTracker.clear();
252 return res;
253 }
254
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700255 /** Register in-flight map to the status tracker */
256 mInFlightStatusId = mStatusTracker->addComponent();
257
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700258 if (mUseHalBufManager) {
259 res = mRequestBufferSM.initialize(mStatusTracker);
260 if (res != OK) {
261 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
262 strerror(-res), res);
263 mInterface->close();
264 mStatusTracker.clear();
265 return res;
266 }
267 }
268
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800269 /** Create buffer manager */
270 mBufferManager = new Camera3BufferManager();
271
272 Vector<int32_t> sessionParamKeys;
273 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
274 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
275 if (sessionKeysEntry.count > 0) {
276 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
277 }
278
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700279 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700280 mRequestThread = new RequestThread(
281 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800282 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800283 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700284 SET_ERR_L("Unable to start request queue thread: %s (%d)",
285 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800286 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800287 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800288 return res;
289 }
290
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700291 mPreparerThread = new PreparerThread();
292
Ruben Brunk183f0562015-08-12 12:55:02 -0700293 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800294 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700295 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700296 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700297 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800298
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800299 // Measure the clock domain offset between camera and video/hw_composer
300 camera_metadata_entry timestampSource =
301 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
302 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
303 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
304 mTimestampOffset = getMonoToBoottimeOffset();
305 }
306
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700307 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100308 camera_metadata_entry partialResultsCount =
309 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
310 if (partialResultsCount.count > 0) {
311 mNumPartialResults = partialResultsCount.data.i32[0];
312 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700313 }
314
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700315 camera_metadata_entry configs =
316 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
317 for (uint32_t i = 0; i < configs.count; i += 4) {
318 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
319 configs.data.i32[i + 3] ==
320 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
321 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
322 configs.data.i32[i + 2]));
323 }
324 }
325
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700326 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700327 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700328 if (res != OK) {
329 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
330 return res;
331 }
332 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800333 return OK;
334}
335
336status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700337 return disconnectImpl();
338}
339
340status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800341 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700342 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800343
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700344 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800345
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700346 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700347 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700348 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700349 {
350 Mutex::Autolock l(mLock);
351 if (mStatus == STATUS_UNINITIALIZED) return res;
352
353 if (mStatus == STATUS_ACTIVE ||
354 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
355 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700356 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700357 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700358 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700359 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700360 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700361 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700362 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
363 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700364 // Continue to close device even in case of error
365 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700366 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800367 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800368
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700369 if (mStatus == STATUS_ERROR) {
370 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700371 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700372
373 if (mStatusTracker != NULL) {
374 mStatusTracker->requestExit();
375 }
376
377 if (mRequestThread != NULL) {
378 mRequestThread->requestExit();
379 }
380
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700381 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
382 for (size_t i = 0; i < mOutputStreams.size(); i++) {
383 streams.push_back(mOutputStreams[i]);
384 }
385 if (mInputStream != nullptr) {
386 streams.push_back(mInputStream);
387 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700388 }
389
390 // Joining done without holding mLock, otherwise deadlocks may ensue
391 // as the threads try to access parent state
392 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
393 // HAL may be in a bad state, so waiting for request thread
394 // (which may be stuck in the HAL processCaptureRequest call)
395 // could be dangerous.
396 mRequestThread->join();
397 }
398
399 if (mStatusTracker != NULL) {
400 mStatusTracker->join();
401 }
402
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800403 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700404 {
405 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800406 mRequestThread.clear();
Emilian Peev2843c362018-09-26 08:49:40 +0100407 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700408 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800409 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700410 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800411
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700412 // Call close without internal mutex held, as the HAL close may need to
413 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800414 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700415
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700416 flushInflightRequests();
417
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700418 {
419 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800420 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700421 mOutputStreams.clear();
422 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700423 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700424 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700425 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700426 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800427
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700428 for (auto& weakStream : streams) {
429 sp<Camera3StreamInterface> stream = weakStream.promote();
430 if (stream != nullptr) {
431 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
432 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
433 }
434 }
435
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700436 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700437 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800438}
439
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700440// For dumping/debugging only -
441// try to acquire a lock a few times, eventually give up to proceed with
442// debug/dump operations
443bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
444 bool gotLock = false;
445 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
446 if (lock.tryLock() == NO_ERROR) {
447 gotLock = true;
448 break;
449 } else {
450 usleep(kDumpSleepDuration);
451 }
452 }
453 return gotLock;
454}
455
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700456Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
457 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100458 const int STREAM_CONFIGURATION_SIZE = 4;
459 const int STREAM_FORMAT_OFFSET = 0;
460 const int STREAM_WIDTH_OFFSET = 1;
461 const int STREAM_HEIGHT_OFFSET = 2;
462 const int STREAM_IS_INPUT_OFFSET = 3;
463 camera_metadata_ro_entry_t availableStreamConfigs =
464 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
465 if (availableStreamConfigs.count == 0 ||
466 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
467 return Size(0, 0);
468 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700469
Emilian Peev08dd2452017-04-06 16:55:14 +0100470 // Get max jpeg size (area-wise).
471 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
472 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
473 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
474 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
475 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
476 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
477 && format == HAL_PIXEL_FORMAT_BLOB &&
478 (width * height > maxJpegWidth * maxJpegHeight)) {
479 maxJpegWidth = width;
480 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700481 }
482 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100483
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700484 return Size(maxJpegWidth, maxJpegHeight);
485}
486
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800487nsecs_t Camera3Device::getMonoToBoottimeOffset() {
488 // try three times to get the clock offset, choose the one
489 // with the minimum gap in measurements.
490 const int tries = 3;
491 nsecs_t bestGap, measured;
492 for (int i = 0; i < tries; ++i) {
493 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
494 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
495 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
496 const nsecs_t gap = tmono2 - tmono;
497 if (i == 0 || gap < bestGap) {
498 bestGap = gap;
499 measured = tbase - ((tmono + tmono2) >> 1);
500 }
501 }
502 return measured;
503}
504
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800505hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
506 int frameworkFormat) {
507 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
508}
509
510DataspaceFlags Camera3Device::mapToHidlDataspace(
511 android_dataspace dataSpace) {
512 return dataSpace;
513}
514
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700515BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100516 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700517 return usage;
518}
519
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800520StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
521 switch (rotation) {
522 case CAMERA3_STREAM_ROTATION_0:
523 return StreamRotation::ROTATION_0;
524 case CAMERA3_STREAM_ROTATION_90:
525 return StreamRotation::ROTATION_90;
526 case CAMERA3_STREAM_ROTATION_180:
527 return StreamRotation::ROTATION_180;
528 case CAMERA3_STREAM_ROTATION_270:
529 return StreamRotation::ROTATION_270;
530 }
531 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
532 return StreamRotation::ROTATION_0;
533}
534
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800535status_t Camera3Device::mapToStreamConfigurationMode(
536 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
537 if (mode == nullptr) return BAD_VALUE;
538 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
539 switch(operationMode) {
540 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
541 *mode = StreamConfigurationMode::NORMAL_MODE;
542 break;
543 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
544 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
545 break;
546 default:
547 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
548 return BAD_VALUE;
549 }
550 } else {
551 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800552 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800553 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800554}
555
556camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
557 switch (status) {
558 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
559 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
560 }
561 return CAMERA3_BUFFER_STATUS_ERROR;
562}
563
564int Camera3Device::mapToFrameworkFormat(
565 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
566 return static_cast<uint32_t>(pixelFormat);
567}
568
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700569android_dataspace Camera3Device::mapToFrameworkDataspace(
570 DataspaceFlags dataSpace) {
571 return static_cast<android_dataspace>(dataSpace);
572}
573
Emilian Peev050f5dc2017-05-18 14:43:56 +0100574uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700575 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700576 return usage;
577}
578
Emilian Peev050f5dc2017-05-18 14:43:56 +0100579uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700580 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700581 return usage;
582}
583
Zhijun Hef7da0962014-04-24 13:27:56 -0700584ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700585 // Get max jpeg size (area-wise).
586 Size maxJpegResolution = getMaxJpegResolution();
587 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800588 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
589 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700590 return BAD_VALUE;
591 }
592
Zhijun Hef7da0962014-04-24 13:27:56 -0700593 // Get max jpeg buffer size
594 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700595 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
596 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800597 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
598 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700599 return BAD_VALUE;
600 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700601 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800602 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700603
604 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700605 float scaleFactor = ((float) (width * height)) /
606 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800607 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
608 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700609 if (jpegBufferSize > maxJpegBufferSize) {
610 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700611 }
612
613 return jpegBufferSize;
614}
615
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700616ssize_t Camera3Device::getPointCloudBufferSize() const {
617 const int FLOATS_PER_POINT=4;
618 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
619 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800620 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
621 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700622 return BAD_VALUE;
623 }
624 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
625 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
626 return maxBytesForPointCloud;
627}
628
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800629ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800630 const int PER_CONFIGURATION_SIZE = 3;
631 const int WIDTH_OFFSET = 0;
632 const int HEIGHT_OFFSET = 1;
633 const int SIZE_OFFSET = 2;
634 camera_metadata_ro_entry rawOpaqueSizes =
635 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800636 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800637 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800638 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
639 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800640 return BAD_VALUE;
641 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700642
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800643 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
644 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
645 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
646 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
647 }
648 }
649
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800650 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
651 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800652 return BAD_VALUE;
653}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700654
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800655status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
656 ATRACE_CALL();
657 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700658
659 // Try to lock, but continue in case of failure (to avoid blocking in
660 // deadlocks)
661 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
662 bool gotLock = tryLockSpinRightRound(mLock);
663
664 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800665 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
666 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700667 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800668 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
669 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700670
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800671 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700672
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800673 String16 templatesOption("-t");
674 int n = args.size();
675 for (int i = 0; i < n; i++) {
676 if (args[i] == templatesOption) {
677 dumpTemplates = true;
678 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000679 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700680 if (i + 1 < n) {
681 String8 monitorTags = String8(args[i + 1]);
682 if (monitorTags == "off") {
683 mTagMonitor.disableMonitoring();
684 } else {
685 mTagMonitor.parseTagsToMonitor(monitorTags);
686 }
687 } else {
688 mTagMonitor.disableMonitoring();
689 }
690 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800691 }
692
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800693 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800694
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800695 const char *status =
696 mStatus == STATUS_ERROR ? "ERROR" :
697 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700698 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
699 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800700 mStatus == STATUS_ACTIVE ? "ACTIVE" :
701 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700702
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800703 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700704 if (mStatus == STATUS_ERROR) {
705 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
706 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800707 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800708 const char *mode =
709 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
710 mOperatingMode == static_cast<int>(
711 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
712 "CUSTOM";
713 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800714
715 if (mInputStream != NULL) {
716 write(fd, lines.string(), lines.size());
717 mInputStream->dump(fd, args);
718 } else {
719 lines.appendFormat(" No input stream.\n");
720 write(fd, lines.string(), lines.size());
721 }
722 for (size_t i = 0; i < mOutputStreams.size(); i++) {
723 mOutputStreams[i]->dump(fd,args);
724 }
725
Zhijun He431503c2016-03-07 17:30:16 -0800726 if (mBufferManager != NULL) {
727 lines = String8(" Camera3 Buffer Manager:\n");
728 write(fd, lines.string(), lines.size());
729 mBufferManager->dump(fd, args);
730 }
Zhijun He125684a2015-12-26 15:07:30 -0800731
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700732 lines = String8(" In-flight requests:\n");
733 if (mInFlightMap.size() == 0) {
734 lines.append(" None\n");
735 } else {
736 for (size_t i = 0; i < mInFlightMap.size(); i++) {
737 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700738 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700739 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800740 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700741 r.numBuffersLeft);
742 }
743 }
744 write(fd, lines.string(), lines.size());
745
Shuzhen Wang686f6442017-06-20 16:16:04 -0700746 if (mRequestThread != NULL) {
747 mRequestThread->dumpCaptureRequestLatency(fd,
748 " ProcessCaptureRequest latency histogram:");
749 }
750
Igor Murashkin1e479c02013-09-06 16:55:14 -0700751 {
752 lines = String8(" Last request sent:\n");
753 write(fd, lines.string(), lines.size());
754
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700755 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700756 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
757 }
758
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800759 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800760 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800761 "TEMPLATE_PREVIEW",
762 "TEMPLATE_STILL_CAPTURE",
763 "TEMPLATE_VIDEO_RECORD",
764 "TEMPLATE_VIDEO_SNAPSHOT",
765 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800766 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800767 };
768
769 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800770 camera_metadata_t *templateRequest = nullptr;
771 mInterface->constructDefaultRequestSettings(
772 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800773 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800774 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800775 lines.append(" Not supported\n");
776 write(fd, lines.string(), lines.size());
777 } else {
778 write(fd, lines.string(), lines.size());
779 dump_indented_camera_metadata(templateRequest,
780 fd, /*verbosity*/2, /*indentation*/8);
781 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800782 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800783 }
784 }
785
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700786 mTagMonitor.dumpMonitoredMetadata(fd);
787
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800788 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800789 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800790 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800791 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800792 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800793
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700794 if (gotLock) mLock.unlock();
795 if (gotInterfaceLock) mInterfaceLock.unlock();
796
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800797 return OK;
798}
799
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700800const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800801 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800802 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
803 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700804 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800805 mStatus == STATUS_ERROR ?
806 "when in error state" : "before init");
807 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700808 if (physicalId.isEmpty()) {
809 return mDeviceInfo;
810 } else {
811 std::string id(physicalId.c_str());
812 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
813 return mPhysicalDeviceInfoMap.at(id);
814 } else {
815 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
816 return mDeviceInfo;
817 }
818 }
819}
820
821const CameraMetadata& Camera3Device::info() const {
822 String8 emptyId;
823 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800824}
825
Jianing Wei90e59c92014-03-12 18:29:36 -0700826status_t Camera3Device::checkStatusOkToCaptureLocked() {
827 switch (mStatus) {
828 case STATUS_ERROR:
829 CLOGE("Device has encountered a serious error");
830 return INVALID_OPERATION;
831 case STATUS_UNINITIALIZED:
832 CLOGE("Device not initialized");
833 return INVALID_OPERATION;
834 case STATUS_UNCONFIGURED:
835 case STATUS_CONFIGURED:
836 case STATUS_ACTIVE:
837 // OK
838 break;
839 default:
840 SET_ERR_L("Unexpected status: %d", mStatus);
841 return INVALID_OPERATION;
842 }
843 return OK;
844}
845
846status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000847 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700848 const std::list<const SurfaceMap> &surfaceMaps,
849 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700850 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700851 if (requestList == NULL) {
852 CLOGE("requestList cannot be NULL.");
853 return BAD_VALUE;
854 }
855
Jianing Weicb0652e2014-03-12 18:29:36 -0700856 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000857 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
859 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
860 ++metadataIt, ++surfaceMapIt) {
861 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700862 if (newRequest == 0) {
863 CLOGE("Can't create capture request");
864 return BAD_VALUE;
865 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700866
Shuzhen Wang9d066012016-09-30 11:30:20 -0700867 newRequest->mRepeating = repeating;
868
Jianing Weicb0652e2014-03-12 18:29:36 -0700869 // Setup burst Id and request Id
870 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000871 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
872 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700873 CLOGE("RequestID entry exists; but must not be empty in metadata");
874 return BAD_VALUE;
875 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000876 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
877 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700878 } else {
879 CLOGE("RequestID does not exist in metadata");
880 return BAD_VALUE;
881 }
882
Jianing Wei90e59c92014-03-12 18:29:36 -0700883 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700884
885 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700886 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700887 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
888 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
889 return BAD_VALUE;
890 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700891
892 // Setup batch size if this is a high speed video recording request.
893 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
894 auto firstRequest = requestList->begin();
895 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
896 if (outputStream->isVideoStream()) {
897 (*firstRequest)->mBatchSize = requestList->size();
898 break;
899 }
900 }
901 }
902
Jianing Wei90e59c92014-03-12 18:29:36 -0700903 return OK;
904}
905
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800906status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800907 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800908
Emilian Peevaebbe412018-01-15 13:53:24 +0000909 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700910 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000911 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700912
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800913 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700914}
915
Emilian Peevaebbe412018-01-15 13:53:24 +0000916void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700917 std::list<const SurfaceMap>& surfaceMaps,
918 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000919 PhysicalCameraSettingsList requestList;
920 requestList.push_back({std::string(getId().string()), request});
921 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700922
923 SurfaceMap surfaceMap;
924 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
925 // With no surface list passed in, stream and surface will have 1-to-1
926 // mapping. So the surface index is 0 for each stream in the surfaceMap.
927 for (size_t i = 0; i < streams.count; i++) {
928 surfaceMap[streams.data.i32[i]].push_back(0);
929 }
930 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800931}
932
Jianing Wei90e59c92014-03-12 18:29:36 -0700933status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000934 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700935 const std::list<const SurfaceMap> &surfaceMaps,
936 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700937 /*out*/
938 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700939 ATRACE_CALL();
940 Mutex::Autolock il(mInterfaceLock);
941 Mutex::Autolock l(mLock);
942
943 status_t res = checkStatusOkToCaptureLocked();
944 if (res != OK) {
945 // error logged by previous call
946 return res;
947 }
948
949 RequestList requestList;
950
Shuzhen Wang0129d522016-10-30 22:43:41 -0700951 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
952 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700953 if (res != OK) {
954 // error logged by previous call
955 return res;
956 }
957
958 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700959 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700960 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700961 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700962 }
963
964 if (res == OK) {
965 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
966 if (res != OK) {
967 SET_ERR_L("Can't transition to active in %f seconds!",
968 kActiveTimeout/1e9);
969 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800970 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700971 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700972 } else {
973 CLOGE("Cannot queue request. Impossible.");
974 return BAD_VALUE;
975 }
976
977 return res;
978}
979
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700980hardware::Return<void> Camera3Device::requestStreamBuffers(
981 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
982 requestStreamBuffers_cb _hidl_cb) {
983 using hardware::camera::device::V3_5::BufferRequestStatus;
984 using hardware::camera::device::V3_5::StreamBufferRet;
985 using hardware::camera::device::V3_5::StreamBufferRequestError;
986
987 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
988
989 hardware::hidl_vec<StreamBufferRet> bufRets;
990 if (!mUseHalBufManager) {
991 ALOGE("%s: Camera %s does not support HAL buffer management",
992 __FUNCTION__, mId.string());
993 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
994 return hardware::Void();
995 }
996
997 SortedVector<int32_t> streamIds;
998 ssize_t sz = streamIds.setCapacity(bufReqs.size());
999 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
1000 ALOGE("%s: failed to allocate memory for %zu buffer requests",
1001 __FUNCTION__, bufReqs.size());
1002 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1003 return hardware::Void();
1004 }
1005
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001006 if (bufReqs.size() > mOutputStreams.size()) {
1007 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
1008 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
1009 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1010 return hardware::Void();
1011 }
1012
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001013 // Check for repeated streamId
1014 for (const auto& bufReq : bufReqs) {
1015 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
1016 ALOGE("%s: Stream %d appear multiple times in buffer requests",
1017 __FUNCTION__, bufReq.streamId);
1018 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1019 return hardware::Void();
1020 }
1021 streamIds.add(bufReq.streamId);
1022 }
1023
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001024 if (!mRequestBufferSM.startRequestBuffer()) {
1025 ALOGE("%s: request buffer disallowed while camera service is configuring",
1026 __FUNCTION__);
1027 _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001028 return hardware::Void();
1029 }
1030
1031 bufRets.resize(bufReqs.size());
1032
1033 bool allReqsSucceeds = true;
1034 bool oneReqSucceeds = false;
1035 for (size_t i = 0; i < bufReqs.size(); i++) {
1036 const auto& bufReq = bufReqs[i];
1037 auto& bufRet = bufRets[i];
1038 int32_t streamId = bufReq.streamId;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001039 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
1040 if (outputStream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001041 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
1042 hardware::hidl_vec<StreamBufferRet> emptyBufRets;
1043 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001044 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001045 return hardware::Void();
1046 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001047
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001048 if (outputStream->isAbandoned()) {
1049 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1050 allReqsSucceeds = false;
1051 continue;
1052 }
1053
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001054 bufRet.streamId = streamId;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001055 size_t handOutBufferCount = outputStream->getOutstandingBuffersCount();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001056 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001057 size_t totalHandout = handOutBufferCount + numBuffersRequested;
1058 uint32_t maxBuffers = outputStream->asHalStream()->max_buffers;
1059 if (totalHandout > maxBuffers) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001060 // Not able to allocate enough buffer. Exit early for this stream
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001061 ALOGE("%s: request too much buffers for stream %d: at HAL: %zu + requesting: %d"
1062 " > max: %d", __FUNCTION__, streamId, handOutBufferCount,
1063 numBuffersRequested, maxBuffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001064 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1065 allReqsSucceeds = false;
1066 continue;
1067 }
1068
1069 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1070 bool currentReqSucceeds = true;
1071 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1072 size_t numAllocatedBuffers = 0;
1073 size_t numPushedInflightBuffers = 0;
1074 for (size_t b = 0; b < numBuffersRequested; b++) {
1075 camera3_stream_buffer_t& sb = streamBuffers[b];
1076 // Since this method can run concurrently with request thread
1077 // We need to update the wait duration everytime we call getbuffer
1078 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1079 status_t res = outputStream->getBuffer(&sb, waitDuration);
1080 if (res != OK) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001081 if (res == NO_INIT || res == DEAD_OBJECT) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001082 ALOGV("%s: Can't get output buffer for stream %d: %s (%d)",
1083 __FUNCTION__, streamId, strerror(-res), res);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001084 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001085 } else {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001086 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1087 __FUNCTION__, streamId, strerror(-res), res);
1088 if (res == TIMED_OUT || res == NO_MEMORY) {
1089 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1090 } else {
1091 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1092 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001093 }
1094 currentReqSucceeds = false;
1095 break;
1096 }
1097 numAllocatedBuffers++;
1098
1099 buffer_handle_t *buffer = sb.buffer;
1100 auto pair = mInterface->getBufferId(*buffer, streamId);
1101 bool isNewBuffer = pair.first;
1102 uint64_t bufferId = pair.second;
1103 StreamBuffer& hBuf = tmpRetBuffers[b];
1104
1105 hBuf.streamId = streamId;
1106 hBuf.bufferId = bufferId;
1107 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1108 hBuf.status = BufferStatus::OK;
1109 hBuf.releaseFence = nullptr;
1110
1111 native_handle_t *acquireFence = nullptr;
1112 if (sb.acquire_fence != -1) {
1113 acquireFence = native_handle_create(1,0);
1114 acquireFence->data[0] = sb.acquire_fence;
1115 }
1116 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1117 hBuf.releaseFence = nullptr;
1118
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08001119 res = mInterface->pushInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001120 if (res != OK) {
1121 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1122 __FUNCTION__, streamId, strerror(-res), res);
1123 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1124 currentReqSucceeds = false;
1125 break;
1126 }
1127 numPushedInflightBuffers++;
1128 }
1129 if (currentReqSucceeds) {
1130 bufRet.val.buffers(std::move(tmpRetBuffers));
1131 oneReqSucceeds = true;
1132 } else {
1133 allReqsSucceeds = false;
1134 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1135 StreamBuffer& hBuf = tmpRetBuffers[b];
1136 buffer_handle_t* buffer;
1137 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1138 if (res != OK) {
1139 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1140 __FUNCTION__, streamId, strerror(-res), res);
1141 }
1142 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001143 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1144 camera3_stream_buffer_t& sb = streamBuffers[b];
1145 sb.acquire_fence = -1;
1146 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1147 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001148 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1149 }
1150 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001151
1152 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1153 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1154 BufferRequestStatus::FAILED_UNKNOWN,
1155 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001156 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001157 return hardware::Void();
1158}
1159
1160hardware::Return<void> Camera3Device::returnStreamBuffers(
1161 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1162 if (!mUseHalBufManager) {
1163 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1164 __FUNCTION__, mId.string());
1165 return hardware::Void();
1166 }
1167
1168 for (const auto& buf : buffers) {
1169 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1170 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1171 continue;
1172 }
1173
1174 buffer_handle_t* buffer;
1175 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1176
1177 if (res != OK) {
1178 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1179 __FUNCTION__, buf.bufferId, buf.streamId);
1180 continue;
1181 }
1182
1183 camera3_stream_buffer_t streamBuffer;
1184 streamBuffer.buffer = buffer;
1185 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1186 streamBuffer.acquire_fence = -1;
1187 streamBuffer.release_fence = -1;
1188
1189 if (buf.releaseFence == nullptr) {
1190 streamBuffer.release_fence = -1;
1191 } else if (buf.releaseFence->numFds == 1) {
1192 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1193 } else {
1194 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1195 __FUNCTION__, buf.releaseFence->numFds);
1196 continue;
1197 }
1198
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001199 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1200 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001201 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1202 continue;
1203 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001204 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001205 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1206 }
1207 return hardware::Void();
1208}
1209
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001210hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001211 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001212 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001213 // Ideally we should grab mLock, but that can lead to deadlock, and
1214 // it's not super important to get up to date value of mStatus for this
1215 // warning print, hence skipping the lock here
1216 if (mStatus == STATUS_ERROR) {
1217 // Per API contract, HAL should act as closed after device error
1218 // But mStatus can be set to error by framework as well, so just log
1219 // a warning here.
1220 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001221 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001222
1223 if (mProcessCaptureResultLock.tryLock() != OK) {
1224 // This should never happen; it indicates a wrong client implementation
1225 // that doesn't follow the contract. But, we can be tolerant here.
1226 ALOGE("%s: callback overlapped! waiting 1s...",
1227 __FUNCTION__);
1228 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1229 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1230 __FUNCTION__);
1231 // really don't know what to do, so bail out.
1232 return hardware::Void();
1233 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001234 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001235 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001236 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001237 }
1238 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001239 return hardware::Void();
1240}
1241
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001242// Only one processCaptureResult should be called at a time, so
1243// the locks won't block. The locks are present here simply to enforce this.
1244hardware::Return<void> Camera3Device::processCaptureResult(
1245 const hardware::hidl_vec<
1246 hardware::camera::device::V3_2::CaptureResult>& results) {
1247 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1248
1249 // Ideally we should grab mLock, but that can lead to deadlock, and
1250 // it's not super important to get up to date value of mStatus for this
1251 // warning print, hence skipping the lock here
1252 if (mStatus == STATUS_ERROR) {
1253 // Per API contract, HAL should act as closed after device error
1254 // But mStatus can be set to error by framework as well, so just log
1255 // a warning here.
1256 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1257 }
1258
1259 if (mProcessCaptureResultLock.tryLock() != OK) {
1260 // This should never happen; it indicates a wrong client implementation
1261 // that doesn't follow the contract. But, we can be tolerant here.
1262 ALOGE("%s: callback overlapped! waiting 1s...",
1263 __FUNCTION__);
1264 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1265 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1266 __FUNCTION__);
1267 // really don't know what to do, so bail out.
1268 return hardware::Void();
1269 }
1270 }
1271 for (const auto& result : results) {
1272 processOneCaptureResultLocked(result, noPhysMetadata);
1273 }
1274 mProcessCaptureResultLock.unlock();
1275 return hardware::Void();
1276}
1277
1278status_t Camera3Device::readOneCameraMetadataLocked(
1279 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1280 const hardware::camera::device::V3_2::CameraMetadata& result) {
1281 if (fmqResultSize > 0) {
1282 resultMetadata.resize(fmqResultSize);
1283 if (mResultMetadataQueue == nullptr) {
1284 return NO_MEMORY; // logged in initialize()
1285 }
1286 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1287 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1288 __FUNCTION__, fmqResultSize);
1289 return INVALID_OPERATION;
1290 }
1291 } else {
1292 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1293 result.size());
1294 }
1295
1296 if (resultMetadata.size() != 0) {
1297 status_t res;
1298 const camera_metadata_t* metadata =
1299 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1300 size_t expected_metadata_size = resultMetadata.size();
1301 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1302 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1303 __FUNCTION__, strerror(-res), res);
1304 return INVALID_OPERATION;
1305 }
1306 }
1307
1308 return OK;
1309}
1310
Yifan Honga640c5a2017-04-12 16:30:31 -07001311void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001312 const hardware::camera::device::V3_2::CaptureResult& result,
1313 const hardware::hidl_vec<
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001314 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadata) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001315 camera3_capture_result r;
1316 status_t res;
1317 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001318
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001319 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001320 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001321 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1322 if (res != OK) {
1323 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1324 __FUNCTION__, result.frameNumber);
1325 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001326 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001327 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001328
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001329 // Read and validate physical camera metadata
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001330 size_t physResultCount = physicalCameraMetadata.size();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001331 std::vector<const char*> physCamIds(physResultCount);
1332 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1333 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1334 physResultMetadata.resize(physResultCount);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001335 for (size_t i = 0; i < physicalCameraMetadata.size(); i++) {
1336 res = readOneCameraMetadataLocked(physicalCameraMetadata[i].fmqMetadataSize,
1337 physResultMetadata[i], physicalCameraMetadata[i].metadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001338 if (res != OK) {
1339 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1340 __FUNCTION__, result.frameNumber,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001341 physicalCameraMetadata[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001342 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001343 }
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001344 physCamIds[i] = physicalCameraMetadata[i].physicalCameraId.c_str();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001345 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1346 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001347 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001348 r.num_physcam_metadata = physResultCount;
1349 r.physcam_ids = physCamIds.data();
1350 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001351
1352 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1353 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1354 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1355 auto& bDst = outputBuffers[i];
1356 const StreamBuffer &bSrc = result.outputBuffers[i];
1357
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001358 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1359 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001360 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1361 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001362 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001363 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001364 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001365
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001366 bool noBufferReturned = false;
1367 buffer_handle_t *buffer = nullptr;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001368 if (mUseHalBufManager) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001369 // This is suspicious most of the time but can be correct during flush where HAL
1370 // has to return capture result before a buffer is requested
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001371 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001372 if (bSrc.status == BufferStatus::OK) {
1373 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1374 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1375 // Still proceeds so other buffers can be returned
1376 }
1377 noBufferReturned = true;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001378 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001379 if (noBufferReturned) {
1380 res = OK;
1381 } else {
1382 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1383 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001384 } else {
1385 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1386 }
1387
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001388 if (res != OK) {
1389 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1390 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001391 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001392 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001393
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001394 bDst.buffer = buffer;
1395 bDst.status = mapHidlBufferStatus(bSrc.status);
1396 bDst.acquire_fence = -1;
1397 if (bSrc.releaseFence == nullptr) {
1398 bDst.release_fence = -1;
1399 } else if (bSrc.releaseFence->numFds == 1) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001400 if (noBufferReturned) {
1401 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
1402 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001403 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1404 } else {
1405 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1406 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001407 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001408 }
1409 }
1410 r.num_output_buffers = outputBuffers.size();
1411 r.output_buffers = outputBuffers.data();
1412
1413 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001414 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001415 r.input_buffer = nullptr;
1416 } else {
1417 if (mInputStream->getId() != result.inputBuffer.streamId) {
1418 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1419 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001420 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001421 }
1422 inputBuffer.stream = mInputStream->asHalStream();
1423 buffer_handle_t *buffer;
1424 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1425 &buffer);
1426 if (res != OK) {
1427 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1428 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001429 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001430 }
1431 inputBuffer.buffer = buffer;
1432 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1433 inputBuffer.acquire_fence = -1;
1434 if (result.inputBuffer.releaseFence == nullptr) {
1435 inputBuffer.release_fence = -1;
1436 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1437 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1438 } else {
1439 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1440 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001441 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001442 }
1443 r.input_buffer = &inputBuffer;
1444 }
1445
1446 r.partial_result = result.partialResult;
1447
1448 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001449}
1450
1451hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001452 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001453 // Ideally we should grab mLock, but that can lead to deadlock, and
1454 // it's not super important to get up to date value of mStatus for this
1455 // warning print, hence skipping the lock here
1456 if (mStatus == STATUS_ERROR) {
1457 // Per API contract, HAL should act as closed after device error
1458 // But mStatus can be set to error by framework as well, so just log
1459 // a warning here.
1460 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001461 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001462
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001463 for (const auto& msg : msgs) {
1464 notify(msg);
1465 }
1466 return hardware::Void();
1467}
1468
1469void Camera3Device::notify(
1470 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1471
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001472 camera3_notify_msg m;
1473 switch (msg.type) {
1474 case MsgType::ERROR:
1475 m.type = CAMERA3_MSG_ERROR;
1476 m.message.error.frame_number = msg.msg.error.frameNumber;
1477 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001478 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1479 if (stream == nullptr) {
1480 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1481 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001482 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001483 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001484 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001485 } else {
1486 m.message.error.error_stream = nullptr;
1487 }
1488 switch (msg.msg.error.errorCode) {
1489 case ErrorCode::ERROR_DEVICE:
1490 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1491 break;
1492 case ErrorCode::ERROR_REQUEST:
1493 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1494 break;
1495 case ErrorCode::ERROR_RESULT:
1496 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1497 break;
1498 case ErrorCode::ERROR_BUFFER:
1499 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1500 break;
1501 }
1502 break;
1503 case MsgType::SHUTTER:
1504 m.type = CAMERA3_MSG_SHUTTER;
1505 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1506 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1507 break;
1508 }
1509 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001510}
1511
Emilian Peevaebbe412018-01-15 13:53:24 +00001512status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001513 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001514 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001515 ATRACE_CALL();
1516
Emilian Peevaebbe412018-01-15 13:53:24 +00001517 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001518}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001519
Jianing Weicb0652e2014-03-12 18:29:36 -07001520status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1521 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001522 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001523
Emilian Peevaebbe412018-01-15 13:53:24 +00001524 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001525 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001526 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001527
Emilian Peevaebbe412018-01-15 13:53:24 +00001528 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001529 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530}
1531
Emilian Peevaebbe412018-01-15 13:53:24 +00001532status_t Camera3Device::setStreamingRequestList(
1533 const List<const PhysicalCameraSettingsList> &requestsList,
1534 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001535 ATRACE_CALL();
1536
Emilian Peevaebbe412018-01-15 13:53:24 +00001537 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001538}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539
1540sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001541 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 status_t res;
1543
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001545 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1546 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001547 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1548 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001549 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001551 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001553 } else if (mStatus == STATUS_UNCONFIGURED) {
1554 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001555 CLOGE("No streams configured");
1556 return NULL;
1557 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 }
1559
Shuzhen Wang0129d522016-10-30 22:43:41 -07001560 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001561 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001562}
1563
Jianing Weicb0652e2014-03-12 18:29:36 -07001564status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001565 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001566 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001567 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001568
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 switch (mStatus) {
1570 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001571 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 return INVALID_OPERATION;
1573 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001574 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001576 case STATUS_UNCONFIGURED:
1577 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001578 case STATUS_ACTIVE:
1579 // OK
1580 break;
1581 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001582 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583 return INVALID_OPERATION;
1584 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001585 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001586
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001587 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001588}
1589
1590status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1591 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001592 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001593
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001594 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001595}
1596
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001597status_t Camera3Device::createInputStream(
1598 uint32_t width, uint32_t height, int format, int *id) {
1599 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001600 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001601 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001602 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001603 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1604 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001605
1606 status_t res;
1607 bool wasActive = false;
1608
1609 switch (mStatus) {
1610 case STATUS_ERROR:
1611 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1612 return INVALID_OPERATION;
1613 case STATUS_UNINITIALIZED:
1614 ALOGE("%s: Device not initialized", __FUNCTION__);
1615 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001616 case STATUS_UNCONFIGURED:
1617 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001618 // OK
1619 break;
1620 case STATUS_ACTIVE:
1621 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001622 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001623 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001624 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001625 return res;
1626 }
1627 wasActive = true;
1628 break;
1629 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001630 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001631 return INVALID_OPERATION;
1632 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001633 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001634
1635 if (mInputStream != 0) {
1636 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1637 return INVALID_OPERATION;
1638 }
1639
1640 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1641 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001642 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001643
1644 mInputStream = newStream;
1645
1646 *id = mNextStreamId++;
1647
1648 // Continue captures if active at start
1649 if (wasActive) {
1650 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001651 // Reuse current operating mode and session parameters for new stream config
1652 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001653 if (res != OK) {
1654 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1655 __FUNCTION__, mNextStreamId, strerror(-res), res);
1656 return res;
1657 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001658 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001659 }
1660
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001661 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001662 return OK;
1663}
1664
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001665status_t Camera3Device::StreamSet::add(
1666 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1667 if (stream == nullptr) {
1668 ALOGE("%s: cannot add null stream", __FUNCTION__);
1669 return BAD_VALUE;
1670 }
1671 std::lock_guard<std::mutex> lock(mLock);
1672 return mData.add(streamId, stream);
1673}
1674
1675ssize_t Camera3Device::StreamSet::remove(int streamId) {
1676 std::lock_guard<std::mutex> lock(mLock);
1677 return mData.removeItem(streamId);
1678}
1679
1680sp<camera3::Camera3OutputStreamInterface>
1681Camera3Device::StreamSet::get(int streamId) {
1682 std::lock_guard<std::mutex> lock(mLock);
1683 ssize_t idx = mData.indexOfKey(streamId);
1684 if (idx == NAME_NOT_FOUND) {
1685 return nullptr;
1686 }
1687 return mData.editValueAt(idx);
1688}
1689
1690sp<camera3::Camera3OutputStreamInterface>
1691Camera3Device::StreamSet::operator[] (size_t index) {
1692 std::lock_guard<std::mutex> lock(mLock);
1693 return mData.editValueAt(index);
1694}
1695
1696size_t Camera3Device::StreamSet::size() const {
1697 std::lock_guard<std::mutex> lock(mLock);
1698 return mData.size();
1699}
1700
1701void Camera3Device::StreamSet::clear() {
1702 std::lock_guard<std::mutex> lock(mLock);
1703 return mData.clear();
1704}
1705
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001706std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1707 std::lock_guard<std::mutex> lock(mLock);
1708 std::vector<int> streamIds(mData.size());
1709 for (size_t i = 0; i < mData.size(); i++) {
1710 streamIds[i] = mData.keyAt(i);
1711 }
1712 return streamIds;
1713}
1714
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001715status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001716 uint32_t width, uint32_t height, int format,
1717 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001718 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001719 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001720 ATRACE_CALL();
1721
1722 if (consumer == nullptr) {
1723 ALOGE("%s: consumer must not be null", __FUNCTION__);
1724 return BAD_VALUE;
1725 }
1726
1727 std::vector<sp<Surface>> consumers;
1728 consumers.push_back(consumer);
1729
1730 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001731 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1732 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001733}
1734
1735status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1736 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1737 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001738 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001739 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001740 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001741
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001742 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001743 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001744 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001745 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001746 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1747 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1748 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001749
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001750 status_t res;
1751 bool wasActive = false;
1752
1753 switch (mStatus) {
1754 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001755 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001756 return INVALID_OPERATION;
1757 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001758 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001759 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001760 case STATUS_UNCONFIGURED:
1761 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001762 // OK
1763 break;
1764 case STATUS_ACTIVE:
1765 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001766 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001767 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001768 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001769 return res;
1770 }
1771 wasActive = true;
1772 break;
1773 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001774 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001775 return INVALID_OPERATION;
1776 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001777 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001778
1779 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001780
Shuzhen Wang0129d522016-10-30 22:43:41 -07001781 if (consumers.size() == 0 && !hasDeferredConsumer) {
1782 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1783 return BAD_VALUE;
1784 }
Zhijun He5d677d12016-05-29 16:52:39 -07001785
Shuzhen Wang0129d522016-10-30 22:43:41 -07001786 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001787 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1788 return BAD_VALUE;
1789 }
1790
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001791 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001792 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001793 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001794 blobBufferSize = getPointCloudBufferSize();
1795 if (blobBufferSize <= 0) {
1796 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1797 return BAD_VALUE;
1798 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001799 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1800 blobBufferSize = width * height;
1801 } else {
1802 blobBufferSize = getJpegBufferSize(width, height);
1803 if (blobBufferSize <= 0) {
1804 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1805 return BAD_VALUE;
1806 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001807 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001808 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001809 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001810 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001811 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1812 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1813 if (rawOpaqueBufferSize <= 0) {
1814 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1815 return BAD_VALUE;
1816 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001817 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001818 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001819 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001820 } else if (isShared) {
1821 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1822 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001823 mTimestampOffset, physicalCameraId, streamSetId,
1824 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001825 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001826 newStream = new Camera3OutputStream(mNextStreamId,
1827 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001828 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001829 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001830 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001831 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001832 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001833 }
Emilian Peev40ead602017-09-26 15:46:36 +01001834
1835 size_t consumerCount = consumers.size();
1836 for (size_t i = 0; i < consumerCount; i++) {
1837 int id = newStream->getSurfaceId(consumers[i]);
1838 if (id < 0) {
1839 SET_ERR_L("Invalid surface id");
1840 return BAD_VALUE;
1841 }
1842 if (surfaceIds != nullptr) {
1843 surfaceIds->push_back(id);
1844 }
1845 }
1846
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001847 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001848
Emilian Peev08dd2452017-04-06 16:55:14 +01001849 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001850
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001851 res = mOutputStreams.add(mNextStreamId, newStream);
1852 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001853 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001854 return res;
1855 }
1856
1857 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001858 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001859
1860 // Continue captures if active at start
1861 if (wasActive) {
1862 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001863 // Reuse current operating mode and session parameters for new stream config
1864 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001865 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001866 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1867 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001868 return res;
1869 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001870 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001871 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001872 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001873 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001874}
1875
Emilian Peev710c1422017-08-30 11:19:38 +01001876status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001877 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001878 if (nullptr == streamInfo) {
1879 return BAD_VALUE;
1880 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001881 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001882 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001883
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001884 switch (mStatus) {
1885 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001886 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001887 return INVALID_OPERATION;
1888 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001889 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001890 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001891 case STATUS_UNCONFIGURED:
1892 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001893 case STATUS_ACTIVE:
1894 // OK
1895 break;
1896 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001897 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001898 return INVALID_OPERATION;
1899 }
1900
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001901 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1902 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001903 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001904 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001905 }
1906
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001907 streamInfo->width = stream->getWidth();
1908 streamInfo->height = stream->getHeight();
1909 streamInfo->format = stream->getFormat();
1910 streamInfo->dataSpace = stream->getDataSpace();
1911 streamInfo->formatOverridden = stream->isFormatOverridden();
1912 streamInfo->originalFormat = stream->getOriginalFormat();
1913 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1914 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001915 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001916}
1917
1918status_t Camera3Device::setStreamTransform(int id,
1919 int transform) {
1920 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001921 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001922 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001923
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001924 switch (mStatus) {
1925 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001926 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001927 return INVALID_OPERATION;
1928 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001929 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001930 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001931 case STATUS_UNCONFIGURED:
1932 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001933 case STATUS_ACTIVE:
1934 // OK
1935 break;
1936 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001937 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001938 return INVALID_OPERATION;
1939 }
1940
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001941 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1942 if (stream == nullptr) {
1943 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001944 return BAD_VALUE;
1945 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001946 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001947}
1948
1949status_t Camera3Device::deleteStream(int id) {
1950 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001951 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001952 Mutex::Autolock l(mLock);
1953 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001954
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001955 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001956
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001957 // CameraDevice semantics require device to already be idle before
1958 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001959 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001960 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001961 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001962 }
1963
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001964 if (mStatus == STATUS_ERROR) {
1965 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1966 __FUNCTION__, mId.string());
1967 return -EBUSY;
1968 }
1969
Igor Murashkin2fba5842013-04-22 14:03:54 -07001970 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001971 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001972 if (mInputStream != NULL && id == mInputStream->getId()) {
1973 deletedStream = mInputStream;
1974 mInputStream.clear();
1975 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001976 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001977 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001978 return BAD_VALUE;
1979 }
Zhijun He5f446352014-01-22 09:49:33 -08001980 }
1981
1982 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001983 if (stream != nullptr) {
1984 deletedStream = stream;
1985 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001986 }
1987
1988 // Free up the stream endpoint so that it can be used by some other stream
1989 res = deletedStream->disconnect();
1990 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001991 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001992 // fall through since we want to still list the stream as deleted.
1993 }
1994 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001995 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001996
1997 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001998}
1999
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002000status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07002001 ATRACE_CALL();
2002 ALOGV("%s: E", __FUNCTION__);
2003
2004 Mutex::Autolock il(mInterfaceLock);
2005 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07002006
Emilian Peev811d2952018-05-25 11:08:40 +01002007 // In case the client doesn't include any session parameter, try a
2008 // speculative configuration using the values from the last cached
2009 // default request.
2010 if (sessionParams.isEmpty() &&
2011 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
2012 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
2013 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
2014 mLastTemplateId);
2015 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
2016 operatingMode);
2017 }
2018
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002019 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
2020}
2021
2022status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
2023 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002024 //Filter out any incoming session parameters
2025 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002026 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
2027 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002028 CameraMetadata filteredParams(availableSessionKeys.count);
2029 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2030 filteredParams.getAndLock());
2031 set_camera_metadata_vendor_id(meta, mVendorTagId);
2032 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002033 if (availableSessionKeys.count > 0) {
2034 for (size_t i = 0; i < availableSessionKeys.count; i++) {
2035 camera_metadata_ro_entry entry = params.find(
2036 availableSessionKeys.data.i32[i]);
2037 if (entry.count > 0) {
2038 filteredParams.update(entry);
2039 }
2040 }
2041 }
2042
2043 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07002044}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002045
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002046status_t Camera3Device::getInputBufferProducer(
2047 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002048 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002049 Mutex::Autolock il(mInterfaceLock);
2050 Mutex::Autolock l(mLock);
2051
2052 if (producer == NULL) {
2053 return BAD_VALUE;
2054 } else if (mInputStream == NULL) {
2055 return INVALID_OPERATION;
2056 }
2057
2058 return mInputStream->getInputBufferProducer(producer);
2059}
2060
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002061status_t Camera3Device::createDefaultRequest(int templateId,
2062 CameraMetadata *request) {
2063 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002064 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002065
2066 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2067 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002068 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002069 return BAD_VALUE;
2070 }
2071
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002072 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002073
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002074 {
2075 Mutex::Autolock l(mLock);
2076 switch (mStatus) {
2077 case STATUS_ERROR:
2078 CLOGE("Device has encountered a serious error");
2079 return INVALID_OPERATION;
2080 case STATUS_UNINITIALIZED:
2081 CLOGE("Device is not initialized!");
2082 return INVALID_OPERATION;
2083 case STATUS_UNCONFIGURED:
2084 case STATUS_CONFIGURED:
2085 case STATUS_ACTIVE:
2086 // OK
2087 break;
2088 default:
2089 SET_ERR_L("Unexpected status: %d", mStatus);
2090 return INVALID_OPERATION;
2091 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002092
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002093 if (!mRequestTemplateCache[templateId].isEmpty()) {
2094 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002095 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002096 return OK;
2097 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002098 }
2099
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002100 camera_metadata_t *rawRequest;
2101 status_t res = mInterface->constructDefaultRequestSettings(
2102 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002103
2104 {
2105 Mutex::Autolock l(mLock);
2106 if (res == BAD_VALUE) {
2107 ALOGI("%s: template %d is not supported on this camera device",
2108 __FUNCTION__, templateId);
2109 return res;
2110 } else if (res != OK) {
2111 CLOGE("Unable to construct request template %d: %s (%d)",
2112 templateId, strerror(-res), res);
2113 return res;
2114 }
2115
2116 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2117 mRequestTemplateCache[templateId].acquire(rawRequest);
2118
2119 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002120 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002121 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002122 return OK;
2123}
2124
2125status_t Camera3Device::waitUntilDrained() {
2126 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002127 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002128 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002129 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002130
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002131 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002132}
2133
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002134status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002135 switch (mStatus) {
2136 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002137 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002138 ALOGV("%s: Already idle", __FUNCTION__);
2139 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002140 case STATUS_CONFIGURED:
2141 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002142 case STATUS_ERROR:
2143 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002144 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002145 break;
2146 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002147 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002148 return INVALID_OPERATION;
2149 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002150 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2151 maxExpectedDuration);
2152 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002153 if (res != OK) {
2154 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2155 res);
2156 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002157 return res;
2158}
2159
Ruben Brunk183f0562015-08-12 12:55:02 -07002160
2161void Camera3Device::internalUpdateStatusLocked(Status status) {
2162 mStatus = status;
2163 mRecentStatusUpdates.add(mStatus);
2164 mStatusChanged.broadcast();
2165}
2166
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002167void Camera3Device::pauseStateNotify(bool enable) {
2168 Mutex::Autolock il(mInterfaceLock);
2169 Mutex::Autolock l(mLock);
2170
2171 mPauseStateNotify = enable;
2172}
2173
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002174// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002175status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08002176 if (mRequestThread.get() != nullptr) {
2177 mRequestThread->setPaused(true);
2178 } else {
2179 return NO_INIT;
2180 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002181
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002182 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2183 maxExpectedDuration);
2184 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002185 if (res != OK) {
2186 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002187 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002188 }
2189
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002190 return res;
2191}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002192
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002193// Resume after internalPauseAndWaitLocked
2194status_t Camera3Device::internalResumeLocked() {
2195 status_t res;
2196
2197 mRequestThread->setPaused(false);
2198
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002199 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2200 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002201 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2202 if (res != OK) {
2203 SET_ERR_L("Can't transition to active in %f seconds!",
2204 kActiveTimeout/1e9);
2205 }
2206 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002207 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002208}
2209
Ruben Brunk183f0562015-08-12 12:55:02 -07002210status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002211 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002212
2213 size_t startIndex = 0;
2214 if (mStatusWaiters == 0) {
2215 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2216 // this status list
2217 mRecentStatusUpdates.clear();
2218 } else {
2219 // If other threads are waiting on updates to this status list, set the position of the
2220 // first element that this list will check rather than clearing the list.
2221 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002222 }
2223
Ruben Brunk183f0562015-08-12 12:55:02 -07002224 mStatusWaiters++;
2225
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002226 if (!active && mUseHalBufManager) {
2227 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08002228 if (mStatus == STATUS_ACTIVE) {
2229 mRequestThread->signalPipelineDrain(streamIds);
2230 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002231 mRequestBufferSM.onWaitUntilIdle();
2232 }
2233
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002234 bool stateSeen = false;
2235 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002236 if (active == (mStatus == STATUS_ACTIVE)) {
2237 // Desired state is current
2238 break;
2239 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002240
2241 res = mStatusChanged.waitRelative(mLock, timeout);
2242 if (res != OK) break;
2243
Ruben Brunk183f0562015-08-12 12:55:02 -07002244 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2245 // transitions.
2246 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2247 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2248 __FUNCTION__);
2249
2250 // Encountered desired state since we began waiting
2251 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002252 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2253 stateSeen = true;
2254 break;
2255 }
2256 }
2257 } while (!stateSeen);
2258
Ruben Brunk183f0562015-08-12 12:55:02 -07002259 mStatusWaiters--;
2260
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002261 return res;
2262}
2263
2264
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002265status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002266 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002267 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002268
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002269 if (listener != NULL && mListener != NULL) {
2270 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2271 }
2272 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002273 mRequestThread->setNotificationListener(listener);
2274 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002275
2276 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002277}
2278
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002279bool Camera3Device::willNotify3A() {
2280 return false;
2281}
2282
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002283status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002284 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002285 status_t res;
2286 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002287
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002288 while (mResultQueue.empty()) {
2289 res = mResultSignal.waitRelative(mOutputLock, timeout);
2290 if (res == TIMED_OUT) {
2291 return res;
2292 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002293 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2294 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002295 return res;
2296 }
2297 }
2298 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002299}
2300
Jianing Weicb0652e2014-03-12 18:29:36 -07002301status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002302 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002303 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002304
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002305 if (mResultQueue.empty()) {
2306 return NOT_ENOUGH_DATA;
2307 }
2308
Jianing Weicb0652e2014-03-12 18:29:36 -07002309 if (frame == NULL) {
2310 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2311 return BAD_VALUE;
2312 }
2313
2314 CaptureResult &result = *(mResultQueue.begin());
2315 frame->mResultExtras = result.mResultExtras;
2316 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002317 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002318 mResultQueue.erase(mResultQueue.begin());
2319
2320 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002321}
2322
2323status_t Camera3Device::triggerAutofocus(uint32_t id) {
2324 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002325 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002326
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002327 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2328 // Mix-in this trigger into the next request and only the next request.
2329 RequestTrigger trigger[] = {
2330 {
2331 ANDROID_CONTROL_AF_TRIGGER,
2332 ANDROID_CONTROL_AF_TRIGGER_START
2333 },
2334 {
2335 ANDROID_CONTROL_AF_TRIGGER_ID,
2336 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002337 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002338 };
2339
2340 return mRequestThread->queueTrigger(trigger,
2341 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002342}
2343
2344status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2345 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002346 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002347
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002348 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2349 // Mix-in this trigger into the next request and only the next request.
2350 RequestTrigger trigger[] = {
2351 {
2352 ANDROID_CONTROL_AF_TRIGGER,
2353 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2354 },
2355 {
2356 ANDROID_CONTROL_AF_TRIGGER_ID,
2357 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002358 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002359 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002360
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002361 return mRequestThread->queueTrigger(trigger,
2362 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002363}
2364
2365status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2366 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002367 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002368
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002369 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2370 // Mix-in this trigger into the next request and only the next request.
2371 RequestTrigger trigger[] = {
2372 {
2373 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2374 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2375 },
2376 {
2377 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2378 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002379 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002380 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002381
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002382 return mRequestThread->queueTrigger(trigger,
2383 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002384}
2385
Jianing Weicb0652e2014-03-12 18:29:36 -07002386status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002387 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002388 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002389 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002390
Zhijun He7ef20392014-04-21 16:04:17 -07002391 {
2392 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002393
2394 // b/116514106 "disconnect()" can get called twice for the same device. The
2395 // camera device will not be initialized during the second run.
2396 if (mStatus == STATUS_UNINITIALIZED) {
2397 return OK;
2398 }
2399
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002400 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002401 }
2402
Emilian Peev08dd2452017-04-06 16:55:14 +01002403 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002404}
2405
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002406status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002407 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2408}
2409
2410status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002411 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002412 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002413 Mutex::Autolock il(mInterfaceLock);
2414 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002415
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002416 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2417 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002418 CLOGE("Stream %d does not exist", streamId);
2419 return BAD_VALUE;
2420 }
2421
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002422 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002423 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002424 return BAD_VALUE;
2425 }
2426
2427 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002428 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002429 return BAD_VALUE;
2430 }
2431
Ruben Brunkc78ac262015-08-13 17:58:46 -07002432 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002433}
2434
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002435status_t Camera3Device::tearDown(int streamId) {
2436 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002437 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002438 Mutex::Autolock il(mInterfaceLock);
2439 Mutex::Autolock l(mLock);
2440
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002441 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2442 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002443 CLOGE("Stream %d does not exist", streamId);
2444 return BAD_VALUE;
2445 }
2446
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002447 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2448 CLOGE("Stream %d is a target of a in-progress request", streamId);
2449 return BAD_VALUE;
2450 }
2451
2452 return stream->tearDown();
2453}
2454
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002455status_t Camera3Device::addBufferListenerForStream(int streamId,
2456 wp<Camera3StreamBufferListener> listener) {
2457 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002458 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002459 Mutex::Autolock il(mInterfaceLock);
2460 Mutex::Autolock l(mLock);
2461
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002462 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2463 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002464 CLOGE("Stream %d does not exist", streamId);
2465 return BAD_VALUE;
2466 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002467 stream->addBufferListener(listener);
2468
2469 return OK;
2470}
2471
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002472/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002473 * Methods called by subclasses
2474 */
2475
2476void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002477 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002478 {
2479 // Need mLock to safely update state and synchronize to current
2480 // state of methods in flight.
2481 Mutex::Autolock l(mLock);
2482 // We can get various system-idle notices from the status tracker
2483 // while starting up. Only care about them if we've actually sent
2484 // in some requests recently.
2485 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2486 return;
2487 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002488 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2489 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002490 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002491
2492 // Skip notifying listener if we're doing some user-transparent
2493 // state changes
2494 if (mPauseStateNotify) return;
2495 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002496
2497 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002498 {
2499 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002500 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002501 }
2502 if (idle && listener != NULL) {
2503 listener->notifyIdle();
2504 }
2505}
2506
Shuzhen Wang758c2152017-01-10 18:26:18 -08002507status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002508 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002509 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002510 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2511 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002512
2513 if (surfaceIds == nullptr) {
2514 return BAD_VALUE;
2515 }
2516
Zhijun He5d677d12016-05-29 16:52:39 -07002517 Mutex::Autolock il(mInterfaceLock);
2518 Mutex::Autolock l(mLock);
2519
Shuzhen Wang758c2152017-01-10 18:26:18 -08002520 if (consumers.size() == 0) {
2521 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002522 return BAD_VALUE;
2523 }
2524
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002525 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2526 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002527 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002528 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002529 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002530
2531 // isConsumerConfigurationDeferred will be off after setConsumers
2532 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002533 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002534 if (res != OK) {
2535 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2536 return res;
2537 }
2538
Emilian Peev40ead602017-09-26 15:46:36 +01002539 for (auto &consumer : consumers) {
2540 int id = stream->getSurfaceId(consumer);
2541 if (id < 0) {
2542 CLOGE("Invalid surface id!");
2543 return BAD_VALUE;
2544 }
2545 surfaceIds->push_back(id);
2546 }
2547
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002548 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002549 if (!stream->isConfiguring()) {
2550 CLOGE("Stream %d was already fully configured.", streamId);
2551 return INVALID_OPERATION;
2552 }
Zhijun He5d677d12016-05-29 16:52:39 -07002553
Shuzhen Wang0129d522016-10-30 22:43:41 -07002554 res = stream->finishConfiguration();
2555 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002556 // If finishConfiguration fails due to abandoned surface, do not set
2557 // device to error state.
2558 bool isSurfaceAbandoned =
2559 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2560 if (!isSurfaceAbandoned) {
2561 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2562 stream->getId(), strerror(-res), res);
2563 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002564 return res;
2565 }
Zhijun He5d677d12016-05-29 16:52:39 -07002566 }
2567
2568 return OK;
2569}
2570
Emilian Peev40ead602017-09-26 15:46:36 +01002571status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2572 const std::vector<OutputStreamInfo> &outputInfo,
2573 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2574 Mutex::Autolock il(mInterfaceLock);
2575 Mutex::Autolock l(mLock);
2576
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002577 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2578 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002579 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002580 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002581 }
2582
2583 for (const auto &it : removedSurfaceIds) {
2584 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2585 CLOGE("Shared surface still part of a pending request!");
2586 return -EBUSY;
2587 }
2588 }
2589
Emilian Peev40ead602017-09-26 15:46:36 +01002590 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2591 if (res != OK) {
2592 CLOGE("Stream %d failed to update stream (error %d %s) ",
2593 streamId, res, strerror(-res));
2594 if (res == UNKNOWN_ERROR) {
2595 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2596 __FUNCTION__);
2597 }
2598 return res;
2599 }
2600
2601 return res;
2602}
2603
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002604status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2605 Mutex::Autolock il(mInterfaceLock);
2606 Mutex::Autolock l(mLock);
2607
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002608 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2609 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002610 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2611 return BAD_VALUE;
2612 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002613 return stream->dropBuffers(dropping);
2614}
2615
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002616/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002617 * Camera3Device private methods
2618 */
2619
2620sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002621 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002622 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002623
2624 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002625 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002626
2627 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002628 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002629 if (inputStreams.count > 0) {
2630 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002631 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002632 CLOGE("Request references unknown input stream %d",
2633 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002634 return NULL;
2635 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002636
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002637 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002638 SET_ERR_L("%s: input stream %d is not configured!",
2639 __FUNCTION__, mInputStream->getId());
2640 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002641 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002642 // Check if stream prepare is blocking requests.
2643 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002644 CLOGE("Request references an input stream that's being prepared!");
2645 return NULL;
2646 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002647
2648 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002649 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002650 }
2651
2652 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002653 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002654 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002655 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002656 return NULL;
2657 }
2658
2659 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002660 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2661 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002662 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002663 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002664 return NULL;
2665 }
Zhijun He5d677d12016-05-29 16:52:39 -07002666 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002667 auto iter = surfaceMap.find(streams.data.i32[i]);
2668 if (iter != surfaceMap.end()) {
2669 const std::vector<size_t>& surfaces = iter->second;
2670 for (const auto& surface : surfaces) {
2671 if (stream->isConsumerConfigurationDeferred(surface)) {
2672 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2673 "due to deferred consumer", stream->getId(), surface);
2674 return NULL;
2675 }
2676 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002677 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002678 }
2679
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002680 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002681 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2682 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002683 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002684 // Check if stream prepare is blocking requests.
2685 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002686 CLOGE("Request references an output stream that's being prepared!");
2687 return NULL;
2688 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002689
2690 newRequest->mOutputStreams.push(stream);
2691 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002692 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002693 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002694
2695 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002696}
2697
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002698bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2699 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2700 Size size = mSupportedOpaqueInputSizes[i];
2701 if (size.width == width && size.height == height) {
2702 return true;
2703 }
2704 }
2705
2706 return false;
2707}
2708
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002709void Camera3Device::cancelStreamsConfigurationLocked() {
2710 int res = OK;
2711 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2712 res = mInputStream->cancelConfiguration();
2713 if (res != OK) {
2714 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2715 mInputStream->getId(), strerror(-res), res);
2716 }
2717 }
2718
2719 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002720 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002721 if (outputStream->isConfiguring()) {
2722 res = outputStream->cancelConfiguration();
2723 if (res != OK) {
2724 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2725 outputStream->getId(), strerror(-res), res);
2726 }
2727 }
2728 }
2729
2730 // Return state to that at start of call, so that future configures
2731 // properly clean things up
2732 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2733 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002734
2735 res = mPreparerThread->resume();
2736 if (res != OK) {
2737 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2738 }
2739}
2740
2741bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2742 ATRACE_CALL();
2743 bool ret = false;
2744
2745 Mutex::Autolock il(mInterfaceLock);
2746 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2747
2748 Mutex::Autolock l(mLock);
2749 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2750 if (rc == NO_ERROR) {
2751 mNeedConfig = true;
2752 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2753 if (rc == NO_ERROR) {
2754 ret = true;
2755 mPauseStateNotify = false;
2756 //Moving to active state while holding 'mLock' is important.
2757 //There could be pending calls to 'create-/deleteStream' which
2758 //will trigger another stream configuration while the already
2759 //present streams end up with outstanding buffers that will
2760 //not get drained.
2761 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002762 } else if (rc == DEAD_OBJECT) {
2763 // DEAD_OBJECT can be returned if either the consumer surface is
2764 // abandoned, or the HAL has died.
2765 // - If the HAL has died, configureStreamsLocked call will set
2766 // device to error state,
2767 // - If surface is abandoned, we should not set device to error
2768 // state.
2769 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002770 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002771 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002772 }
2773 } else {
2774 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2775 }
2776
2777 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002778}
2779
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002780status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002781 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002782 ATRACE_CALL();
2783 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002784
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002785 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002786 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002787 return INVALID_OPERATION;
2788 }
2789
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002790 if (operatingMode < 0) {
2791 CLOGE("Invalid operating mode: %d", operatingMode);
2792 return BAD_VALUE;
2793 }
2794
2795 bool isConstrainedHighSpeed =
2796 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2797 operatingMode;
2798
2799 if (mOperatingMode != operatingMode) {
2800 mNeedConfig = true;
2801 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2802 mOperatingMode = operatingMode;
2803 }
2804
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002805 if (!mNeedConfig) {
2806 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2807 return OK;
2808 }
2809
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002810 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2811 // adding a dummy stream instead.
2812 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2813 if (mOutputStreams.size() == 0) {
2814 addDummyStreamLocked();
2815 } else {
2816 tryRemoveDummyStreamLocked();
2817 }
2818
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002819 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002820 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002821
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002822 mPreparerThread->pause();
2823
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002824 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002825 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002826 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2827
2828 Vector<camera3_stream_t*> streams;
2829 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002830 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002831
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002832
2833 if (mInputStream != NULL) {
2834 camera3_stream_t *inputStream;
2835 inputStream = mInputStream->startConfiguration();
2836 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002837 CLOGE("Can't start input stream configuration");
2838 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002839 return INVALID_OPERATION;
2840 }
2841 streams.add(inputStream);
2842 }
2843
2844 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002845
2846 // Don't configure bidi streams twice, nor add them twice to the list
2847 if (mOutputStreams[i].get() ==
2848 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2849
2850 config.num_streams--;
2851 continue;
2852 }
2853
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002854 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002855 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002856 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002857 CLOGE("Can't start output stream configuration");
2858 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002859 return INVALID_OPERATION;
2860 }
2861 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002862
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002863 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002864 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2865 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002866 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2867 bufferSizes[k] = static_cast<uint32_t>(
2868 getJpegBufferSize(outputStream->width, outputStream->height));
2869 } else if (outputStream->data_space ==
2870 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2871 bufferSizes[k] = outputStream->width * outputStream->height;
2872 } else {
2873 ALOGW("%s: Blob dataSpace %d not supported",
2874 __FUNCTION__, outputStream->data_space);
2875 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002876 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002877 }
2878
2879 config.streams = streams.editArray();
2880
2881 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002882 // max_buffers, usage, and priv fields, as well as data_space and format
2883 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002884
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002885 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002886 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002887 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002888
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002889 if (res == BAD_VALUE) {
2890 // HAL rejected this set of streams as unsupported, clean up config
2891 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002892 CLOGE("Set of requested inputs/outputs not supported by HAL");
2893 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002894 return BAD_VALUE;
2895 } else if (res != OK) {
2896 // Some other kind of error from configure_streams - this is not
2897 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002898 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2899 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002900 return res;
2901 }
2902
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002903 // Finish all stream configuration immediately.
2904 // TODO: Try to relax this later back to lazy completion, which should be
2905 // faster
2906
Igor Murashkin073f8572013-05-02 14:59:28 -07002907 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002908 bool streamReConfigured = false;
2909 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002910 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002911 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002912 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002913 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002914 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2915 return DEAD_OBJECT;
2916 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002917 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002918 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002919 if (streamReConfigured) {
2920 mInterface->onStreamReConfigured(mInputStream->getId());
2921 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002922 }
2923
2924 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002925 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002926 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002927 bool streamReConfigured = false;
2928 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002929 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002930 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002931 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002932 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002933 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2934 return DEAD_OBJECT;
2935 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002936 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002937 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002938 if (streamReConfigured) {
2939 mInterface->onStreamReConfigured(outputStream->getId());
2940 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002941 }
2942 }
2943
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002944 // Request thread needs to know to avoid using repeat-last-settings protocol
2945 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002946 if (notifyRequestThread) {
2947 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2948 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002949
Zhijun He90f7c372016-08-16 16:19:43 -07002950 char value[PROPERTY_VALUE_MAX];
2951 property_get("camera.fifo.disable", value, "0");
2952 int32_t disableFifo = atoi(value);
2953 if (disableFifo != 1) {
2954 // Boost priority of request thread to SCHED_FIFO.
2955 pid_t requestThreadTid = mRequestThread->getTid();
2956 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002957 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002958 if (res != OK) {
2959 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2960 strerror(-res), res);
2961 } else {
2962 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2963 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002964 }
2965
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002966 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002967 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2968 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2969 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2970 sessionParams.unlock(newSessionParams);
2971 mSessionParams.unlock(currentSessionParams);
2972 if (updateSessionParams) {
2973 mSessionParams = sessionParams;
2974 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002975
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002976 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002977
Ruben Brunk183f0562015-08-12 12:55:02 -07002978 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2979 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002980
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002981 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002982
Zhijun He0a210512014-07-24 13:45:15 -07002983 // tear down the deleted streams after configure streams.
2984 mDeletedStreams.clear();
2985
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002986 auto rc = mPreparerThread->resume();
2987 if (rc != OK) {
2988 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2989 return rc;
2990 }
2991
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002992 if (mDummyStreamId == NO_STREAM) {
2993 mRequestBufferSM.onStreamsConfigured();
2994 }
2995
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002996 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002997}
2998
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002999status_t Camera3Device::addDummyStreamLocked() {
3000 ATRACE_CALL();
3001 status_t res;
3002
3003 if (mDummyStreamId != NO_STREAM) {
3004 // Should never be adding a second dummy stream when one is already
3005 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003006 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
3007 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003008 return INVALID_OPERATION;
3009 }
3010
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003011 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003012
3013 sp<Camera3OutputStreamInterface> dummyStream =
3014 new Camera3DummyStream(mNextStreamId);
3015
3016 res = mOutputStreams.add(mNextStreamId, dummyStream);
3017 if (res < 0) {
3018 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
3019 return res;
3020 }
3021
3022 mDummyStreamId = mNextStreamId;
3023 mNextStreamId++;
3024
3025 return OK;
3026}
3027
3028status_t Camera3Device::tryRemoveDummyStreamLocked() {
3029 ATRACE_CALL();
3030 status_t res;
3031
3032 if (mDummyStreamId == NO_STREAM) return OK;
3033 if (mOutputStreams.size() == 1) return OK;
3034
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003035 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003036
3037 // Ok, have a dummy stream and there's at least one other output stream,
3038 // so remove the dummy
3039
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003040 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
3041 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003042 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3043 return INVALID_OPERATION;
3044 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003045 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003046
3047 // Free up the stream endpoint so that it can be used by some other stream
3048 res = deletedStream->disconnect();
3049 if (res != OK) {
3050 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3051 // fall through since we want to still list the stream as deleted.
3052 }
3053 mDeletedStreams.add(deletedStream);
3054 mDummyStreamId = NO_STREAM;
3055
3056 return res;
3057}
3058
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003059void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003060 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003061 Mutex::Autolock l(mLock);
3062 va_list args;
3063 va_start(args, fmt);
3064
3065 setErrorStateLockedV(fmt, args);
3066
3067 va_end(args);
3068}
3069
3070void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003071 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003072 Mutex::Autolock l(mLock);
3073 setErrorStateLockedV(fmt, args);
3074}
3075
3076void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3077 va_list args;
3078 va_start(args, fmt);
3079
3080 setErrorStateLockedV(fmt, args);
3081
3082 va_end(args);
3083}
3084
3085void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003086 // Print out all error messages to log
3087 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003088 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003089
3090 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003091 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003092
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003093 mErrorCause = errorCause;
3094
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003095 if (mRequestThread != nullptr) {
3096 mRequestThread->setPaused(true);
3097 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003098 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003099
3100 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003101 sp<NotificationListener> listener = mListener.promote();
3102 if (listener != NULL) {
3103 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003104 CaptureResultExtras());
3105 }
3106
3107 // Save stack trace. View by dumping it later.
3108 CameraTraces::saveTrace();
3109 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003110}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003111
3112/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003113 * In-flight request management
3114 */
3115
Jianing Weicb0652e2014-03-12 18:29:36 -07003116status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003117 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003118 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003119 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003120 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003121 ATRACE_CALL();
3122 Mutex::Autolock l(mInFlightLock);
3123
3124 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003125 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003126 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3127 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003128 if (res < 0) return res;
3129
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003130 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003131 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3132 // avoid a deadlock during reprocess requests.
3133 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003134 if (mStatusTracker != nullptr) {
3135 mStatusTracker->markComponentActive(mInFlightStatusId);
3136 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003137 }
3138
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003139 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003140 return OK;
3141}
3142
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003143void Camera3Device::returnOutputBuffers(
3144 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003145 nsecs_t timestamp, bool timestampIncreasing,
3146 const SurfaceMap& outputSurfaces,
3147 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003148
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003149 for (size_t i = 0; i < numBuffers; i++)
3150 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003151 if (outputBuffers[i].buffer == nullptr) {
3152 if (!mUseHalBufManager) {
3153 // With HAL buffer management API, HAL sometimes will have to return buffers that
3154 // has not got a output buffer handle filled yet. This is though illegal if HAL
3155 // buffer management API is not being used.
3156 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3157 }
3158 continue;
3159 }
3160
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003161 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3162 int streamId = stream->getId();
3163 const auto& it = outputSurfaces.find(streamId);
3164 status_t res = OK;
3165 if (it != outputSurfaces.end()) {
3166 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003167 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3168 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003169 } else {
3170 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003171 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3172 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003173 }
3174
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003175 // Note: stream may be deallocated at this point, if this buffer was
3176 // the last reference to it.
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003177 if (res == NO_INIT || res == DEAD_OBJECT) {
3178 ALOGV("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
3179 } else if (res != OK) {
3180 ALOGE("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003181 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003182
3183 // Long processing consumers can cause returnBuffer timeout for shared stream
3184 // If that happens, cancel the buffer and send a buffer error to client
3185 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3186 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3187 // cancel the buffer
3188 camera3_stream_buffer_t sb = outputBuffers[i];
3189 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003190 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3191 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003192
3193 // notify client buffer error
3194 sp<NotificationListener> listener;
3195 {
3196 Mutex::Autolock l(mOutputLock);
3197 listener = mListener.promote();
3198 }
3199
3200 if (listener != nullptr) {
3201 CaptureResultExtras extras = inResultExtras;
3202 extras.errorStreamId = streamId;
3203 listener->notifyError(
3204 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3205 extras);
3206 }
3207 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003208 }
3209}
3210
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003211void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003212 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003213 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003214 mInFlightMap.removeItemsAt(idx, 1);
3215
3216 // Indicate idle inFlightMap to the status tracker
3217 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003218 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003219 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3220 // avoid a deadlock during reprocess requests.
3221 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003222 if (mStatusTracker != nullptr) {
3223 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3224 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003225 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003226 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003227}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003228
3229void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3230
3231 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3232 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3233
3234 nsecs_t sensorTimestamp = request.sensorTimestamp;
3235 nsecs_t shutterTimestamp = request.shutterTimestamp;
3236
3237 // Check if it's okay to remove the request from InFlightMap:
3238 // In the case of a successful request:
3239 // all input and output buffers, all result metadata, shutter callback
3240 // arrived.
3241 // In the case of a unsuccessful request:
3242 // all input and output buffers arrived.
3243 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003244 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003245 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003246 if (request.stillCapture) {
3247 ATRACE_ASYNC_END("still capture", frameNumber);
3248 }
3249
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003250 ATRACE_ASYNC_END("frame capture", frameNumber);
3251
Shuzhen Wang403044a2017-02-26 23:29:04 -08003252 // Sanity check - if sensor timestamp matches shutter timestamp in the
3253 // case of request having callback.
3254 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003255 sensorTimestamp != shutterTimestamp) {
3256 SET_ERR("sensor timestamp (%" PRId64
3257 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3258 sensorTimestamp, frameNumber, shutterTimestamp);
3259 }
3260
3261 // for an unsuccessful request, it may have pending output buffers to
3262 // return.
3263 assert(request.requestStatus != OK ||
3264 request.pendingOutputBuffers.size() == 0);
3265 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003266 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3267 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003268
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003269 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003270 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3271 }
3272
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003273 // Sanity check - if we have too many in-flight frames with long total inflight duration,
3274 // something has likely gone wrong. This might still be legit only if application send in
3275 // a long burst of long exposure requests.
3276 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3277 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3278 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3279 mInFlightMap.size(), mExpectedInflightDuration);
3280 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3281 kInFlightWarnLimitHighSpeed) {
3282 CLOGW("In-flight list too large for high speed configuration: %zu,"
3283 "total inflight duration %" PRIu64,
3284 mInFlightMap.size(), mExpectedInflightDuration);
3285 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003286 }
3287}
3288
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003289void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003290 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003291 { // First return buffers cached in mInFlightMap
3292 Mutex::Autolock l(mInFlightLock);
3293 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3294 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3295 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003296 request.pendingOutputBuffers.size(), 0,
3297 /*timestampIncreasing*/true, request.outputSurfaces,
3298 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003299 }
3300 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003301 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003302 }
3303
3304 // Then return all inflight buffers not returned by HAL
3305 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3306 mInterface->getInflightBufferKeys(&inflightKeys);
3307
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003308 // Inflight buffers for HAL buffer manager
3309 std::vector<uint64_t> inflightRequestBufferKeys;
3310 mInterface->getInflightRequestBufferKeys(&inflightRequestBufferKeys);
3311
3312 // (streamId, frameNumber, buffer_handle_t*) tuple for all inflight buffers.
3313 // frameNumber will be -1 for buffers from HAL buffer manager
3314 std::vector<std::tuple<int32_t, int32_t, buffer_handle_t*>> inflightBuffers;
3315 inflightBuffers.reserve(inflightKeys.size() + inflightRequestBufferKeys.size());
3316
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003317 for (auto& pair : inflightKeys) {
3318 int32_t frameNumber = pair.first;
3319 int32_t streamId = pair.second;
3320 buffer_handle_t* buffer;
3321 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3322 if (res != OK) {
3323 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3324 __FUNCTION__, frameNumber, streamId);
3325 continue;
3326 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003327 inflightBuffers.push_back(std::make_tuple(streamId, frameNumber, buffer));
3328 }
3329
3330 for (auto& bufferId : inflightRequestBufferKeys) {
3331 int32_t streamId = -1;
3332 buffer_handle_t* buffer = nullptr;
3333 status_t res = mInterface->popInflightRequestBuffer(bufferId, &buffer, &streamId);
3334 if (res != OK) {
3335 ALOGE("%s: cannot find in-flight buffer %" PRIu64, __FUNCTION__, bufferId);
3336 continue;
3337 }
3338 inflightBuffers.push_back(std::make_tuple(streamId, /*frameNumber*/-1, buffer));
3339 }
3340
3341 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3342 for (auto& tuple : inflightBuffers) {
3343 status_t res = OK;
3344 int32_t streamId = std::get<0>(tuple);
3345 int32_t frameNumber = std::get<1>(tuple);
3346 buffer_handle_t* buffer = std::get<2>(tuple);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003347
3348 camera3_stream_buffer_t streamBuffer;
3349 streamBuffer.buffer = buffer;
3350 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3351 streamBuffer.acquire_fence = -1;
3352 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003353
3354 // First check if the buffer belongs to deleted stream
3355 bool streamDeleted = false;
3356 for (auto& stream : mDeletedStreams) {
3357 if (streamId == stream->getId()) {
3358 streamDeleted = true;
3359 // Return buffer to deleted stream
3360 camera3_stream* halStream = stream->asHalStream();
3361 streamBuffer.stream = halStream;
3362 switch (halStream->stream_type) {
3363 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003364 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3365 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003366 if (res != OK) {
3367 ALOGE("%s: Can't return output buffer for frame %d to"
3368 " stream %d: %s (%d)", __FUNCTION__,
3369 frameNumber, streamId, strerror(-res), res);
3370 }
3371 break;
3372 case CAMERA3_STREAM_INPUT:
3373 res = stream->returnInputBuffer(streamBuffer);
3374 if (res != OK) {
3375 ALOGE("%s: Can't return input buffer for frame %d to"
3376 " stream %d: %s (%d)", __FUNCTION__,
3377 frameNumber, streamId, strerror(-res), res);
3378 }
3379 break;
3380 default: // Bi-direcitonal stream is deprecated
3381 ALOGE("%s: stream %d has unknown stream type %d",
3382 __FUNCTION__, streamId, halStream->stream_type);
3383 break;
3384 }
3385 break;
3386 }
3387 }
3388 if (streamDeleted) {
3389 continue;
3390 }
3391
3392 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003393 if (streamId == inputStreamId) {
3394 streamBuffer.stream = mInputStream->asHalStream();
3395 res = mInputStream->returnInputBuffer(streamBuffer);
3396 if (res != OK) {
3397 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003398 " stream %d: %s (%d)", __FUNCTION__,
3399 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003400 }
3401 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003402 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3403 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003404 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3405 continue;
3406 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003407 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003408 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3409 }
3410 }
3411}
3412
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003413void Camera3Device::insertResultLocked(CaptureResult *result,
3414 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003415 if (result == nullptr) return;
3416
Emilian Peev71c73a22017-03-21 16:35:51 +00003417 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3418 result->mMetadata.getAndLock());
3419 set_camera_metadata_vendor_id(meta, mVendorTagId);
3420 result->mMetadata.unlock(meta);
3421
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003422 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3423 (int32_t*)&frameNumber, 1) != OK) {
3424 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3425 return;
3426 }
3427
3428 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3429 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3430 return;
3431 }
3432
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003433 // Update vendor tag id for physical metadata
3434 for (auto& physicalMetadata : result->mPhysicalMetadatas) {
3435 camera_metadata_t *pmeta = const_cast<camera_metadata_t *>(
3436 physicalMetadata.mPhysicalCameraMetadata.getAndLock());
3437 set_camera_metadata_vendor_id(pmeta, mVendorTagId);
3438 physicalMetadata.mPhysicalCameraMetadata.unlock(pmeta);
3439 }
3440
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003441 // Valid result, insert into queue
3442 List<CaptureResult>::iterator queuedResult =
3443 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3444 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3445 ", burstId = %" PRId32, __FUNCTION__,
3446 queuedResult->mResultExtras.requestId,
3447 queuedResult->mResultExtras.frameNumber,
3448 queuedResult->mResultExtras.burstId);
3449
3450 mResultSignal.signal();
3451}
3452
3453
3454void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003455 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003456 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003457 Mutex::Autolock l(mOutputLock);
3458
3459 CaptureResult captureResult;
3460 captureResult.mResultExtras = resultExtras;
3461 captureResult.mMetadata = partialResult;
3462
Shuzhen Wang268a1362018-10-16 16:32:59 -07003463 // Fix up result metadata for monochrome camera.
3464 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3465 if (res != OK) {
3466 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3467 return;
3468 }
3469
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003470 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003471}
3472
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003473
3474void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3475 CaptureResultExtras &resultExtras,
3476 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003477 uint32_t frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003478 bool reprocess, bool zslStillCapture,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003479 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003480 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003481 if (pendingMetadata.isEmpty())
3482 return;
3483
3484 Mutex::Autolock l(mOutputLock);
3485
3486 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003487 if (reprocess) {
3488 if (frameNumber < mNextReprocessResultFrameNumber) {
3489 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003490 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003491 frameNumber, mNextReprocessResultFrameNumber);
3492 return;
3493 }
3494 mNextReprocessResultFrameNumber = frameNumber + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003495 } else if (zslStillCapture) {
3496 if (frameNumber < mNextZslStillResultFrameNumber) {
3497 SET_ERR("Out-of-order ZSL still capture result metadata submitted! "
3498 "(got frame number %d, expecting %d)",
3499 frameNumber, mNextZslStillResultFrameNumber);
3500 return;
3501 }
3502 mNextZslStillResultFrameNumber = frameNumber + 1;
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003503 } else {
3504 if (frameNumber < mNextResultFrameNumber) {
3505 SET_ERR("Out-of-order capture result metadata submitted! "
3506 "(got frame number %d, expecting %d)",
3507 frameNumber, mNextResultFrameNumber);
3508 return;
3509 }
3510 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003511 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003512
3513 CaptureResult captureResult;
3514 captureResult.mResultExtras = resultExtras;
3515 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003516 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003517
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003518 // Append any previous partials to form a complete result
3519 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3520 captureResult.mMetadata.append(collectedPartialResult);
3521 }
3522
3523 captureResult.mMetadata.sort();
3524
3525 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003526 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3527 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003528 SET_ERR("No timestamp provided by HAL for frame %d!",
3529 frameNumber);
3530 return;
3531 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003532 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3533 camera_metadata_entry timestamp =
3534 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3535 if (timestamp.count == 0) {
3536 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3537 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3538 return;
3539 }
3540 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003541
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003542 // Fix up some result metadata to account for HAL-level distortion correction
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003543 status_t res =
3544 mDistortionMappers[mId.c_str()].correctCaptureResult(&captureResult.mMetadata);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003545 if (res != OK) {
3546 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3547 frameNumber, strerror(res), res);
3548 return;
3549 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003550 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3551 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3552 if (mDistortionMappers.find(cameraId8.c_str()) == mDistortionMappers.end()) {
3553 continue;
3554 }
3555 res = mDistortionMappers[cameraId8.c_str()].correctCaptureResult(
3556 &physicalMetadata.mPhysicalCameraMetadata);
3557 if (res != OK) {
3558 SET_ERR("Unable to correct physical capture result metadata for frame %d: %s (%d)",
3559 frameNumber, strerror(res), res);
3560 return;
3561 }
3562 }
3563
Shuzhen Wang268a1362018-10-16 16:32:59 -07003564 // Fix up result metadata for monochrome camera.
3565 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3566 if (res != OK) {
3567 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3568 return;
3569 }
3570 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3571 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3572 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3573 physicalMetadata.mPhysicalCameraMetadata);
3574 if (res != OK) {
3575 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3576 return;
3577 }
3578 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003579
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003580 std::unordered_map<std::string, CameraMetadata> monitoredPhysicalMetadata;
3581 for (auto& m : physicalMetadatas) {
3582 monitoredPhysicalMetadata.emplace(String8(m.mPhysicalCameraId).string(),
3583 CameraMetadata(m.mPhysicalCameraMetadata));
3584 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003585 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003586 frameNumber, timestamp.data.i64[0], captureResult.mMetadata,
3587 monitoredPhysicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003588
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003589 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003590}
3591
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003592/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003593 * Camera HAL device callback methods
3594 */
3595
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003596void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003597 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003598
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003599 status_t res;
3600
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003601 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003602 if (result->result == NULL && result->num_output_buffers == 0 &&
3603 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003604 SET_ERR("No result data provided by HAL for frame %d",
3605 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003606 return;
3607 }
Zhijun He204e3292014-07-14 17:09:23 -07003608
Zhijun He204e3292014-07-14 17:09:23 -07003609 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003610 result->result != NULL &&
3611 result->partial_result != 1) {
3612 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3613 " if partial result is not supported",
3614 frameNumber, result->partial_result);
3615 return;
3616 }
3617
3618 bool isPartialResult = false;
3619 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003620 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003621
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003622 // Get shutter timestamp and resultExtras from list of in-flight requests,
3623 // where it was added by the shutter notification for this frame. If the
3624 // shutter timestamp isn't received yet, append the output buffers to the
3625 // in-flight request and they will be returned when the shutter timestamp
3626 // arrives. Update the in-flight status and remove the in-flight entry if
3627 // all result data and shutter timestamp have been received.
3628 nsecs_t shutterTimestamp = 0;
3629
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003630 {
3631 Mutex::Autolock l(mInFlightLock);
3632 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3633 if (idx == NAME_NOT_FOUND) {
3634 SET_ERR("Unknown frame number for capture result: %d",
3635 frameNumber);
3636 return;
3637 }
3638 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003639 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3640 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003641 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003642 __FUNCTION__, request.resultExtras.requestId,
3643 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003644 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003645 // Always update the partial count to the latest one if it's not 0
3646 // (buffers only). When framework aggregates adjacent partial results
3647 // into one, the latest partial count will be used.
3648 if (result->partial_result != 0)
3649 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003650
3651 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003652 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003653 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3654 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3655 " the range of [1, %d] when metadata is included in the result",
3656 frameNumber, result->partial_result, mNumPartialResults);
3657 return;
3658 }
3659 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003660 if (isPartialResult && result->num_physcam_metadata) {
3661 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3662 " physical camera result", frameNumber);
3663 return;
3664 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003665 if (isPartialResult) {
3666 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003667 }
3668
Shuzhen Wang4a472662017-02-26 23:29:04 -08003669 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003670 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003671 sendPartialCaptureResult(result->result, request.resultExtras,
3672 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003673 }
3674 }
3675
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003676 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003677 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003678
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003679 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003680 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003681 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3682 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3683 request.physicalCameraIds.size(), result->num_physcam_metadata);
3684 return;
3685 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003686 if (request.haveResultMetadata) {
3687 SET_ERR("Called multiple times with metadata for frame %d",
3688 frameNumber);
3689 return;
3690 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003691 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3692 String8 physicalId(result->physcam_ids[i]);
3693 std::set<String8>::iterator cameraIdIter =
3694 request.physicalCameraIds.find(physicalId);
3695 if (cameraIdIter != request.physicalCameraIds.end()) {
3696 request.physicalCameraIds.erase(cameraIdIter);
3697 } else {
3698 SET_ERR("Total result for frame %d has already returned for camera %s",
3699 frameNumber, physicalId.c_str());
3700 return;
3701 }
3702 }
Zhijun He204e3292014-07-14 17:09:23 -07003703 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003704 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003705 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003706 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003707 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003708 request.haveResultMetadata = true;
3709 }
3710
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003711 uint32_t numBuffersReturned = result->num_output_buffers;
3712 if (result->input_buffer != NULL) {
3713 if (hasInputBufferInRequest) {
3714 numBuffersReturned += 1;
3715 } else {
3716 ALOGW("%s: Input buffer should be NULL if there is no input"
3717 " buffer sent in the request",
3718 __FUNCTION__);
3719 }
3720 }
3721 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003722 if (request.numBuffersLeft < 0) {
3723 SET_ERR("Too many buffers returned for frame %d",
3724 frameNumber);
3725 return;
3726 }
3727
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003728 camera_metadata_ro_entry_t entry;
3729 res = find_camera_metadata_ro_entry(result->result,
3730 ANDROID_SENSOR_TIMESTAMP, &entry);
3731 if (res == OK && entry.count == 1) {
3732 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003733 }
3734
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003735 // If shutter event isn't received yet, append the output buffers to
3736 // the in-flight request. Otherwise, return the output buffers to
3737 // streams.
3738 if (shutterTimestamp == 0) {
3739 request.pendingOutputBuffers.appendArray(result->output_buffers,
3740 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003741 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003742 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003743 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003744 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3745 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003746 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003747
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003748 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003749 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3750 CameraMetadata physicalMetadata;
3751 physicalMetadata.append(result->physcam_metadata[i]);
3752 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3753 physicalMetadata});
3754 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003755 if (shutterTimestamp == 0) {
3756 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003757 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003758 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003759 CameraMetadata metadata;
3760 metadata = result->result;
3761 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003762 collectedPartialResult, frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003763 hasInputBufferInRequest, request.zslCapture && request.stillCapture,
3764 request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003765 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003766 }
3767
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003768 removeInFlightRequestIfReadyLocked(idx);
3769 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003770
Zhijun Hef0d962a2014-06-30 10:24:11 -07003771 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003772 if (hasInputBufferInRequest) {
3773 Camera3Stream *stream =
3774 Camera3Stream::cast(result->input_buffer->stream);
3775 res = stream->returnInputBuffer(*(result->input_buffer));
3776 // Note: stream may be deallocated at this point, if this buffer was the
3777 // last reference to it.
3778 if (res != OK) {
3779 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3780 " its stream:%s (%d)", __FUNCTION__,
3781 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003782 }
3783 } else {
3784 ALOGW("%s: Input buffer should be NULL if there is no input"
3785 " buffer sent in the request, skipping input buffer return.",
3786 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003787 }
3788 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003789}
3790
3791void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003792 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003793 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003794 {
3795 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003796 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003797 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003798
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003799 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003800 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003801 return;
3802 }
3803
3804 switch (msg->type) {
3805 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003806 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003807 break;
3808 }
3809 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003810 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003811 break;
3812 }
3813 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003814 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003815 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003816 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003817}
3818
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003819void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003820 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003821 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003822 // Map camera HAL error codes to ICameraDeviceCallback error codes
3823 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003824 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003825 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003826 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003827 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003828 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003829 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003830 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003831 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003832 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003833 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003834 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003835 };
3836
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003837 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003838 ((msg.error_code >= 0) &&
3839 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3840 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003841 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003842
3843 int streamId = 0;
Emilian Peevedec62d2019-03-19 17:59:24 -07003844 String16 physicalCameraId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003845 if (msg.error_stream != NULL) {
3846 Camera3Stream *stream =
3847 Camera3Stream::cast(msg.error_stream);
3848 streamId = stream->getId();
Emilian Peevedec62d2019-03-19 17:59:24 -07003849 physicalCameraId = String16(stream->physicalCameraId());
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003850 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003851 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3852 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003853 streamId, msg.error_code);
3854
3855 CaptureResultExtras resultExtras;
3856 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003857 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003858 // SET_ERR calls notifyError
3859 SET_ERR("Camera HAL reported serious device error");
3860 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003861 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3862 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3863 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003864 {
3865 Mutex::Autolock l(mInFlightLock);
3866 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3867 if (idx >= 0) {
3868 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3869 r.requestStatus = msg.error_code;
3870 resultExtras = r.resultExtras;
Emilian Peevedec62d2019-03-19 17:59:24 -07003871 bool logicalDeviceResultError = false;
3872 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3873 errorCode) {
3874 if (physicalCameraId.size() > 0) {
3875 String8 cameraId(physicalCameraId);
3876 if (r.physicalCameraIds.find(cameraId) == r.physicalCameraIds.end()) {
3877 ALOGE("%s: Reported result failure for physical camera device: %s "
3878 " which is not part of the respective request!",
3879 __FUNCTION__, cameraId.string());
3880 break;
3881 }
3882 resultExtras.errorPhysicalCameraId = physicalCameraId;
3883 } else {
3884 logicalDeviceResultError = true;
3885 }
3886 }
3887
3888 if (logicalDeviceResultError
Shuzhen Wang20f57342017-08-24 15:39:05 -07003889 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3890 errorCode) {
3891 r.skipResultMetadata = true;
3892 }
Emilian Peevedec62d2019-03-19 17:59:24 -07003893 if (logicalDeviceResultError) {
Emilian Peevba0fac32017-03-30 09:05:34 +01003894 // In case of missing result check whether the buffers
3895 // returned. If they returned, then remove inflight
3896 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003897 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3898 // otherwise we are depending on HAL to send the buffers back after
3899 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003900 removeInFlightRequestIfReadyLocked(idx);
3901 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003902 } else {
3903 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003904 ALOGE("Camera %s: %s: cannot find in-flight request on "
3905 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003906 resultExtras.frameNumber);
3907 }
3908 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003909 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003910 if (listener != NULL) {
3911 listener->notifyError(errorCode, resultExtras);
3912 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003913 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003914 }
3915 break;
3916 default:
3917 // SET_ERR calls notifyError
3918 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3919 break;
3920 }
3921}
3922
3923void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003924 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003925 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003926 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003927
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003928 // Set timestamp for the request in the in-flight tracking
3929 // and get the request ID to send upstream
3930 {
3931 Mutex::Autolock l(mInFlightLock);
3932 idx = mInFlightMap.indexOfKey(msg.frame_number);
3933 if (idx >= 0) {
3934 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003935
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003936 // Verify ordering of shutter notifications
3937 {
3938 Mutex::Autolock l(mOutputLock);
3939 // TODO: need to track errors for tighter bounds on expected frame number.
3940 if (r.hasInputBuffer) {
3941 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003942 SET_ERR("Reprocess shutter notification out-of-order. Expected "
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003943 "notification for frame %d, got frame %d",
3944 mNextReprocessShutterFrameNumber, msg.frame_number);
3945 return;
3946 }
3947 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003948 } else if (r.zslCapture && r.stillCapture) {
3949 if (msg.frame_number < mNextZslStillShutterFrameNumber) {
3950 SET_ERR("ZSL still capture shutter notification out-of-order. Expected "
3951 "notification for frame %d, got frame %d",
3952 mNextZslStillShutterFrameNumber, msg.frame_number);
3953 return;
3954 }
3955 mNextZslStillShutterFrameNumber = msg.frame_number + 1;
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003956 } else {
3957 if (msg.frame_number < mNextShutterFrameNumber) {
3958 SET_ERR("Shutter notification out-of-order. Expected "
3959 "notification for frame %d, got frame %d",
3960 mNextShutterFrameNumber, msg.frame_number);
3961 return;
3962 }
3963 mNextShutterFrameNumber = msg.frame_number + 1;
3964 }
3965 }
3966
Shuzhen Wang4a472662017-02-26 23:29:04 -08003967 r.shutterTimestamp = msg.timestamp;
3968 if (r.hasCallback) {
3969 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003970 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003971 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003972 // Call listener, if any
3973 if (listener != NULL) {
3974 listener->notifyShutter(r.resultExtras, msg.timestamp);
3975 }
3976 // send pending result and buffers
3977 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3978 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003979 r.hasInputBuffer, r.zslCapture && r.stillCapture,
3980 r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003981 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003982 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003983 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003984 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3985 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003986 r.pendingOutputBuffers.clear();
3987
3988 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003989 }
3990 }
3991 if (idx < 0) {
3992 SET_ERR("Shutter notification for non-existent frame number %d",
3993 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003994 }
3995}
3996
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003997CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003998 ALOGV("%s", __FUNCTION__);
3999
Igor Murashkin1e479c02013-09-06 16:55:14 -07004000 CameraMetadata retVal;
4001
4002 if (mRequestThread != NULL) {
4003 retVal = mRequestThread->getLatestRequest();
4004 }
4005
Igor Murashkin1e479c02013-09-06 16:55:14 -07004006 return retVal;
4007}
4008
Jianing Weicb0652e2014-03-12 18:29:36 -07004009
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004010void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004011 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
4012 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
4013
4014 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
4015 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004016}
4017
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004018/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004019 * HalInterface inner class methods
4020 */
4021
Yifan Hongf79b5542017-04-11 14:44:25 -07004022Camera3Device::HalInterface::HalInterface(
4023 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004024 std::shared_ptr<RequestMetadataQueue> queue,
4025 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004026 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004027 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08004028 mUseHalBufManager(useHalBufManager),
4029 mIsReconfigurationQuerySupported(true) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004030 // Check with hardware service manager if we can downcast these interfaces
4031 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004032 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
4033 if (castResult_3_5.isOk()) {
4034 mHidlSession_3_5 = castResult_3_5;
4035 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004036 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4037 if (castResult_3_4.isOk()) {
4038 mHidlSession_3_4 = castResult_3_4;
4039 }
4040 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
4041 if (castResult_3_3.isOk()) {
4042 mHidlSession_3_3 = castResult_3_3;
4043 }
4044}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004045
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004046Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004047
4048Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004049 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004050 mRequestMetadataQueue(other.mRequestMetadataQueue),
4051 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004052
4053bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004054 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004055}
4056
4057void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00004058 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00004059 mHidlSession_3_4.clear();
4060 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004061 mHidlSession.clear();
4062}
4063
4064status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
4065 camera3_request_template_t templateId,
4066 /*out*/ camera_metadata_t **requestTemplate) {
4067 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
4068 if (!valid()) return INVALID_OPERATION;
4069 status_t res = OK;
4070
Emilian Peev31abd0a2017-05-11 18:37:46 +01004071 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004072
4073 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01004074 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004075 status = s;
4076 if (status == common::V1_0::Status::OK) {
4077 const camera_metadata *r =
4078 reinterpret_cast<const camera_metadata_t*>(request.data());
4079 size_t expectedSize = request.size();
4080 int ret = validate_camera_metadata_structure(r, &expectedSize);
4081 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
4082 *requestTemplate = clone_camera_metadata(r);
4083 if (*requestTemplate == nullptr) {
4084 ALOGE("%s: Unable to clone camera metadata received from HAL",
4085 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004086 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004087 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004088 } else {
4089 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
4090 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004091 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004092 }
4093 };
4094 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004095 RequestTemplate id;
4096 switch (templateId) {
4097 case CAMERA3_TEMPLATE_PREVIEW:
4098 id = RequestTemplate::PREVIEW;
4099 break;
4100 case CAMERA3_TEMPLATE_STILL_CAPTURE:
4101 id = RequestTemplate::STILL_CAPTURE;
4102 break;
4103 case CAMERA3_TEMPLATE_VIDEO_RECORD:
4104 id = RequestTemplate::VIDEO_RECORD;
4105 break;
4106 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
4107 id = RequestTemplate::VIDEO_SNAPSHOT;
4108 break;
4109 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
4110 id = RequestTemplate::ZERO_SHUTTER_LAG;
4111 break;
4112 case CAMERA3_TEMPLATE_MANUAL:
4113 id = RequestTemplate::MANUAL;
4114 break;
4115 default:
4116 // Unknown template ID, or this HAL is too old to support it
4117 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004118 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004119 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004120
Emilian Peev31abd0a2017-05-11 18:37:46 +01004121 if (!err.isOk()) {
4122 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4123 res = DEAD_OBJECT;
4124 } else {
4125 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004126 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004127
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004128 return res;
4129}
4130
Emilian Peev4ec17882019-01-24 17:16:58 -08004131bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4132 CameraMetadata& newSessionParams) {
4133 // We do reconfiguration by default;
4134 bool ret = true;
4135 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4136 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4137 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4138 oldSessionParams.getAndLock());
4139 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4140 newSessionParams.getAndLock());
4141 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4142 get_camera_metadata_size(oldSessioMeta));
4143 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4144 get_camera_metadata_size(newSessioMeta));
4145 hardware::camera::common::V1_0::Status callStatus;
4146 bool required;
4147 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4148 bool requiredFlag) {
4149 callStatus = s;
4150 required = requiredFlag;
4151 };
4152 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4153 oldSessionParams.unlock(oldSessioMeta);
4154 newSessionParams.unlock(newSessioMeta);
4155 if (err.isOk()) {
4156 switch (callStatus) {
4157 case hardware::camera::common::V1_0::Status::OK:
4158 ret = required;
4159 break;
4160 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4161 mIsReconfigurationQuerySupported = false;
4162 ret = true;
4163 break;
4164 default:
4165 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4166 ret = true;
4167 }
4168 } else {
4169 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4170 ret = true;
4171 }
4172 }
4173
4174 return ret;
4175}
4176
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004177status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004178 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004179 ATRACE_NAME("CameraHal::configureStreams");
4180 if (!valid()) return INVALID_OPERATION;
4181 status_t res = OK;
4182
Emilian Peev31abd0a2017-05-11 18:37:46 +01004183 // Convert stream config to HIDL
4184 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004185 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4186 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4187 requestedConfiguration3_2.streams.resize(config->num_streams);
4188 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004189 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004190 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4191 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004192 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004193
Emilian Peev31abd0a2017-05-11 18:37:46 +01004194 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4195 cam3stream->setBufferFreedListener(this);
4196 int streamId = cam3stream->getId();
4197 StreamType streamType;
4198 switch (src->stream_type) {
4199 case CAMERA3_STREAM_OUTPUT:
4200 streamType = StreamType::OUTPUT;
4201 break;
4202 case CAMERA3_STREAM_INPUT:
4203 streamType = StreamType::INPUT;
4204 break;
4205 default:
4206 ALOGE("%s: Stream %d: Unsupported stream type %d",
4207 __FUNCTION__, streamId, config->streams[i]->stream_type);
4208 return BAD_VALUE;
4209 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004210 dst3_2.id = streamId;
4211 dst3_2.streamType = streamType;
4212 dst3_2.width = src->width;
4213 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004214 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004215 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07004216 // For HidlSession version 3.5 or newer, the format and dataSpace sent
4217 // to HAL are original, not the overriden ones.
4218 if (mHidlSession_3_5 != nullptr) {
4219 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
4220 cam3stream->getOriginalFormat() : src->format);
4221 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
4222 cam3stream->getOriginalDataSpace() : src->data_space);
4223 } else {
4224 dst3_2.format = mapToPixelFormat(src->format);
4225 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4226 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004227 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004228 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004229 if (src->physical_camera_id != nullptr) {
4230 dst3_4.physicalCameraId = src->physical_camera_id;
4231 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004232
4233 activeStreams.insert(streamId);
4234 // Create Buffer ID map if necessary
4235 if (mBufferIdMaps.count(streamId) == 0) {
4236 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4237 }
4238 }
4239 // remove BufferIdMap for deleted streams
4240 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4241 int streamId = it->first;
4242 bool active = activeStreams.count(streamId) > 0;
4243 if (!active) {
4244 it = mBufferIdMaps.erase(it);
4245 } else {
4246 ++it;
4247 }
4248 }
4249
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004250 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004251 res = mapToStreamConfigurationMode(
4252 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004253 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004254 if (res != OK) {
4255 return res;
4256 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004257 requestedConfiguration3_2.operationMode = operationMode;
4258 requestedConfiguration3_4.operationMode = operationMode;
4259 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004260 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4261 get_camera_metadata_size(sessionParams));
4262
Emilian Peev31abd0a2017-05-11 18:37:46 +01004263 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004264 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004265 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004266 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004267
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004268 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004269 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4270 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004271 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004272 };
4273
4274 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4275 (hardware::Return<void>& err) -> status_t {
4276 if (!err.isOk()) {
4277 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4278 return DEAD_OBJECT;
4279 }
4280 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4281 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4282 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4283 }
4284 return OK;
4285 };
4286
Shuzhen Wang92653952019-05-07 15:11:43 -07004287 // See which version of HAL we have
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004288 if (mHidlSession_3_5 != nullptr) {
4289 ALOGV("%s: v3.5 device found", __FUNCTION__);
4290 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4291 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4292 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4293 auto err = mHidlSession_3_5->configureStreams_3_5(
4294 requestedConfiguration3_5, configStream34Cb);
4295 res = postprocConfigStream34(err);
4296 if (res != OK) {
4297 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004298 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004299 } else if (mHidlSession_3_4 != nullptr) {
4300 // We do; use v3.4 for the call
4301 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004302 auto err = mHidlSession_3_4->configureStreams_3_4(
4303 requestedConfiguration3_4, configStream34Cb);
4304 res = postprocConfigStream34(err);
4305 if (res != OK) {
4306 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004307 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004308 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004309 // We do; use v3.3 for the call
4310 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004311 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004312 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004313 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004314 finalConfiguration = halConfiguration;
4315 status = s;
4316 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004317 if (!err.isOk()) {
4318 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4319 return DEAD_OBJECT;
4320 }
4321 } else {
4322 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4323 ALOGV("%s: v3.2 device found", __FUNCTION__);
4324 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004325 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004326 [&status, &finalConfiguration_3_2]
4327 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4328 finalConfiguration_3_2 = halConfiguration;
4329 status = s;
4330 });
4331 if (!err.isOk()) {
4332 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4333 return DEAD_OBJECT;
4334 }
4335 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4336 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4337 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4338 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004339 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004340 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004341 }
4342
4343 if (status != common::V1_0::Status::OK ) {
4344 return CameraProviderManager::mapToStatusT(status);
4345 }
4346
4347 // And convert output stream configuration from HIDL
4348
4349 for (size_t i = 0; i < config->num_streams; i++) {
4350 camera3_stream_t *dst = config->streams[i];
4351 int streamId = Camera3Stream::cast(dst)->getId();
4352
4353 // Start scan at i, with the assumption that the stream order matches
4354 size_t realIdx = i;
4355 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004356 size_t halStreamCount = finalConfiguration.streams.size();
4357 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004358 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004359 found = true;
4360 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004361 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004362 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004363 }
4364 if (!found) {
4365 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4366 __FUNCTION__, streamId);
4367 return INVALID_OPERATION;
4368 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004369 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004370
Emilian Peev710c1422017-08-30 11:19:38 +01004371 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004372 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4373 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4374
Yin-Chia Yeh90667662019-07-01 15:45:00 -07004375 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07004376 dstStream->setFormatOverride(false);
4377 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004378 if (dst->format != overrideFormat) {
4379 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4380 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004381 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004382 if (dst->data_space != overrideDataSpace) {
4383 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4384 streamId, dst->format);
4385 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004386 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07004387 bool needFormatOverride =
4388 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
4389 bool needDataspaceOverride =
4390 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004391 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07004392 dstStream->setFormatOverride(needFormatOverride);
4393 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004394 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004395 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004396 }
4397
Emilian Peev31abd0a2017-05-11 18:37:46 +01004398 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004399 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004400 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004401 __FUNCTION__, streamId);
4402 return INVALID_OPERATION;
4403 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004404 dstStream->setUsage(
4405 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004406 } else {
4407 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004408 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004409 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4410 __FUNCTION__, streamId);
4411 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004412 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004413 dstStream->setUsage(
4414 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004415 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004416 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004417 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004418
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004419 return res;
4420}
4421
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004422status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004423 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004424 /*out*/std::vector<native_handle_t*>* handlesCreated,
4425 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004426 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004427 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
4428 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
4429 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004430 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004431 }
4432
4433 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004434
4435 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004436
4437 {
4438 std::lock_guard<std::mutex> lock(mInflightLock);
4439 if (request->input_buffer != nullptr) {
4440 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4441 buffer_handle_t buf = *(request->input_buffer->buffer);
4442 auto pair = getBufferId(buf, streamId);
4443 bool isNewBuffer = pair.first;
4444 uint64_t bufferId = pair.second;
4445 captureRequest->inputBuffer.streamId = streamId;
4446 captureRequest->inputBuffer.bufferId = bufferId;
4447 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4448 captureRequest->inputBuffer.status = BufferStatus::OK;
4449 native_handle_t *acquireFence = nullptr;
4450 if (request->input_buffer->acquire_fence != -1) {
4451 acquireFence = native_handle_create(1,0);
4452 acquireFence->data[0] = request->input_buffer->acquire_fence;
4453 handlesCreated->push_back(acquireFence);
4454 }
4455 captureRequest->inputBuffer.acquireFence = acquireFence;
4456 captureRequest->inputBuffer.releaseFence = nullptr;
4457
4458 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004459 request->input_buffer->buffer);
4460 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004461 } else {
4462 captureRequest->inputBuffer.streamId = -1;
4463 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4464 }
4465
4466 captureRequest->outputBuffers.resize(request->num_output_buffers);
4467 for (size_t i = 0; i < request->num_output_buffers; i++) {
4468 const camera3_stream_buffer_t *src = request->output_buffers + i;
4469 StreamBuffer &dst = captureRequest->outputBuffers[i];
4470 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004471 if (src->buffer != nullptr) {
4472 buffer_handle_t buf = *(src->buffer);
4473 auto pair = getBufferId(buf, streamId);
4474 bool isNewBuffer = pair.first;
4475 dst.bufferId = pair.second;
4476 dst.buffer = isNewBuffer ? buf : nullptr;
4477 native_handle_t *acquireFence = nullptr;
4478 if (src->acquire_fence != -1) {
4479 acquireFence = native_handle_create(1,0);
4480 acquireFence->data[0] = src->acquire_fence;
4481 handlesCreated->push_back(acquireFence);
4482 }
4483 dst.acquireFence = acquireFence;
4484 } else if (mUseHalBufManager) {
4485 // HAL buffer management path
4486 dst.bufferId = BUFFER_ID_NO_BUFFER;
4487 dst.buffer = nullptr;
4488 dst.acquireFence = nullptr;
4489 } else {
4490 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4491 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004492 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004493 dst.streamId = streamId;
4494 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004495 dst.releaseFence = nullptr;
4496
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004497 // Output buffers are empty when using HAL buffer manager
4498 if (!mUseHalBufManager) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004499 pushInflightBufferLocked(captureRequest->frameNumber, streamId, src->buffer);
4500 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004501 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004502 }
4503 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004504 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004505}
4506
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004507void Camera3Device::HalInterface::cleanupNativeHandles(
4508 std::vector<native_handle_t*> *handles, bool closeFd) {
4509 if (handles == nullptr) {
4510 return;
4511 }
4512 if (closeFd) {
4513 for (auto& handle : *handles) {
4514 native_handle_close(handle);
4515 }
4516 }
4517 for (auto& handle : *handles) {
4518 native_handle_delete(handle);
4519 }
4520 handles->clear();
4521 return;
4522}
4523
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004524status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4525 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4526 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4527 if (!valid()) return INVALID_OPERATION;
4528
Emilian Peevaebbe412018-01-15 13:53:24 +00004529 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4530 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4531 if (castResult_3_4.isOk()) {
4532 hidlSession_3_4 = castResult_3_4;
4533 }
4534
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004535 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004536 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004537 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004538 if (hidlSession_3_4 != nullptr) {
4539 captureRequests_3_4.resize(batchSize);
4540 } else {
4541 captureRequests.resize(batchSize);
4542 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004543 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004544 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004545
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004546 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004547 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004548 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004549 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004550 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00004551 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004552 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
4553 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004554 }
4555 if (res != OK) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004556 popInflightBuffers(inflightBuffers);
4557 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004558 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004559 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004560 }
4561
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004562 std::vector<device::V3_2::BufferCache> cachesToRemove;
4563 {
4564 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4565 for (auto& pair : mFreedBuffers) {
4566 // The stream might have been removed since onBufferFreed
4567 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4568 cachesToRemove.push_back({pair.first, pair.second});
4569 }
4570 }
4571 mFreedBuffers.clear();
4572 }
4573
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004574 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4575 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004576
4577 // Write metadata to FMQ.
4578 for (size_t i = 0; i < batchSize; i++) {
4579 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004580 device::V3_2::CaptureRequest* captureRequest;
4581 if (hidlSession_3_4 != nullptr) {
4582 captureRequest = &captureRequests_3_4[i].v3_2;
4583 } else {
4584 captureRequest = &captureRequests[i];
4585 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004586
4587 if (request->settings != nullptr) {
4588 size_t settingsSize = get_camera_metadata_size(request->settings);
4589 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4590 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4591 captureRequest->settings.resize(0);
4592 captureRequest->fmqSettingsSize = settingsSize;
4593 } else {
4594 if (mRequestMetadataQueue != nullptr) {
4595 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4596 }
4597 captureRequest->settings.setToExternal(
4598 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4599 get_camera_metadata_size(request->settings));
4600 captureRequest->fmqSettingsSize = 0u;
4601 }
4602 } else {
4603 // A null request settings maps to a size-0 CameraMetadata
4604 captureRequest->settings.resize(0);
4605 captureRequest->fmqSettingsSize = 0u;
4606 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004607
4608 if (hidlSession_3_4 != nullptr) {
4609 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4610 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004611 if (request->physcam_settings != nullptr) {
4612 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4613 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4614 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4615 settingsSize)) {
4616 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4617 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4618 settingsSize;
4619 } else {
4620 if (mRequestMetadataQueue != nullptr) {
4621 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4622 }
4623 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4624 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4625 request->physcam_settings[j])),
4626 get_camera_metadata_size(request->physcam_settings[j]));
4627 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004628 }
Emilian Peev00420d22018-02-05 21:33:13 +00004629 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004630 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004631 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004632 }
4633 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4634 request->physcam_id[j];
4635 }
4636 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004637 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004638
4639 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004640 auto resultCallback =
4641 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4642 status = s;
4643 *numRequestProcessed = n;
4644 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004645 if (hidlSession_3_4 != nullptr) {
4646 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004647 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004648 } else {
4649 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004650 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004651 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004652 if (!err.isOk()) {
4653 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004654 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004655 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004656
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004657 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4658 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4659 __FUNCTION__, *numRequestProcessed, batchSize);
4660 status = common::V1_0::Status::INTERNAL_ERROR;
4661 }
4662
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004663 res = CameraProviderManager::mapToStatusT(status);
4664 if (res == OK) {
4665 if (mHidlSession->isRemote()) {
4666 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
4667 // sent to camera HAL processes)
4668 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
4669 } else {
4670 // In passthrough mode the FDs are now owned by HAL
4671 cleanupNativeHandles(&handlesCreated);
4672 }
4673 } else {
4674 popInflightBuffers(inflightBuffers);
4675 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004676 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004677 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004678}
4679
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004680status_t Camera3Device::HalInterface::flush() {
4681 ATRACE_NAME("CameraHal::flush");
4682 if (!valid()) return INVALID_OPERATION;
4683 status_t res = OK;
4684
Emilian Peev31abd0a2017-05-11 18:37:46 +01004685 auto err = mHidlSession->flush();
4686 if (!err.isOk()) {
4687 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4688 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004689 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004690 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004691 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004692
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004693 return res;
4694}
4695
Emilian Peev31abd0a2017-05-11 18:37:46 +01004696status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004697 ATRACE_NAME("CameraHal::dump");
4698 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004699
Emilian Peev31abd0a2017-05-11 18:37:46 +01004700 // Handled by CameraProviderManager::dump
4701
4702 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004703}
4704
4705status_t Camera3Device::HalInterface::close() {
4706 ATRACE_NAME("CameraHal::close()");
4707 if (!valid()) return INVALID_OPERATION;
4708 status_t res = OK;
4709
Emilian Peev31abd0a2017-05-11 18:37:46 +01004710 auto err = mHidlSession->close();
4711 // Interface will be dead shortly anyway, so don't log errors
4712 if (!err.isOk()) {
4713 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004714 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004715
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004716 return res;
4717}
4718
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004719void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4720 ATRACE_NAME("CameraHal::signalPipelineDrain");
4721 if (!valid() || mHidlSession_3_5 == nullptr) {
4722 ALOGE("%s called on invalid camera!", __FUNCTION__);
4723 return;
4724 }
4725
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004726 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004727 if (!err.isOk()) {
4728 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4729 return;
4730 }
4731}
4732
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004733void Camera3Device::HalInterface::getInflightBufferKeys(
4734 std::vector<std::pair<int32_t, int32_t>>* out) {
4735 std::lock_guard<std::mutex> lock(mInflightLock);
4736 out->clear();
4737 out->reserve(mInflightBufferMap.size());
4738 for (auto& pair : mInflightBufferMap) {
4739 uint64_t key = pair.first;
4740 int32_t streamId = key & 0xFFFFFFFF;
4741 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4742 out->push_back(std::make_pair(frameNumber, streamId));
4743 }
4744 return;
4745}
4746
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004747void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4748 std::vector<uint64_t>* out) {
4749 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4750 out->clear();
4751 out->reserve(mRequestedBuffers.size());
4752 for (auto& pair : mRequestedBuffers) {
4753 out->push_back(pair.first);
4754 }
4755 return;
4756}
4757
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004758status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004759 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004760 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004761 mInflightBufferMap[key] = buffer;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004762 return OK;
4763}
4764
4765status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004766 int32_t frameNumber, int32_t streamId,
4767 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004768 std::lock_guard<std::mutex> lock(mInflightLock);
4769
4770 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4771 auto it = mInflightBufferMap.find(key);
4772 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004773 if (buffer != nullptr) {
4774 *buffer = it->second;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004775 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004776 mInflightBufferMap.erase(it);
4777 return OK;
4778}
4779
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004780void Camera3Device::HalInterface::popInflightBuffers(
4781 const std::vector<std::pair<int32_t, int32_t>>& buffers) {
4782 for (const auto& pair : buffers) {
4783 int32_t frameNumber = pair.first;
4784 int32_t streamId = pair.second;
4785 popInflightBuffer(frameNumber, streamId, nullptr);
4786 }
4787}
4788
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004789status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004790 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004791 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004792 auto pair = mRequestedBuffers.insert({bufferId, {streamId, buf}});
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004793 if (!pair.second) {
4794 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4795 __FUNCTION__, bufferId);
4796 return BAD_VALUE;
4797 }
4798 return OK;
4799}
4800
4801// Find and pop a buffer_handle_t based on bufferId
4802status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004803 uint64_t bufferId,
4804 /*out*/ buffer_handle_t** buffer,
4805 /*optional out*/ int32_t* streamId) {
4806 if (buffer == nullptr) {
4807 ALOGE("%s: buffer (%p) must not be null", __FUNCTION__, buffer);
4808 return BAD_VALUE;
4809 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004810 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4811 auto it = mRequestedBuffers.find(bufferId);
4812 if (it == mRequestedBuffers.end()) {
4813 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4814 __FUNCTION__, bufferId);
4815 return BAD_VALUE;
4816 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004817 *buffer = it->second.second;
4818 if (streamId != nullptr) {
4819 *streamId = it->second.first;
4820 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004821 mRequestedBuffers.erase(it);
4822 return OK;
4823}
4824
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004825std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4826 const buffer_handle_t& buf, int streamId) {
4827 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4828
4829 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4830 auto it = bIdMap.find(buf);
4831 if (it == bIdMap.end()) {
4832 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004833 ALOGV("stream %d now have %zu buffer caches, buf %p",
4834 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004835 return std::make_pair(true, mNextBufferId - 1);
4836 } else {
4837 return std::make_pair(false, it->second);
4838 }
4839}
4840
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004841void Camera3Device::HalInterface::onBufferFreed(
4842 int streamId, const native_handle_t* handle) {
4843 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4844 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4845 auto mapIt = mBufferIdMaps.find(streamId);
4846 if (mapIt == mBufferIdMaps.end()) {
4847 // streamId might be from a deleted stream here
4848 ALOGI("%s: stream %d has been removed",
4849 __FUNCTION__, streamId);
4850 return;
4851 }
4852 BufferIdMap& bIdMap = mapIt->second;
4853 auto it = bIdMap.find(handle);
4854 if (it == bIdMap.end()) {
4855 ALOGW("%s: cannot find buffer %p in stream %d",
4856 __FUNCTION__, handle, streamId);
4857 return;
4858 } else {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004859 bufferId = it->second;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004860 bIdMap.erase(it);
4861 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4862 __FUNCTION__, streamId, bIdMap.size(), handle);
4863 }
4864 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4865}
4866
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004867void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
4868 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4869 auto mapIt = mBufferIdMaps.find(streamId);
4870 if (mapIt == mBufferIdMaps.end()) {
4871 ALOGE("%s: streamId %d not found!", __FUNCTION__, streamId);
4872 return;
4873 }
4874
4875 BufferIdMap& bIdMap = mapIt->second;
4876 for (const auto& it : bIdMap) {
4877 uint64_t bufferId = it.second;
4878 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4879 }
4880 bIdMap.clear();
4881}
4882
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004883/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004884 * RequestThread inner class methods
4885 */
4886
4887Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004888 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004889 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4890 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004891 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004892 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004893 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004894 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004895 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004896 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004897 mReconfigured(false),
4898 mDoPause(false),
4899 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004900 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004901 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004902 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004903 mCurrentAfTriggerId(0),
4904 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004905 mRepeatingLastFrameNumber(
4906 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004907 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004908 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004909 mRequestLatency(kRequestLatencyBinSize),
4910 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004911 mLatestSessionParams(sessionParamKeys.size()),
4912 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004913 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004914}
4915
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004916Camera3Device::RequestThread::~RequestThread() {}
4917
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004918void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004919 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004920 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004921 Mutex::Autolock l(mRequestLock);
4922 mListener = listener;
4923}
4924
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004925void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4926 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004927 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004928 Mutex::Autolock l(mRequestLock);
4929 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004930 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004931 // Prepare video stream for high speed recording.
4932 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004933 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004934}
4935
Jianing Wei90e59c92014-03-12 18:29:36 -07004936status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004937 List<sp<CaptureRequest> > &requests,
4938 /*out*/
4939 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004940 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004941 Mutex::Autolock l(mRequestLock);
4942 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4943 ++it) {
4944 mRequestQueue.push_back(*it);
4945 }
4946
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004947 if (lastFrameNumber != NULL) {
4948 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4949 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4950 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4951 *lastFrameNumber);
4952 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004953
Jianing Wei90e59c92014-03-12 18:29:36 -07004954 unpauseForNewRequests();
4955
4956 return OK;
4957}
4958
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004959
4960status_t Camera3Device::RequestThread::queueTrigger(
4961 RequestTrigger trigger[],
4962 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004963 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004964 Mutex::Autolock l(mTriggerMutex);
4965 status_t ret;
4966
4967 for (size_t i = 0; i < count; ++i) {
4968 ret = queueTriggerLocked(trigger[i]);
4969
4970 if (ret != OK) {
4971 return ret;
4972 }
4973 }
4974
4975 return OK;
4976}
4977
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004978const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4979 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004980 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004981 if (d != nullptr) return d->mId;
4982 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004983}
4984
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004985status_t Camera3Device::RequestThread::queueTriggerLocked(
4986 RequestTrigger trigger) {
4987
4988 uint32_t tag = trigger.metadataTag;
4989 ssize_t index = mTriggerMap.indexOfKey(tag);
4990
4991 switch (trigger.getTagType()) {
4992 case TYPE_BYTE:
4993 // fall-through
4994 case TYPE_INT32:
4995 break;
4996 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004997 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4998 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004999 return INVALID_OPERATION;
5000 }
5001
5002 /**
5003 * Collect only the latest trigger, since we only have 1 field
5004 * in the request settings per trigger tag, and can't send more than 1
5005 * trigger per request.
5006 */
5007 if (index != NAME_NOT_FOUND) {
5008 mTriggerMap.editValueAt(index) = trigger;
5009 } else {
5010 mTriggerMap.add(tag, trigger);
5011 }
5012
5013 return OK;
5014}
5015
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005016status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005017 const RequestList &requests,
5018 /*out*/
5019 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005020 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005021 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005022 if (lastFrameNumber != NULL) {
5023 *lastFrameNumber = mRepeatingLastFrameNumber;
5024 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005025 mRepeatingRequests.clear();
5026 mRepeatingRequests.insert(mRepeatingRequests.begin(),
5027 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005028
5029 unpauseForNewRequests();
5030
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005031 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005032 return OK;
5033}
5034
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07005035bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005036 if (mRepeatingRequests.empty()) {
5037 return false;
5038 }
5039 int32_t requestId = requestIn->mResultExtras.requestId;
5040 const RequestList &repeatRequests = mRepeatingRequests;
5041 // All repeating requests are guaranteed to have same id so only check first quest
5042 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
5043 return (firstRequest->mResultExtras.requestId == requestId);
5044}
5045
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005046status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005047 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005048 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005049 return clearRepeatingRequestsLocked(lastFrameNumber);
5050
5051}
5052
5053status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005054 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005055 if (lastFrameNumber != NULL) {
5056 *lastFrameNumber = mRepeatingLastFrameNumber;
5057 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005058 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005059 return OK;
5060}
5061
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005062status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005063 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005064 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005065 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005066 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005067
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005068 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005069
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005070 // Send errors for all requests pending in the request queue, including
5071 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005072 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005073 if (listener != NULL) {
5074 for (RequestList::iterator it = mRequestQueue.begin();
5075 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005076 // Abort the input buffers for reprocess requests.
5077 if ((*it)->mInputStream != NULL) {
5078 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07005079 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
5080 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005081 if (res != OK) {
5082 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
5083 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5084 } else {
5085 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
5086 if (res != OK) {
5087 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
5088 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5089 }
5090 }
5091 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005092 // Set the frame number this request would have had, if it
5093 // had been submitted; this frame number will not be reused.
5094 // The requestId and burstId fields were set when the request was
5095 // submitted originally (in convertMetadataListToRequestListLocked)
5096 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005097 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005098 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005099 }
5100 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005101 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08005102
5103 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005104 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005105 if (lastFrameNumber != NULL) {
5106 *lastFrameNumber = mRepeatingLastFrameNumber;
5107 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005108 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005109 return OK;
5110}
5111
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005112status_t Camera3Device::RequestThread::flush() {
5113 ATRACE_CALL();
5114 Mutex::Autolock l(mFlushLock);
5115
Emilian Peev08dd2452017-04-06 16:55:14 +01005116 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005117}
5118
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005119void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005120 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005121 Mutex::Autolock l(mPauseLock);
5122 mDoPause = paused;
5123 mDoPauseSignal.signal();
5124}
5125
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005126status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
5127 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005128 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005129 Mutex::Autolock l(mLatestRequestMutex);
5130 status_t res;
5131 while (mLatestRequestId != requestId) {
5132 nsecs_t startTime = systemTime();
5133
5134 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
5135 if (res != OK) return res;
5136
5137 timeout -= (systemTime() - startTime);
5138 }
5139
5140 return OK;
5141}
5142
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005143void Camera3Device::RequestThread::requestExit() {
5144 // Call parent to set up shutdown
5145 Thread::requestExit();
5146 // The exit from any possible waits
5147 mDoPauseSignal.signal();
5148 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07005149
5150 mRequestLatency.log("ProcessCaptureRequest latency histogram");
5151 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005152}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005153
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005154void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005155 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005156 bool surfaceAbandoned = false;
5157 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005158 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005159 {
5160 Mutex::Autolock l(mRequestLock);
5161 // Check all streams needed by repeating requests are still valid. Otherwise, stop
5162 // repeating requests.
5163 for (const auto& request : mRepeatingRequests) {
5164 for (const auto& s : request->mOutputStreams) {
5165 if (s->isAbandoned()) {
5166 surfaceAbandoned = true;
5167 clearRepeatingRequestsLocked(&lastFrameNumber);
5168 break;
5169 }
5170 }
5171 if (surfaceAbandoned) {
5172 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005173 }
5174 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005175 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005176 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005177
5178 if (listener != NULL && surfaceAbandoned) {
5179 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005180 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005181}
5182
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005183bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005184 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005185 status_t res;
5186 size_t batchSize = mNextRequests.size();
5187 std::vector<camera3_capture_request_t*> requests(batchSize);
5188 uint32_t numRequestProcessed = 0;
5189 for (size_t i = 0; i < batchSize; i++) {
5190 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07005191 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005192 }
5193
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005194 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
5195
5196 bool triggerRemoveFailed = false;
5197 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
5198 for (size_t i = 0; i < numRequestProcessed; i++) {
5199 NextRequest& nextRequest = mNextRequests.editItemAt(i);
5200 nextRequest.submitted = true;
5201
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005202 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00005203
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005204 if (!triggerRemoveFailed) {
5205 // Remove any previously queued triggers (after unlock)
5206 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5207 if (removeTriggerRes != OK) {
5208 triggerRemoveFailed = true;
5209 triggerFailedRequest = nextRequest;
5210 }
5211 }
5212 }
5213
5214 if (triggerRemoveFailed) {
5215 SET_ERR("RequestThread: Unable to remove triggers "
5216 "(capture request %d, HAL device: %s (%d)",
5217 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5218 cleanUpFailedRequests(/*sendRequestError*/ false);
5219 return false;
5220 }
5221
5222 if (res != OK) {
5223 // Should only get a failure here for malformed requests or device-level
5224 // errors, so consider all errors fatal. Bad metadata failures should
5225 // come through notify.
5226 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5227 mNextRequests[numRequestProcessed].halRequest.frame_number,
5228 strerror(-res), res);
5229 cleanUpFailedRequests(/*sendRequestError*/ false);
5230 return false;
5231 }
5232 return true;
5233}
5234
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005235nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5236 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5237 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5238 find_camera_metadata_ro_entry(request,
5239 ANDROID_CONTROL_AE_MODE,
5240 &e);
5241 if (e.count == 0) return maxExpectedDuration;
5242
5243 switch (e.data.u8[0]) {
5244 case ANDROID_CONTROL_AE_MODE_OFF:
5245 find_camera_metadata_ro_entry(request,
5246 ANDROID_SENSOR_EXPOSURE_TIME,
5247 &e);
5248 if (e.count > 0) {
5249 maxExpectedDuration = e.data.i64[0];
5250 }
5251 find_camera_metadata_ro_entry(request,
5252 ANDROID_SENSOR_FRAME_DURATION,
5253 &e);
5254 if (e.count > 0) {
5255 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5256 }
5257 break;
5258 default:
5259 find_camera_metadata_ro_entry(request,
5260 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5261 &e);
5262 if (e.count > 1) {
5263 maxExpectedDuration = 1e9 / e.data.u8[0];
5264 }
5265 break;
5266 }
5267
5268 return maxExpectedDuration;
5269}
5270
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005271bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5272 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5273 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5274 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5275 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5276 return true;
5277 }
5278
5279 return false;
5280}
5281
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005282void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
5283 // Update the latest request sent to HAL
5284 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5285 Mutex::Autolock al(mLatestRequestMutex);
5286
5287 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5288 mLatestRequest.acquire(cloned);
5289
5290 mLatestPhysicalRequest.clear();
5291 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
5292 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
5293 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
5294 CameraMetadata(cloned));
5295 }
5296
5297 sp<Camera3Device> parent = mParent.promote();
5298 if (parent != NULL) {
5299 parent->monitorMetadata(TagMonitor::REQUEST,
5300 nextRequest.halRequest.frame_number,
5301 0, mLatestRequest, mLatestPhysicalRequest);
5302 }
5303 }
5304
5305 if (nextRequest.halRequest.settings != NULL) {
5306 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5307 nextRequest.halRequest.settings);
5308 }
5309
5310 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5311}
5312
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005313bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5314 ATRACE_CALL();
5315 bool updatesDetected = false;
5316
Emilian Peev4ec17882019-01-24 17:16:58 -08005317 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005318 for (auto tag : mSessionParamKeys) {
5319 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005320 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005321
5322 if (entry.count > 0) {
5323 bool isDifferent = false;
5324 if (lastEntry.count > 0) {
5325 // Have a last value, compare to see if changed
5326 if (lastEntry.type == entry.type &&
5327 lastEntry.count == entry.count) {
5328 // Same type and count, compare values
5329 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5330 size_t entryBytes = bytesPerValue * lastEntry.count;
5331 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5332 if (cmp != 0) {
5333 isDifferent = true;
5334 }
5335 } else {
5336 // Count or type has changed
5337 isDifferent = true;
5338 }
5339 } else {
5340 // No last entry, so always consider to be different
5341 isDifferent = true;
5342 }
5343
5344 if (isDifferent) {
5345 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005346 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5347 updatesDetected = true;
5348 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005349 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005350 }
5351 } else if (lastEntry.count > 0) {
5352 // Value has been removed
5353 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005354 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005355 updatesDetected = true;
5356 }
5357 }
5358
Emilian Peev4ec17882019-01-24 17:16:58 -08005359 bool reconfigureRequired;
5360 if (updatesDetected) {
5361 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5362 updatedParams);
5363 mLatestSessionParams = updatedParams;
5364 } else {
5365 reconfigureRequired = false;
5366 }
5367
5368 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005369}
5370
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005371bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005372 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005373 status_t res;
5374
5375 // Handle paused state.
5376 if (waitIfPaused()) {
5377 return true;
5378 }
5379
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005380 // Wait for the next batch of requests.
5381 waitForNextRequestBatch();
5382 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005383 return true;
5384 }
5385
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005386 // Get the latest request ID, if any
5387 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005388 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005389 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005390 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005391 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005392 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005393 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5394 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005395 }
5396
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005397 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5398 // or a single request from streaming or burst. In either case the first element
5399 // should contain the latest camera settings that we need to check for any session
5400 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005401 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005402 res = OK;
5403
5404 //Input stream buffers are already acquired at this point so an input stream
5405 //will not be able to move to idle state unless we force it.
5406 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5407 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5408 if (res != OK) {
5409 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5410 cleanUpFailedRequests(/*sendRequestError*/ false);
5411 return false;
5412 }
5413 }
5414
5415 if (res == OK) {
5416 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5417 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005418 sp<Camera3Device> parent = mParent.promote();
5419 if (parent != nullptr) {
5420 parent->pauseStateNotify(true);
5421 }
5422
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005423 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5424
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005425 if (parent != nullptr) {
5426 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5427 }
5428
5429 statusTracker->markComponentActive(mStatusId);
5430 setPaused(false);
5431 }
5432
5433 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5434 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5435 if (res != OK) {
5436 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5437 cleanUpFailedRequests(/*sendRequestError*/ false);
5438 return false;
5439 }
5440 }
5441 }
5442 }
5443
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005444 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005445 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005446 if (res == TIMED_OUT) {
5447 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005448 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005449 // Check if any stream is abandoned.
5450 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005451 return true;
5452 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005453 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005454 return false;
5455 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005456
Zhijun Hecc27e112013-10-03 16:12:43 -07005457 // Inform waitUntilRequestProcessed thread of a new request ID
5458 {
5459 Mutex::Autolock al(mLatestRequestMutex);
5460
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005461 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005462 mLatestRequestSignal.signal();
5463 }
5464
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005465 // Submit a batch of requests to HAL.
5466 // Use flush lock only when submitting multilple requests in a batch.
5467 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5468 // which may take a long time to finish so synchronizing flush() and
5469 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5470 // For now, only synchronize for high speed recording and we should figure something out for
5471 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005472 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005473
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005474 if (useFlushLock) {
5475 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005476 }
5477
Zhijun Hef0645c12016-08-02 00:58:11 -07005478 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005479 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005480
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005481 sp<Camera3Device> parent = mParent.promote();
5482 if (parent != nullptr) {
5483 parent->mRequestBufferSM.onSubmittingRequest();
5484 }
5485
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005486 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005487 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07005488 submitRequestSuccess = sendRequestsBatch();
5489
Shuzhen Wang686f6442017-06-20 16:16:04 -07005490 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5491 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005492
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005493 if (useFlushLock) {
5494 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005495 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005496
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005497 // Unset as current request
5498 {
5499 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005500 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005501 }
5502
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005503 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005504}
5505
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005506status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005507 ATRACE_CALL();
5508
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005509 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005510 for (size_t i = 0; i < mNextRequests.size(); i++) {
5511 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005512 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5513 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5514 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5515
5516 // Prepare a request to HAL
5517 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5518
5519 // Insert any queued triggers (before metadata is locked)
5520 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005521 if (res < 0) {
5522 SET_ERR("RequestThread: Unable to insert triggers "
5523 "(capture request %d, HAL device: %s (%d)",
5524 halRequest->frame_number, strerror(-res), res);
5525 return INVALID_OPERATION;
5526 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005527
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005528 int triggerCount = res;
5529 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5530 mPrevTriggers = triggerCount;
5531
5532 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005533 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5534 // Request settings are all the same within one batch, so only treat the first
5535 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005536 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005537 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005538 /**
5539 * HAL workaround:
5540 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5541 */
5542 res = addDummyTriggerIds(captureRequest);
5543 if (res != OK) {
5544 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5545 "(capture request %d, HAL device: %s (%d)",
5546 halRequest->frame_number, strerror(-res), res);
5547 return INVALID_OPERATION;
5548 }
5549
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005550 {
5551 // Correct metadata regions for distortion correction if enabled
5552 sp<Camera3Device> parent = mParent.promote();
5553 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07005554 List<PhysicalCameraSettings>::iterator it;
5555 for (it = captureRequest->mSettingsList.begin();
5556 it != captureRequest->mSettingsList.end(); it++) {
5557 if (parent->mDistortionMappers.find(it->cameraId) ==
5558 parent->mDistortionMappers.end()) {
5559 continue;
5560 }
5561 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
5562 &(it->metadata));
5563 if (res != OK) {
5564 SET_ERR("RequestThread: Unable to correct capture requests "
5565 "for lens distortion for request %d: %s (%d)",
5566 halRequest->frame_number, strerror(-res), res);
5567 return INVALID_OPERATION;
5568 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005569 }
5570 }
5571 }
5572
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005573 /**
5574 * The request should be presorted so accesses in HAL
5575 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5576 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005577 captureRequest->mSettingsList.begin()->metadata.sort();
5578 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005579 mPrevRequest = captureRequest;
5580 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5581
5582 IF_ALOGV() {
5583 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5584 find_camera_metadata_ro_entry(
5585 halRequest->settings,
5586 ANDROID_CONTROL_AF_TRIGGER,
5587 &e
5588 );
5589 if (e.count > 0) {
5590 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5591 __FUNCTION__,
5592 halRequest->frame_number,
5593 e.data.u8[0]);
5594 }
5595 }
5596 } else {
5597 // leave request.settings NULL to indicate 'reuse latest given'
5598 ALOGVV("%s: Request settings are REUSED",
5599 __FUNCTION__);
5600 }
5601
Emilian Peevaebbe412018-01-15 13:53:24 +00005602 if (captureRequest->mSettingsList.size() > 1) {
5603 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5604 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005605 if (newRequest) {
5606 halRequest->physcam_settings =
5607 new const camera_metadata* [halRequest->num_physcam_settings];
5608 } else {
5609 halRequest->physcam_settings = nullptr;
5610 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005611 auto it = ++captureRequest->mSettingsList.begin();
5612 size_t i = 0;
5613 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5614 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005615 if (newRequest) {
5616 it->metadata.sort();
5617 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5618 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005619 }
5620 }
5621
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005622 uint32_t totalNumBuffers = 0;
5623
5624 // Fill in buffers
5625 if (captureRequest->mInputStream != NULL) {
5626 halRequest->input_buffer = &captureRequest->mInputBuffer;
5627 totalNumBuffers += 1;
5628 } else {
5629 halRequest->input_buffer = NULL;
5630 }
5631
5632 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5633 captureRequest->mOutputStreams.size());
5634 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005635 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005636
5637 sp<Camera3Device> parent = mParent.promote();
5638 if (parent == NULL) {
5639 // Should not happen, and nowhere to send errors to, so just log it
5640 CLOGE("RequestThread: Parent is gone");
5641 return INVALID_OPERATION;
5642 }
5643 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5644
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005645 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005646 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005647 sp<Camera3OutputStreamInterface> outputStream =
5648 captureRequest->mOutputStreams.editItemAt(j);
5649 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005650
5651 // Prepare video buffers for high speed recording on the first video request.
5652 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5653 // Only try to prepare video stream on the first video request.
5654 mPrepareVideoStream = false;
5655
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005656 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5657 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005658 while (res == NOT_ENOUGH_DATA) {
5659 res = outputStream->prepareNextBuffer();
5660 }
5661 if (res != OK) {
5662 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5663 __FUNCTION__, strerror(-res), res);
5664 outputStream->cancelPrepare();
5665 }
5666 }
5667
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005668 std::vector<size_t> uniqueSurfaceIds;
5669 res = outputStream->getUniqueSurfaceIds(
5670 captureRequest->mOutputSurfaces[streamId],
5671 &uniqueSurfaceIds);
5672 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5673 if (res != OK && res != INVALID_OPERATION) {
5674 ALOGE("%s: failed to query stream %d unique surface IDs",
5675 __FUNCTION__, streamId);
5676 return res;
5677 }
5678 if (res == OK) {
5679 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5680 }
5681
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005682 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005683 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005684 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005685 return TIMED_OUT;
5686 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005687 // HAL will request buffer through requestStreamBuffer API
5688 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5689 buffer.stream = outputStream->asHalStream();
5690 buffer.buffer = nullptr;
5691 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5692 buffer.acquire_fence = -1;
5693 buffer.release_fence = -1;
5694 } else {
5695 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5696 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005697 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005698 if (res != OK) {
5699 // Can't get output buffer from gralloc queue - this could be due to
5700 // abandoned queue or other consumer misbehavior, so not a fatal
5701 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005702 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005703 " %s (%d)", strerror(-res), res);
5704
5705 return TIMED_OUT;
5706 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005707 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005708
5709 {
5710 sp<Camera3Device> parent = mParent.promote();
5711 if (parent != nullptr) {
5712 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5713 for (const auto& settings : captureRequest->mSettingsList) {
5714 if ((streamCameraId.isEmpty() &&
5715 parent->getId() == settings.cameraId.c_str()) ||
5716 streamCameraId == settings.cameraId.c_str()) {
5717 outputStream->fireBufferRequestForFrameNumber(
5718 captureRequest->mResultExtras.frameNumber,
5719 settings.metadata);
5720 }
5721 }
5722 }
5723 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005724
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005725 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5726
5727 if (!physicalCameraId.isEmpty()) {
5728 // Physical stream isn't supported for input request.
5729 if (halRequest->input_buffer) {
5730 CLOGE("Physical stream is not supported for input request");
5731 return INVALID_OPERATION;
5732 }
5733 requestedPhysicalCameras.insert(physicalCameraId);
5734 }
5735 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005736 }
5737 totalNumBuffers += halRequest->num_output_buffers;
5738
5739 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005740 // If this request list is for constrained high speed recording (not
5741 // preview), and the current request is not the last one in the batch,
5742 // do not send callback to the app.
5743 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005744 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005745 hasCallback = false;
5746 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005747 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005748 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005749 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5750 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5751 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5752 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5753 isStillCapture = true;
5754 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5755 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005756
5757 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5758 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5759 isZslCapture = true;
5760 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005761 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005762 res = parent->registerInFlight(halRequest->frame_number,
5763 totalNumBuffers, captureRequest->mResultExtras,
5764 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005765 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005766 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005767 requestedPhysicalCameras, isStillCapture, isZslCapture,
5768 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5769 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005770 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5771 ", burstId = %" PRId32 ".",
5772 __FUNCTION__,
5773 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5774 captureRequest->mResultExtras.burstId);
5775 if (res != OK) {
5776 SET_ERR("RequestThread: Unable to register new in-flight request:"
5777 " %s (%d)", strerror(-res), res);
5778 return INVALID_OPERATION;
5779 }
5780 }
5781
5782 return OK;
5783}
5784
Igor Murashkin1e479c02013-09-06 16:55:14 -07005785CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005786 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005787 Mutex::Autolock al(mLatestRequestMutex);
5788
5789 ALOGV("RequestThread::%s", __FUNCTION__);
5790
5791 return mLatestRequest;
5792}
5793
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005794bool Camera3Device::RequestThread::isStreamPending(
5795 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005796 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005797 Mutex::Autolock l(mRequestLock);
5798
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005799 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005800 if (!nextRequest.submitted) {
5801 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5802 if (stream == s) return true;
5803 }
5804 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005805 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005806 }
5807
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005808 for (const auto& request : mRequestQueue) {
5809 for (const auto& s : request->mOutputStreams) {
5810 if (stream == s) return true;
5811 }
5812 if (stream == request->mInputStream) return true;
5813 }
5814
5815 for (const auto& request : mRepeatingRequests) {
5816 for (const auto& s : request->mOutputStreams) {
5817 if (stream == s) return true;
5818 }
5819 if (stream == request->mInputStream) return true;
5820 }
5821
5822 return false;
5823}
Jianing Weicb0652e2014-03-12 18:29:36 -07005824
Emilian Peev40ead602017-09-26 15:46:36 +01005825bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5826 ATRACE_CALL();
5827 Mutex::Autolock l(mRequestLock);
5828
5829 for (const auto& nextRequest : mNextRequests) {
5830 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5831 if (s.first == streamId) {
5832 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5833 if (it != s.second.end()) {
5834 return true;
5835 }
5836 }
5837 }
5838 }
5839
5840 for (const auto& request : mRequestQueue) {
5841 for (const auto& s : request->mOutputSurfaces) {
5842 if (s.first == streamId) {
5843 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5844 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005845 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005846 }
5847 }
5848 }
5849 }
5850
5851 for (const auto& request : mRepeatingRequests) {
5852 for (const auto& s : request->mOutputSurfaces) {
5853 if (s.first == streamId) {
5854 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5855 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005856 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005857 }
5858 }
5859 }
5860 }
5861
5862 return false;
5863}
5864
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005865void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5866 if (!mUseHalBufManager) {
5867 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5868 return;
5869 }
5870
5871 Mutex::Autolock pl(mPauseLock);
5872 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005873 mInterface->signalPipelineDrain(streamIds);
5874 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005875 }
5876 // If request thread is still busy, wait until paused then notify HAL
5877 mNotifyPipelineDrain = true;
5878 mStreamIdsToBeDrained = streamIds;
5879}
5880
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005881nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005882 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005883 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005884 return mExpectedInflightDuration > kMinInflightDuration ?
5885 mExpectedInflightDuration : kMinInflightDuration;
5886}
5887
Emilian Peevaebbe412018-01-15 13:53:24 +00005888void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5889 camera3_capture_request_t *halRequest) {
5890 if ((request == nullptr) || (halRequest == nullptr)) {
5891 ALOGE("%s: Invalid request!", __FUNCTION__);
5892 return;
5893 }
5894
5895 if (halRequest->num_physcam_settings > 0) {
5896 if (halRequest->physcam_id != nullptr) {
5897 delete [] halRequest->physcam_id;
5898 halRequest->physcam_id = nullptr;
5899 }
5900 if (halRequest->physcam_settings != nullptr) {
5901 auto it = ++(request->mSettingsList.begin());
5902 size_t i = 0;
5903 for (; it != request->mSettingsList.end(); it++, i++) {
5904 it->metadata.unlock(halRequest->physcam_settings[i]);
5905 }
5906 delete [] halRequest->physcam_settings;
5907 halRequest->physcam_settings = nullptr;
5908 }
5909 }
5910}
5911
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005912void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5913 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005914 return;
5915 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005916
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005917 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005918 // Skip the ones that have been submitted successfully.
5919 if (nextRequest.submitted) {
5920 continue;
5921 }
5922
5923 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5924 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5925 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5926
5927 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005928 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005929 }
5930
Emilian Peevaebbe412018-01-15 13:53:24 +00005931 cleanupPhysicalSettings(captureRequest, halRequest);
5932
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005933 if (captureRequest->mInputStream != NULL) {
5934 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5935 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5936 }
5937
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005938 // No output buffer can be returned when using HAL buffer manager
5939 if (!mUseHalBufManager) {
5940 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5941 //Buffers that failed processing could still have
5942 //valid acquire fence.
5943 int acquireFence = (*outputBuffers)[i].acquire_fence;
5944 if (0 <= acquireFence) {
5945 close(acquireFence);
5946 outputBuffers->editItemAt(i).acquire_fence = -1;
5947 }
5948 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5949 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5950 /*timestampIncreasing*/true, std::vector<size_t> (),
5951 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005952 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005953 }
5954
5955 if (sendRequestError) {
5956 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005957 sp<NotificationListener> listener = mListener.promote();
5958 if (listener != NULL) {
5959 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005960 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005961 captureRequest->mResultExtras);
5962 }
5963 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005964
5965 // Remove yet-to-be submitted inflight request from inflightMap
5966 {
5967 sp<Camera3Device> parent = mParent.promote();
5968 if (parent != NULL) {
5969 Mutex::Autolock l(parent->mInFlightLock);
5970 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5971 if (idx >= 0) {
5972 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5973 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5974 parent->removeInFlightMapEntryLocked(idx);
5975 }
5976 }
5977 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005978 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005979
5980 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005981 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005982}
5983
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005984void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005985 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005986 // Optimized a bit for the simple steady-state case (single repeating
5987 // request), to avoid putting that request in the queue temporarily.
5988 Mutex::Autolock l(mRequestLock);
5989
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005990 assert(mNextRequests.empty());
5991
5992 NextRequest nextRequest;
5993 nextRequest.captureRequest = waitForNextRequestLocked();
5994 if (nextRequest.captureRequest == nullptr) {
5995 return;
5996 }
5997
5998 nextRequest.halRequest = camera3_capture_request_t();
5999 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006000 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006001
6002 // Wait for additional requests
6003 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
6004
6005 for (size_t i = 1; i < batchSize; i++) {
6006 NextRequest additionalRequest;
6007 additionalRequest.captureRequest = waitForNextRequestLocked();
6008 if (additionalRequest.captureRequest == nullptr) {
6009 break;
6010 }
6011
6012 additionalRequest.halRequest = camera3_capture_request_t();
6013 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006014 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006015 }
6016
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006017 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006018 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006019 mNextRequests.size(), batchSize);
6020 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006021 }
6022
6023 return;
6024}
6025
6026sp<Camera3Device::CaptureRequest>
6027 Camera3Device::RequestThread::waitForNextRequestLocked() {
6028 status_t res;
6029 sp<CaptureRequest> nextRequest;
6030
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006031 while (mRequestQueue.empty()) {
6032 if (!mRepeatingRequests.empty()) {
6033 // Always atomically enqueue all requests in a repeating request
6034 // list. Guarantees a complete in-sequence set of captures to
6035 // application.
6036 const RequestList &requests = mRepeatingRequests;
6037 RequestList::const_iterator firstRequest =
6038 requests.begin();
6039 nextRequest = *firstRequest;
6040 mRequestQueue.insert(mRequestQueue.end(),
6041 ++firstRequest,
6042 requests.end());
6043 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07006044
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006045 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07006046
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006047 break;
6048 }
6049
6050 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
6051
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006052 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
6053 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006054 Mutex::Autolock pl(mPauseLock);
6055 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006056 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006057 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006058 if (mNotifyPipelineDrain) {
6059 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6060 mNotifyPipelineDrain = false;
6061 mStreamIdsToBeDrained.clear();
6062 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006063 // Let the tracker know
6064 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6065 if (statusTracker != 0) {
6066 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6067 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006068 sp<Camera3Device> parent = mParent.promote();
6069 if (parent != nullptr) {
6070 parent->mRequestBufferSM.onRequestThreadPaused();
6071 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006072 }
6073 // Stop waiting for now and let thread management happen
6074 return NULL;
6075 }
6076 }
6077
6078 if (nextRequest == NULL) {
6079 // Don't have a repeating request already in hand, so queue
6080 // must have an entry now.
6081 RequestList::iterator firstRequest =
6082 mRequestQueue.begin();
6083 nextRequest = *firstRequest;
6084 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07006085 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
6086 sp<NotificationListener> listener = mListener.promote();
6087 if (listener != NULL) {
6088 listener->notifyRequestQueueEmpty();
6089 }
6090 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006091 }
6092
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006093 // In case we've been unpaused by setPaused clearing mDoPause, need to
6094 // update internal pause state (capture/setRepeatingRequest unpause
6095 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006096 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006097 if (mPaused) {
6098 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
6099 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6100 if (statusTracker != 0) {
6101 statusTracker->markComponentActive(mStatusId);
6102 }
6103 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006104 mPaused = false;
6105
6106 // Check if we've reconfigured since last time, and reset the preview
6107 // request if so. Can't use 'NULL request == repeat' across configure calls.
6108 if (mReconfigured) {
6109 mPrevRequest.clear();
6110 mReconfigured = false;
6111 }
6112
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006113 if (nextRequest != NULL) {
6114 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006115 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
6116 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006117
6118 // Since RequestThread::clear() removes buffers from the input stream,
6119 // get the right buffer here before unlocking mRequestLock
6120 if (nextRequest->mInputStream != NULL) {
6121 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
6122 if (res != OK) {
6123 // Can't get input buffer from gralloc queue - this could be due to
6124 // disconnected queue or other producer misbehavior, so not a fatal
6125 // error
6126 ALOGE("%s: Can't get input buffer, skipping request:"
6127 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006128
6129 sp<NotificationListener> listener = mListener.promote();
6130 if (listener != NULL) {
6131 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006132 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006133 nextRequest->mResultExtras);
6134 }
6135 return NULL;
6136 }
6137 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006138 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07006139
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006140 return nextRequest;
6141}
6142
6143bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006144 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006145 status_t res;
6146 Mutex::Autolock l(mPauseLock);
6147 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006148 if (mPaused == false) {
6149 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006150 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006151 if (mNotifyPipelineDrain) {
6152 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6153 mNotifyPipelineDrain = false;
6154 mStreamIdsToBeDrained.clear();
6155 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006156 // Let the tracker know
6157 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6158 if (statusTracker != 0) {
6159 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6160 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006161 sp<Camera3Device> parent = mParent.promote();
6162 if (parent != nullptr) {
6163 parent->mRequestBufferSM.onRequestThreadPaused();
6164 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006165 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006166
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006167 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006168 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006169 return true;
6170 }
6171 }
6172 // We don't set mPaused to false here, because waitForNextRequest needs
6173 // to further manage the paused state in case of starvation.
6174 return false;
6175}
6176
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006177void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006178 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006179 // With work to do, mark thread as unpaused.
6180 // If paused by request (setPaused), don't resume, to avoid
6181 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006182 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006183 Mutex::Autolock p(mPauseLock);
6184 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006185 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6186 if (mPaused) {
6187 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6188 if (statusTracker != 0) {
6189 statusTracker->markComponentActive(mStatusId);
6190 }
6191 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006192 mPaused = false;
6193 }
6194}
6195
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006196void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6197 sp<Camera3Device> parent = mParent.promote();
6198 if (parent != NULL) {
6199 va_list args;
6200 va_start(args, fmt);
6201
6202 parent->setErrorStateV(fmt, args);
6203
6204 va_end(args);
6205 }
6206}
6207
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006208status_t Camera3Device::RequestThread::insertTriggers(
6209 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006210 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006211 Mutex::Autolock al(mTriggerMutex);
6212
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006213 sp<Camera3Device> parent = mParent.promote();
6214 if (parent == NULL) {
6215 CLOGE("RequestThread: Parent is gone");
6216 return DEAD_OBJECT;
6217 }
6218
Emilian Peevaebbe412018-01-15 13:53:24 +00006219 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006220 size_t count = mTriggerMap.size();
6221
6222 for (size_t i = 0; i < count; ++i) {
6223 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006224 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006225
6226 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6227 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6228 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006229 if (isAeTrigger) {
6230 request->mResultExtras.precaptureTriggerId = triggerId;
6231 mCurrentPreCaptureTriggerId = triggerId;
6232 } else {
6233 request->mResultExtras.afTriggerId = triggerId;
6234 mCurrentAfTriggerId = triggerId;
6235 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006236 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006237 }
6238
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006239 camera_metadata_entry entry = metadata.find(tag);
6240
6241 if (entry.count > 0) {
6242 /**
6243 * Already has an entry for this trigger in the request.
6244 * Rewrite it with our requested trigger value.
6245 */
6246 RequestTrigger oldTrigger = trigger;
6247
6248 oldTrigger.entryValue = entry.data.u8[0];
6249
6250 mTriggerReplacedMap.add(tag, oldTrigger);
6251 } else {
6252 /**
6253 * More typical, no trigger entry, so we just add it
6254 */
6255 mTriggerRemovedMap.add(tag, trigger);
6256 }
6257
6258 status_t res;
6259
6260 switch (trigger.getTagType()) {
6261 case TYPE_BYTE: {
6262 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6263 res = metadata.update(tag,
6264 &entryValue,
6265 /*count*/1);
6266 break;
6267 }
6268 case TYPE_INT32:
6269 res = metadata.update(tag,
6270 &trigger.entryValue,
6271 /*count*/1);
6272 break;
6273 default:
6274 ALOGE("%s: Type not supported: 0x%x",
6275 __FUNCTION__,
6276 trigger.getTagType());
6277 return INVALID_OPERATION;
6278 }
6279
6280 if (res != OK) {
6281 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6282 ", value %d", __FUNCTION__, trigger.getTagName(),
6283 trigger.entryValue);
6284 return res;
6285 }
6286
6287 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6288 trigger.getTagName(),
6289 trigger.entryValue);
6290 }
6291
6292 mTriggerMap.clear();
6293
6294 return count;
6295}
6296
6297status_t Camera3Device::RequestThread::removeTriggers(
6298 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006299 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006300 Mutex::Autolock al(mTriggerMutex);
6301
Emilian Peevaebbe412018-01-15 13:53:24 +00006302 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006303
6304 /**
6305 * Replace all old entries with their old values.
6306 */
6307 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6308 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6309
6310 status_t res;
6311
6312 uint32_t tag = trigger.metadataTag;
6313 switch (trigger.getTagType()) {
6314 case TYPE_BYTE: {
6315 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6316 res = metadata.update(tag,
6317 &entryValue,
6318 /*count*/1);
6319 break;
6320 }
6321 case TYPE_INT32:
6322 res = metadata.update(tag,
6323 &trigger.entryValue,
6324 /*count*/1);
6325 break;
6326 default:
6327 ALOGE("%s: Type not supported: 0x%x",
6328 __FUNCTION__,
6329 trigger.getTagType());
6330 return INVALID_OPERATION;
6331 }
6332
6333 if (res != OK) {
6334 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6335 ", trigger value %d", __FUNCTION__,
6336 trigger.getTagName(), trigger.entryValue);
6337 return res;
6338 }
6339 }
6340 mTriggerReplacedMap.clear();
6341
6342 /**
6343 * Remove all new entries.
6344 */
6345 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6346 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6347 status_t res = metadata.erase(trigger.metadataTag);
6348
6349 if (res != OK) {
6350 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6351 ", trigger value %d", __FUNCTION__,
6352 trigger.getTagName(), trigger.entryValue);
6353 return res;
6354 }
6355 }
6356 mTriggerRemovedMap.clear();
6357
6358 return OK;
6359}
6360
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006361status_t Camera3Device::RequestThread::addDummyTriggerIds(
6362 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006363 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006364 static const int32_t dummyTriggerId = 1;
6365 status_t res;
6366
Emilian Peevaebbe412018-01-15 13:53:24 +00006367 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006368
6369 // If AF trigger is active, insert a dummy AF trigger ID if none already
6370 // exists
6371 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6372 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6373 if (afTrigger.count > 0 &&
6374 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6375 afId.count == 0) {
6376 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6377 if (res != OK) return res;
6378 }
6379
6380 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6381 // if none already exists
6382 camera_metadata_entry pcTrigger =
6383 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6384 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6385 if (pcTrigger.count > 0 &&
6386 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6387 pcId.count == 0) {
6388 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6389 &dummyTriggerId, 1);
6390 if (res != OK) return res;
6391 }
6392
6393 return OK;
6394}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006395
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006396/**
6397 * PreparerThread inner class methods
6398 */
6399
6400Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006401 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006402 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006403}
6404
6405Camera3Device::PreparerThread::~PreparerThread() {
6406 Thread::requestExitAndWait();
6407 if (mCurrentStream != nullptr) {
6408 mCurrentStream->cancelPrepare();
6409 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6410 mCurrentStream.clear();
6411 }
6412 clear();
6413}
6414
Ruben Brunkc78ac262015-08-13 17:58:46 -07006415status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006416 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006417 status_t res;
6418
6419 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006420 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006421
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006422 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006423 if (res == OK) {
6424 // No preparation needed, fire listener right off
6425 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006426 if (listener != NULL) {
6427 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006428 }
6429 return OK;
6430 } else if (res != NOT_ENOUGH_DATA) {
6431 return res;
6432 }
6433
6434 // Need to prepare, start up thread if necessary
6435 if (!mActive) {
6436 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6437 // isn't running
6438 Thread::requestExitAndWait();
6439 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6440 if (res != OK) {
6441 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006442 if (listener != NULL) {
6443 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006444 }
6445 return res;
6446 }
6447 mCancelNow = false;
6448 mActive = true;
6449 ALOGV("%s: Preparer stream started", __FUNCTION__);
6450 }
6451
6452 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006453 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006454 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6455
6456 return OK;
6457}
6458
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006459void Camera3Device::PreparerThread::pause() {
6460 ATRACE_CALL();
6461
6462 Mutex::Autolock l(mLock);
6463
6464 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6465 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6466 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6467 int currentMaxCount = mCurrentMaxCount;
6468 mPendingStreams.clear();
6469 mCancelNow = true;
6470 while (mActive) {
6471 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6472 if (res == TIMED_OUT) {
6473 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6474 return;
6475 } else if (res != OK) {
6476 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6477 return;
6478 }
6479 }
6480
6481 //Check whether the prepare thread was able to complete the current
6482 //stream. In case work is still pending emplace it along with the rest
6483 //of the streams in the pending list.
6484 if (currentStream != nullptr) {
6485 if (!mCurrentPrepareComplete) {
6486 pendingStreams.emplace(currentMaxCount, currentStream);
6487 }
6488 }
6489
6490 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6491 for (const auto& it : mPendingStreams) {
6492 it.second->cancelPrepare();
6493 }
6494}
6495
6496status_t Camera3Device::PreparerThread::resume() {
6497 ATRACE_CALL();
6498 status_t res;
6499
6500 Mutex::Autolock l(mLock);
6501 sp<NotificationListener> listener = mListener.promote();
6502
6503 if (mActive) {
6504 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6505 return NO_INIT;
6506 }
6507
6508 auto it = mPendingStreams.begin();
6509 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006510 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006511 if (res == OK) {
6512 if (listener != NULL) {
6513 listener->notifyPrepared(it->second->getId());
6514 }
6515 it = mPendingStreams.erase(it);
6516 } else if (res != NOT_ENOUGH_DATA) {
6517 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6518 res, strerror(-res));
6519 it = mPendingStreams.erase(it);
6520 } else {
6521 it++;
6522 }
6523 }
6524
6525 if (mPendingStreams.empty()) {
6526 return OK;
6527 }
6528
6529 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6530 if (res != OK) {
6531 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6532 __FUNCTION__, res, strerror(-res));
6533 return res;
6534 }
6535 mCancelNow = false;
6536 mActive = true;
6537 ALOGV("%s: Preparer stream started", __FUNCTION__);
6538
6539 return OK;
6540}
6541
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006542status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006543 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006544 Mutex::Autolock l(mLock);
6545
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006546 for (const auto& it : mPendingStreams) {
6547 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006548 }
6549 mPendingStreams.clear();
6550 mCancelNow = true;
6551
6552 return OK;
6553}
6554
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006555void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006556 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006557 Mutex::Autolock l(mLock);
6558 mListener = listener;
6559}
6560
6561bool Camera3Device::PreparerThread::threadLoop() {
6562 status_t res;
6563 {
6564 Mutex::Autolock l(mLock);
6565 if (mCurrentStream == nullptr) {
6566 // End thread if done with work
6567 if (mPendingStreams.empty()) {
6568 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6569 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6570 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6571 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006572 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006573 return false;
6574 }
6575
6576 // Get next stream to prepare
6577 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006578 mCurrentStream = it->second;
6579 mCurrentMaxCount = it->first;
6580 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006581 mPendingStreams.erase(it);
6582 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6583 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6584 } else if (mCancelNow) {
6585 mCurrentStream->cancelPrepare();
6586 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6587 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6588 mCurrentStream.clear();
6589 mCancelNow = false;
6590 return true;
6591 }
6592 }
6593
6594 res = mCurrentStream->prepareNextBuffer();
6595 if (res == NOT_ENOUGH_DATA) return true;
6596 if (res != OK) {
6597 // Something bad happened; try to recover by cancelling prepare and
6598 // signalling listener anyway
6599 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6600 mCurrentStream->getId(), res, strerror(-res));
6601 mCurrentStream->cancelPrepare();
6602 }
6603
6604 // This stream has finished, notify listener
6605 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006606 sp<NotificationListener> listener = mListener.promote();
6607 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006608 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6609 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006610 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006611 }
6612
6613 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6614 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006615 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006616
6617 return true;
6618}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006619
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006620status_t Camera3Device::RequestBufferStateMachine::initialize(
6621 sp<camera3::StatusTracker> statusTracker) {
6622 if (statusTracker == nullptr) {
6623 ALOGE("%s: statusTracker is null", __FUNCTION__);
6624 return BAD_VALUE;
6625 }
6626
6627 std::lock_guard<std::mutex> lock(mLock);
6628 mStatusTracker = statusTracker;
6629 mRequestBufferStatusId = statusTracker->addComponent();
6630 return OK;
6631}
6632
6633bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6634 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006635 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006636 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006637 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006638 return true;
6639 }
6640 return false;
6641}
6642
6643void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6644 std::lock_guard<std::mutex> lock(mLock);
6645 if (!mRequestBufferOngoing) {
6646 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6647 return;
6648 }
6649 mRequestBufferOngoing = false;
6650 if (mStatus == RB_STATUS_PENDING_STOP) {
6651 checkSwitchToStopLocked();
6652 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006653 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006654}
6655
6656void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6657 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006658 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006659 return;
6660}
6661
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006662void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006663 std::lock_guard<std::mutex> lock(mLock);
6664 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006665 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6666 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006667 mInflightMapEmpty = false;
6668 if (mStatus == RB_STATUS_STOPPED) {
6669 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006670 }
6671 return;
6672}
6673
6674void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6675 std::lock_guard<std::mutex> lock(mLock);
6676 mRequestThreadPaused = true;
6677 if (mStatus == RB_STATUS_PENDING_STOP) {
6678 checkSwitchToStopLocked();
6679 }
6680 return;
6681}
6682
6683void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6684 std::lock_guard<std::mutex> lock(mLock);
6685 mInflightMapEmpty = true;
6686 if (mStatus == RB_STATUS_PENDING_STOP) {
6687 checkSwitchToStopLocked();
6688 }
6689 return;
6690}
6691
6692void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6693 std::lock_guard<std::mutex> lock(mLock);
6694 if (!checkSwitchToStopLocked()) {
6695 mStatus = RB_STATUS_PENDING_STOP;
6696 }
6697 return;
6698}
6699
6700void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6701 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6702 if (statusTracker != nullptr) {
6703 if (active) {
6704 statusTracker->markComponentActive(mRequestBufferStatusId);
6705 } else {
6706 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6707 }
6708 }
6709}
6710
6711bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6712 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6713 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006714 return true;
6715 }
6716 return false;
6717}
6718
Shuzhen Wang268a1362018-10-16 16:32:59 -07006719status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6720 CameraMetadata& resultMetadata) {
6721 status_t res = OK;
6722 if (!mNeedFixupMonochromeTags) {
6723 return res;
6724 }
6725
6726 // Remove tags that are not applicable to monochrome camera.
6727 int32_t tagsToRemove[] = {
6728 ANDROID_SENSOR_GREEN_SPLIT,
6729 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6730 ANDROID_COLOR_CORRECTION_MODE,
6731 ANDROID_COLOR_CORRECTION_TRANSFORM,
6732 ANDROID_COLOR_CORRECTION_GAINS,
6733 };
6734 for (auto tag : tagsToRemove) {
6735 res = resultMetadata.erase(tag);
6736 if (res != OK) {
6737 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6738 return res;
6739 }
6740 }
6741
6742 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6743 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6744 for (size_t i = 1; i < blEntry.count; i++) {
6745 blEntry.data.f[i] = blEntry.data.f[0];
6746 }
6747
6748 // ANDROID_SENSOR_NOISE_PROFILE
6749 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6750 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6751 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6752 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6753 if (res != OK) {
6754 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6755 __FUNCTION__, strerror(-res), res);
6756 return res;
6757 }
6758 }
6759
6760 // ANDROID_STATISTICS_LENS_SHADING_MAP
6761 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6762 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6763 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6764 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6765 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6766 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6767 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6768 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6769 }
6770 }
6771
6772 // ANDROID_TONEMAP_CURVE_BLUE
6773 // ANDROID_TONEMAP_CURVE_GREEN
6774 // ANDROID_TONEMAP_CURVE_RED
6775 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6776 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6777 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6778 if (tcbEntry.count > 0
6779 && tcbEntry.count == tcgEntry.count
6780 && tcbEntry.count == tcrEntry.count) {
6781 for (size_t i = 0; i < tcbEntry.count; i++) {
6782 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6783 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6784 }
6785 }
6786
6787 return res;
6788}
6789
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006790}; // namespace android