blob: dd5a62bed2c49d1b503bba3b6f0a3a46d107c6af [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) {
Shuzhen Wang468dbb82019-07-31 11:35:33 -07003682 SET_ERR("Expected physical Camera metadata count %d not equal to actual count %d",
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003683 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);
Shuzhen Wang468dbb82019-07-31 11:35:33 -07003876 auto iter = r.physicalCameraIds.find(cameraId);
3877 if (iter == r.physicalCameraIds.end()) {
Emilian Peevedec62d2019-03-19 17:59:24 -07003878 ALOGE("%s: Reported result failure for physical camera device: %s "
3879 " which is not part of the respective request!",
3880 __FUNCTION__, cameraId.string());
3881 break;
3882 }
Shuzhen Wang468dbb82019-07-31 11:35:33 -07003883 r.physicalCameraIds.erase(iter);
Emilian Peevedec62d2019-03-19 17:59:24 -07003884 resultExtras.errorPhysicalCameraId = physicalCameraId;
3885 } else {
3886 logicalDeviceResultError = true;
3887 }
3888 }
3889
3890 if (logicalDeviceResultError
Shuzhen Wang20f57342017-08-24 15:39:05 -07003891 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3892 errorCode) {
3893 r.skipResultMetadata = true;
3894 }
Emilian Peevedec62d2019-03-19 17:59:24 -07003895 if (logicalDeviceResultError) {
Emilian Peevba0fac32017-03-30 09:05:34 +01003896 // In case of missing result check whether the buffers
3897 // returned. If they returned, then remove inflight
3898 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003899 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3900 // otherwise we are depending on HAL to send the buffers back after
3901 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003902 removeInFlightRequestIfReadyLocked(idx);
3903 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003904 } else {
3905 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003906 ALOGE("Camera %s: %s: cannot find in-flight request on "
3907 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003908 resultExtras.frameNumber);
3909 }
3910 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003911 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003912 if (listener != NULL) {
3913 listener->notifyError(errorCode, resultExtras);
3914 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003915 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003916 }
3917 break;
3918 default:
3919 // SET_ERR calls notifyError
3920 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3921 break;
3922 }
3923}
3924
3925void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003926 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003927 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003928 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003929
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003930 // Set timestamp for the request in the in-flight tracking
3931 // and get the request ID to send upstream
3932 {
3933 Mutex::Autolock l(mInFlightLock);
3934 idx = mInFlightMap.indexOfKey(msg.frame_number);
3935 if (idx >= 0) {
3936 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003937
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003938 // Verify ordering of shutter notifications
3939 {
3940 Mutex::Autolock l(mOutputLock);
3941 // TODO: need to track errors for tighter bounds on expected frame number.
3942 if (r.hasInputBuffer) {
3943 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003944 SET_ERR("Reprocess shutter notification out-of-order. Expected "
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003945 "notification for frame %d, got frame %d",
3946 mNextReprocessShutterFrameNumber, msg.frame_number);
3947 return;
3948 }
3949 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003950 } else if (r.zslCapture && r.stillCapture) {
3951 if (msg.frame_number < mNextZslStillShutterFrameNumber) {
3952 SET_ERR("ZSL still capture shutter notification out-of-order. Expected "
3953 "notification for frame %d, got frame %d",
3954 mNextZslStillShutterFrameNumber, msg.frame_number);
3955 return;
3956 }
3957 mNextZslStillShutterFrameNumber = msg.frame_number + 1;
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003958 } else {
3959 if (msg.frame_number < mNextShutterFrameNumber) {
3960 SET_ERR("Shutter notification out-of-order. Expected "
3961 "notification for frame %d, got frame %d",
3962 mNextShutterFrameNumber, msg.frame_number);
3963 return;
3964 }
3965 mNextShutterFrameNumber = msg.frame_number + 1;
3966 }
3967 }
3968
Shuzhen Wang4a472662017-02-26 23:29:04 -08003969 r.shutterTimestamp = msg.timestamp;
3970 if (r.hasCallback) {
3971 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003972 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003973 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003974 // Call listener, if any
3975 if (listener != NULL) {
3976 listener->notifyShutter(r.resultExtras, msg.timestamp);
3977 }
3978 // send pending result and buffers
3979 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3980 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003981 r.hasInputBuffer, r.zslCapture && r.stillCapture,
3982 r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003983 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003984 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003985 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003986 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3987 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003988 r.pendingOutputBuffers.clear();
3989
3990 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003991 }
3992 }
3993 if (idx < 0) {
3994 SET_ERR("Shutter notification for non-existent frame number %d",
3995 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003996 }
3997}
3998
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003999CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07004000 ALOGV("%s", __FUNCTION__);
4001
Igor Murashkin1e479c02013-09-06 16:55:14 -07004002 CameraMetadata retVal;
4003
4004 if (mRequestThread != NULL) {
4005 retVal = mRequestThread->getLatestRequest();
4006 }
4007
Igor Murashkin1e479c02013-09-06 16:55:14 -07004008 return retVal;
4009}
4010
Jianing Weicb0652e2014-03-12 18:29:36 -07004011
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004012void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004013 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
4014 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
4015
4016 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
4017 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004018}
4019
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004020/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004021 * HalInterface inner class methods
4022 */
4023
Yifan Hongf79b5542017-04-11 14:44:25 -07004024Camera3Device::HalInterface::HalInterface(
4025 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004026 std::shared_ptr<RequestMetadataQueue> queue,
4027 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004028 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004029 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08004030 mUseHalBufManager(useHalBufManager),
4031 mIsReconfigurationQuerySupported(true) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004032 // Check with hardware service manager if we can downcast these interfaces
4033 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004034 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
4035 if (castResult_3_5.isOk()) {
4036 mHidlSession_3_5 = castResult_3_5;
4037 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004038 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4039 if (castResult_3_4.isOk()) {
4040 mHidlSession_3_4 = castResult_3_4;
4041 }
4042 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
4043 if (castResult_3_3.isOk()) {
4044 mHidlSession_3_3 = castResult_3_3;
4045 }
4046}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004047
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004048Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004049
4050Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004051 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004052 mRequestMetadataQueue(other.mRequestMetadataQueue),
4053 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004054
4055bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004056 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004057}
4058
4059void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00004060 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00004061 mHidlSession_3_4.clear();
4062 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004063 mHidlSession.clear();
4064}
4065
4066status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
4067 camera3_request_template_t templateId,
4068 /*out*/ camera_metadata_t **requestTemplate) {
4069 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
4070 if (!valid()) return INVALID_OPERATION;
4071 status_t res = OK;
4072
Emilian Peev31abd0a2017-05-11 18:37:46 +01004073 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004074
4075 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01004076 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004077 status = s;
4078 if (status == common::V1_0::Status::OK) {
4079 const camera_metadata *r =
4080 reinterpret_cast<const camera_metadata_t*>(request.data());
4081 size_t expectedSize = request.size();
4082 int ret = validate_camera_metadata_structure(r, &expectedSize);
4083 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
4084 *requestTemplate = clone_camera_metadata(r);
4085 if (*requestTemplate == nullptr) {
4086 ALOGE("%s: Unable to clone camera metadata received from HAL",
4087 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004088 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004089 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004090 } else {
4091 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
4092 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004093 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004094 }
4095 };
4096 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004097 RequestTemplate id;
4098 switch (templateId) {
4099 case CAMERA3_TEMPLATE_PREVIEW:
4100 id = RequestTemplate::PREVIEW;
4101 break;
4102 case CAMERA3_TEMPLATE_STILL_CAPTURE:
4103 id = RequestTemplate::STILL_CAPTURE;
4104 break;
4105 case CAMERA3_TEMPLATE_VIDEO_RECORD:
4106 id = RequestTemplate::VIDEO_RECORD;
4107 break;
4108 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
4109 id = RequestTemplate::VIDEO_SNAPSHOT;
4110 break;
4111 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
4112 id = RequestTemplate::ZERO_SHUTTER_LAG;
4113 break;
4114 case CAMERA3_TEMPLATE_MANUAL:
4115 id = RequestTemplate::MANUAL;
4116 break;
4117 default:
4118 // Unknown template ID, or this HAL is too old to support it
4119 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004120 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004121 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004122
Emilian Peev31abd0a2017-05-11 18:37:46 +01004123 if (!err.isOk()) {
4124 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4125 res = DEAD_OBJECT;
4126 } else {
4127 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004128 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004129
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004130 return res;
4131}
4132
Emilian Peev4ec17882019-01-24 17:16:58 -08004133bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4134 CameraMetadata& newSessionParams) {
4135 // We do reconfiguration by default;
4136 bool ret = true;
4137 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4138 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4139 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4140 oldSessionParams.getAndLock());
4141 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4142 newSessionParams.getAndLock());
4143 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4144 get_camera_metadata_size(oldSessioMeta));
4145 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4146 get_camera_metadata_size(newSessioMeta));
4147 hardware::camera::common::V1_0::Status callStatus;
4148 bool required;
4149 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4150 bool requiredFlag) {
4151 callStatus = s;
4152 required = requiredFlag;
4153 };
4154 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4155 oldSessionParams.unlock(oldSessioMeta);
4156 newSessionParams.unlock(newSessioMeta);
4157 if (err.isOk()) {
4158 switch (callStatus) {
4159 case hardware::camera::common::V1_0::Status::OK:
4160 ret = required;
4161 break;
4162 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4163 mIsReconfigurationQuerySupported = false;
4164 ret = true;
4165 break;
4166 default:
4167 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4168 ret = true;
4169 }
4170 } else {
4171 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4172 ret = true;
4173 }
4174 }
4175
4176 return ret;
4177}
4178
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004179status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004180 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004181 ATRACE_NAME("CameraHal::configureStreams");
4182 if (!valid()) return INVALID_OPERATION;
4183 status_t res = OK;
4184
Emilian Peev31abd0a2017-05-11 18:37:46 +01004185 // Convert stream config to HIDL
4186 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004187 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4188 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4189 requestedConfiguration3_2.streams.resize(config->num_streams);
4190 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004191 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004192 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4193 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004194 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004195
Emilian Peev31abd0a2017-05-11 18:37:46 +01004196 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4197 cam3stream->setBufferFreedListener(this);
4198 int streamId = cam3stream->getId();
4199 StreamType streamType;
4200 switch (src->stream_type) {
4201 case CAMERA3_STREAM_OUTPUT:
4202 streamType = StreamType::OUTPUT;
4203 break;
4204 case CAMERA3_STREAM_INPUT:
4205 streamType = StreamType::INPUT;
4206 break;
4207 default:
4208 ALOGE("%s: Stream %d: Unsupported stream type %d",
4209 __FUNCTION__, streamId, config->streams[i]->stream_type);
4210 return BAD_VALUE;
4211 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004212 dst3_2.id = streamId;
4213 dst3_2.streamType = streamType;
4214 dst3_2.width = src->width;
4215 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004216 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004217 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07004218 // For HidlSession version 3.5 or newer, the format and dataSpace sent
4219 // to HAL are original, not the overriden ones.
4220 if (mHidlSession_3_5 != nullptr) {
4221 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
4222 cam3stream->getOriginalFormat() : src->format);
4223 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
4224 cam3stream->getOriginalDataSpace() : src->data_space);
4225 } else {
4226 dst3_2.format = mapToPixelFormat(src->format);
4227 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4228 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004229 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004230 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004231 if (src->physical_camera_id != nullptr) {
4232 dst3_4.physicalCameraId = src->physical_camera_id;
4233 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004234
4235 activeStreams.insert(streamId);
4236 // Create Buffer ID map if necessary
4237 if (mBufferIdMaps.count(streamId) == 0) {
4238 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4239 }
4240 }
4241 // remove BufferIdMap for deleted streams
4242 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4243 int streamId = it->first;
4244 bool active = activeStreams.count(streamId) > 0;
4245 if (!active) {
4246 it = mBufferIdMaps.erase(it);
4247 } else {
4248 ++it;
4249 }
4250 }
4251
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004252 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004253 res = mapToStreamConfigurationMode(
4254 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004255 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004256 if (res != OK) {
4257 return res;
4258 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004259 requestedConfiguration3_2.operationMode = operationMode;
4260 requestedConfiguration3_4.operationMode = operationMode;
4261 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004262 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4263 get_camera_metadata_size(sessionParams));
4264
Emilian Peev31abd0a2017-05-11 18:37:46 +01004265 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004266 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004267 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004268 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004269
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004270 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004271 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4272 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004273 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004274 };
4275
4276 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4277 (hardware::Return<void>& err) -> status_t {
4278 if (!err.isOk()) {
4279 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4280 return DEAD_OBJECT;
4281 }
4282 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4283 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4284 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4285 }
4286 return OK;
4287 };
4288
Shuzhen Wang92653952019-05-07 15:11:43 -07004289 // See which version of HAL we have
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004290 if (mHidlSession_3_5 != nullptr) {
4291 ALOGV("%s: v3.5 device found", __FUNCTION__);
4292 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4293 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4294 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4295 auto err = mHidlSession_3_5->configureStreams_3_5(
4296 requestedConfiguration3_5, configStream34Cb);
4297 res = postprocConfigStream34(err);
4298 if (res != OK) {
4299 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004300 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004301 } else if (mHidlSession_3_4 != nullptr) {
4302 // We do; use v3.4 for the call
4303 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004304 auto err = mHidlSession_3_4->configureStreams_3_4(
4305 requestedConfiguration3_4, configStream34Cb);
4306 res = postprocConfigStream34(err);
4307 if (res != OK) {
4308 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004309 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004310 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004311 // We do; use v3.3 for the call
4312 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004313 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004314 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004315 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004316 finalConfiguration = halConfiguration;
4317 status = s;
4318 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004319 if (!err.isOk()) {
4320 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4321 return DEAD_OBJECT;
4322 }
4323 } else {
4324 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4325 ALOGV("%s: v3.2 device found", __FUNCTION__);
4326 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004327 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004328 [&status, &finalConfiguration_3_2]
4329 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4330 finalConfiguration_3_2 = halConfiguration;
4331 status = s;
4332 });
4333 if (!err.isOk()) {
4334 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4335 return DEAD_OBJECT;
4336 }
4337 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4338 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4339 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4340 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004341 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004342 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004343 }
4344
4345 if (status != common::V1_0::Status::OK ) {
4346 return CameraProviderManager::mapToStatusT(status);
4347 }
4348
4349 // And convert output stream configuration from HIDL
4350
4351 for (size_t i = 0; i < config->num_streams; i++) {
4352 camera3_stream_t *dst = config->streams[i];
4353 int streamId = Camera3Stream::cast(dst)->getId();
4354
4355 // Start scan at i, with the assumption that the stream order matches
4356 size_t realIdx = i;
4357 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004358 size_t halStreamCount = finalConfiguration.streams.size();
4359 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004360 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004361 found = true;
4362 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004363 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004364 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004365 }
4366 if (!found) {
4367 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4368 __FUNCTION__, streamId);
4369 return INVALID_OPERATION;
4370 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004371 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004372
Emilian Peev710c1422017-08-30 11:19:38 +01004373 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004374 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4375 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4376
Yin-Chia Yeh90667662019-07-01 15:45:00 -07004377 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07004378 dstStream->setFormatOverride(false);
4379 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004380 if (dst->format != overrideFormat) {
4381 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4382 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004383 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004384 if (dst->data_space != overrideDataSpace) {
4385 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4386 streamId, dst->format);
4387 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004388 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07004389 bool needFormatOverride =
4390 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
4391 bool needDataspaceOverride =
4392 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004393 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07004394 dstStream->setFormatOverride(needFormatOverride);
4395 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004396 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004397 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004398 }
4399
Emilian Peev31abd0a2017-05-11 18:37:46 +01004400 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004401 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004402 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004403 __FUNCTION__, streamId);
4404 return INVALID_OPERATION;
4405 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004406 dstStream->setUsage(
4407 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004408 } else {
4409 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004410 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004411 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4412 __FUNCTION__, streamId);
4413 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004414 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004415 dstStream->setUsage(
4416 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004417 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004418 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004419 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004420
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004421 return res;
4422}
4423
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004424status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004425 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004426 /*out*/std::vector<native_handle_t*>* handlesCreated,
4427 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004428 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004429 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
4430 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
4431 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004432 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004433 }
4434
4435 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004436
4437 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004438
4439 {
4440 std::lock_guard<std::mutex> lock(mInflightLock);
4441 if (request->input_buffer != nullptr) {
4442 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4443 buffer_handle_t buf = *(request->input_buffer->buffer);
4444 auto pair = getBufferId(buf, streamId);
4445 bool isNewBuffer = pair.first;
4446 uint64_t bufferId = pair.second;
4447 captureRequest->inputBuffer.streamId = streamId;
4448 captureRequest->inputBuffer.bufferId = bufferId;
4449 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4450 captureRequest->inputBuffer.status = BufferStatus::OK;
4451 native_handle_t *acquireFence = nullptr;
4452 if (request->input_buffer->acquire_fence != -1) {
4453 acquireFence = native_handle_create(1,0);
4454 acquireFence->data[0] = request->input_buffer->acquire_fence;
4455 handlesCreated->push_back(acquireFence);
4456 }
4457 captureRequest->inputBuffer.acquireFence = acquireFence;
4458 captureRequest->inputBuffer.releaseFence = nullptr;
4459
4460 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004461 request->input_buffer->buffer);
4462 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004463 } else {
4464 captureRequest->inputBuffer.streamId = -1;
4465 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4466 }
4467
4468 captureRequest->outputBuffers.resize(request->num_output_buffers);
4469 for (size_t i = 0; i < request->num_output_buffers; i++) {
4470 const camera3_stream_buffer_t *src = request->output_buffers + i;
4471 StreamBuffer &dst = captureRequest->outputBuffers[i];
4472 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004473 if (src->buffer != nullptr) {
4474 buffer_handle_t buf = *(src->buffer);
4475 auto pair = getBufferId(buf, streamId);
4476 bool isNewBuffer = pair.first;
4477 dst.bufferId = pair.second;
4478 dst.buffer = isNewBuffer ? buf : nullptr;
4479 native_handle_t *acquireFence = nullptr;
4480 if (src->acquire_fence != -1) {
4481 acquireFence = native_handle_create(1,0);
4482 acquireFence->data[0] = src->acquire_fence;
4483 handlesCreated->push_back(acquireFence);
4484 }
4485 dst.acquireFence = acquireFence;
4486 } else if (mUseHalBufManager) {
4487 // HAL buffer management path
4488 dst.bufferId = BUFFER_ID_NO_BUFFER;
4489 dst.buffer = nullptr;
4490 dst.acquireFence = nullptr;
4491 } else {
4492 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4493 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004494 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004495 dst.streamId = streamId;
4496 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004497 dst.releaseFence = nullptr;
4498
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004499 // Output buffers are empty when using HAL buffer manager
4500 if (!mUseHalBufManager) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004501 pushInflightBufferLocked(captureRequest->frameNumber, streamId, src->buffer);
4502 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004503 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004504 }
4505 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004506 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004507}
4508
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004509void Camera3Device::HalInterface::cleanupNativeHandles(
4510 std::vector<native_handle_t*> *handles, bool closeFd) {
4511 if (handles == nullptr) {
4512 return;
4513 }
4514 if (closeFd) {
4515 for (auto& handle : *handles) {
4516 native_handle_close(handle);
4517 }
4518 }
4519 for (auto& handle : *handles) {
4520 native_handle_delete(handle);
4521 }
4522 handles->clear();
4523 return;
4524}
4525
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004526status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4527 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4528 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4529 if (!valid()) return INVALID_OPERATION;
4530
Emilian Peevaebbe412018-01-15 13:53:24 +00004531 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4532 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4533 if (castResult_3_4.isOk()) {
4534 hidlSession_3_4 = castResult_3_4;
4535 }
4536
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004537 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004538 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004539 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004540 if (hidlSession_3_4 != nullptr) {
4541 captureRequests_3_4.resize(batchSize);
4542 } else {
4543 captureRequests.resize(batchSize);
4544 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004545 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004546 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004547
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004548 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004549 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004550 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004551 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004552 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00004553 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004554 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
4555 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004556 }
4557 if (res != OK) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004558 popInflightBuffers(inflightBuffers);
4559 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004560 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004561 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004562 }
4563
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004564 std::vector<device::V3_2::BufferCache> cachesToRemove;
4565 {
4566 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4567 for (auto& pair : mFreedBuffers) {
4568 // The stream might have been removed since onBufferFreed
4569 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4570 cachesToRemove.push_back({pair.first, pair.second});
4571 }
4572 }
4573 mFreedBuffers.clear();
4574 }
4575
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004576 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4577 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004578
4579 // Write metadata to FMQ.
4580 for (size_t i = 0; i < batchSize; i++) {
4581 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004582 device::V3_2::CaptureRequest* captureRequest;
4583 if (hidlSession_3_4 != nullptr) {
4584 captureRequest = &captureRequests_3_4[i].v3_2;
4585 } else {
4586 captureRequest = &captureRequests[i];
4587 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004588
4589 if (request->settings != nullptr) {
4590 size_t settingsSize = get_camera_metadata_size(request->settings);
4591 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4592 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4593 captureRequest->settings.resize(0);
4594 captureRequest->fmqSettingsSize = settingsSize;
4595 } else {
4596 if (mRequestMetadataQueue != nullptr) {
4597 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4598 }
4599 captureRequest->settings.setToExternal(
4600 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4601 get_camera_metadata_size(request->settings));
4602 captureRequest->fmqSettingsSize = 0u;
4603 }
4604 } else {
4605 // A null request settings maps to a size-0 CameraMetadata
4606 captureRequest->settings.resize(0);
4607 captureRequest->fmqSettingsSize = 0u;
4608 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004609
4610 if (hidlSession_3_4 != nullptr) {
4611 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4612 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004613 if (request->physcam_settings != nullptr) {
4614 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4615 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4616 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4617 settingsSize)) {
4618 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4619 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4620 settingsSize;
4621 } else {
4622 if (mRequestMetadataQueue != nullptr) {
4623 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4624 }
4625 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4626 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4627 request->physcam_settings[j])),
4628 get_camera_metadata_size(request->physcam_settings[j]));
4629 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004630 }
Emilian Peev00420d22018-02-05 21:33:13 +00004631 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004632 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004633 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004634 }
4635 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4636 request->physcam_id[j];
4637 }
4638 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004639 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004640
4641 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004642 auto resultCallback =
4643 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4644 status = s;
4645 *numRequestProcessed = n;
4646 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004647 if (hidlSession_3_4 != nullptr) {
4648 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004649 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004650 } else {
4651 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004652 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004653 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004654 if (!err.isOk()) {
4655 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004656 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004657 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004658
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004659 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4660 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4661 __FUNCTION__, *numRequestProcessed, batchSize);
4662 status = common::V1_0::Status::INTERNAL_ERROR;
4663 }
4664
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004665 res = CameraProviderManager::mapToStatusT(status);
4666 if (res == OK) {
4667 if (mHidlSession->isRemote()) {
4668 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
4669 // sent to camera HAL processes)
4670 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
4671 } else {
4672 // In passthrough mode the FDs are now owned by HAL
4673 cleanupNativeHandles(&handlesCreated);
4674 }
4675 } else {
4676 popInflightBuffers(inflightBuffers);
4677 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004678 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004679 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004680}
4681
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004682status_t Camera3Device::HalInterface::flush() {
4683 ATRACE_NAME("CameraHal::flush");
4684 if (!valid()) return INVALID_OPERATION;
4685 status_t res = OK;
4686
Emilian Peev31abd0a2017-05-11 18:37:46 +01004687 auto err = mHidlSession->flush();
4688 if (!err.isOk()) {
4689 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4690 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004691 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004692 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004693 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004694
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004695 return res;
4696}
4697
Emilian Peev31abd0a2017-05-11 18:37:46 +01004698status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004699 ATRACE_NAME("CameraHal::dump");
4700 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004701
Emilian Peev31abd0a2017-05-11 18:37:46 +01004702 // Handled by CameraProviderManager::dump
4703
4704 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004705}
4706
4707status_t Camera3Device::HalInterface::close() {
4708 ATRACE_NAME("CameraHal::close()");
4709 if (!valid()) return INVALID_OPERATION;
4710 status_t res = OK;
4711
Emilian Peev31abd0a2017-05-11 18:37:46 +01004712 auto err = mHidlSession->close();
4713 // Interface will be dead shortly anyway, so don't log errors
4714 if (!err.isOk()) {
4715 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004716 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004717
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004718 return res;
4719}
4720
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004721void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4722 ATRACE_NAME("CameraHal::signalPipelineDrain");
4723 if (!valid() || mHidlSession_3_5 == nullptr) {
4724 ALOGE("%s called on invalid camera!", __FUNCTION__);
4725 return;
4726 }
4727
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004728 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004729 if (!err.isOk()) {
4730 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4731 return;
4732 }
4733}
4734
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004735void Camera3Device::HalInterface::getInflightBufferKeys(
4736 std::vector<std::pair<int32_t, int32_t>>* out) {
4737 std::lock_guard<std::mutex> lock(mInflightLock);
4738 out->clear();
4739 out->reserve(mInflightBufferMap.size());
4740 for (auto& pair : mInflightBufferMap) {
4741 uint64_t key = pair.first;
4742 int32_t streamId = key & 0xFFFFFFFF;
4743 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4744 out->push_back(std::make_pair(frameNumber, streamId));
4745 }
4746 return;
4747}
4748
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004749void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4750 std::vector<uint64_t>* out) {
4751 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4752 out->clear();
4753 out->reserve(mRequestedBuffers.size());
4754 for (auto& pair : mRequestedBuffers) {
4755 out->push_back(pair.first);
4756 }
4757 return;
4758}
4759
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004760status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004761 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004762 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004763 mInflightBufferMap[key] = buffer;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004764 return OK;
4765}
4766
4767status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004768 int32_t frameNumber, int32_t streamId,
4769 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004770 std::lock_guard<std::mutex> lock(mInflightLock);
4771
4772 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4773 auto it = mInflightBufferMap.find(key);
4774 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004775 if (buffer != nullptr) {
4776 *buffer = it->second;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004777 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004778 mInflightBufferMap.erase(it);
4779 return OK;
4780}
4781
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004782void Camera3Device::HalInterface::popInflightBuffers(
4783 const std::vector<std::pair<int32_t, int32_t>>& buffers) {
4784 for (const auto& pair : buffers) {
4785 int32_t frameNumber = pair.first;
4786 int32_t streamId = pair.second;
4787 popInflightBuffer(frameNumber, streamId, nullptr);
4788 }
4789}
4790
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004791status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004792 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004793 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004794 auto pair = mRequestedBuffers.insert({bufferId, {streamId, buf}});
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004795 if (!pair.second) {
4796 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4797 __FUNCTION__, bufferId);
4798 return BAD_VALUE;
4799 }
4800 return OK;
4801}
4802
4803// Find and pop a buffer_handle_t based on bufferId
4804status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004805 uint64_t bufferId,
4806 /*out*/ buffer_handle_t** buffer,
4807 /*optional out*/ int32_t* streamId) {
4808 if (buffer == nullptr) {
4809 ALOGE("%s: buffer (%p) must not be null", __FUNCTION__, buffer);
4810 return BAD_VALUE;
4811 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004812 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4813 auto it = mRequestedBuffers.find(bufferId);
4814 if (it == mRequestedBuffers.end()) {
4815 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4816 __FUNCTION__, bufferId);
4817 return BAD_VALUE;
4818 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004819 *buffer = it->second.second;
4820 if (streamId != nullptr) {
4821 *streamId = it->second.first;
4822 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004823 mRequestedBuffers.erase(it);
4824 return OK;
4825}
4826
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004827std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4828 const buffer_handle_t& buf, int streamId) {
4829 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4830
4831 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4832 auto it = bIdMap.find(buf);
4833 if (it == bIdMap.end()) {
4834 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004835 ALOGV("stream %d now have %zu buffer caches, buf %p",
4836 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004837 return std::make_pair(true, mNextBufferId - 1);
4838 } else {
4839 return std::make_pair(false, it->second);
4840 }
4841}
4842
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004843void Camera3Device::HalInterface::onBufferFreed(
4844 int streamId, const native_handle_t* handle) {
4845 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4846 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4847 auto mapIt = mBufferIdMaps.find(streamId);
4848 if (mapIt == mBufferIdMaps.end()) {
4849 // streamId might be from a deleted stream here
4850 ALOGI("%s: stream %d has been removed",
4851 __FUNCTION__, streamId);
4852 return;
4853 }
4854 BufferIdMap& bIdMap = mapIt->second;
4855 auto it = bIdMap.find(handle);
4856 if (it == bIdMap.end()) {
4857 ALOGW("%s: cannot find buffer %p in stream %d",
4858 __FUNCTION__, handle, streamId);
4859 return;
4860 } else {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004861 bufferId = it->second;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004862 bIdMap.erase(it);
4863 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4864 __FUNCTION__, streamId, bIdMap.size(), handle);
4865 }
4866 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4867}
4868
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004869void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
4870 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4871 auto mapIt = mBufferIdMaps.find(streamId);
4872 if (mapIt == mBufferIdMaps.end()) {
4873 ALOGE("%s: streamId %d not found!", __FUNCTION__, streamId);
4874 return;
4875 }
4876
4877 BufferIdMap& bIdMap = mapIt->second;
4878 for (const auto& it : bIdMap) {
4879 uint64_t bufferId = it.second;
4880 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4881 }
4882 bIdMap.clear();
4883}
4884
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004885/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004886 * RequestThread inner class methods
4887 */
4888
4889Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004890 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004891 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4892 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004893 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004894 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004895 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004896 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004897 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004898 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004899 mReconfigured(false),
4900 mDoPause(false),
4901 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004902 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004903 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004904 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004905 mCurrentAfTriggerId(0),
4906 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004907 mRepeatingLastFrameNumber(
4908 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004909 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004910 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004911 mRequestLatency(kRequestLatencyBinSize),
4912 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004913 mLatestSessionParams(sessionParamKeys.size()),
4914 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004915 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004916}
4917
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004918Camera3Device::RequestThread::~RequestThread() {}
4919
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004920void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004921 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004922 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004923 Mutex::Autolock l(mRequestLock);
4924 mListener = listener;
4925}
4926
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004927void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4928 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004929 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004930 Mutex::Autolock l(mRequestLock);
4931 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004932 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004933 // Prepare video stream for high speed recording.
4934 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004935 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004936}
4937
Jianing Wei90e59c92014-03-12 18:29:36 -07004938status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004939 List<sp<CaptureRequest> > &requests,
4940 /*out*/
4941 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004942 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004943 Mutex::Autolock l(mRequestLock);
4944 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4945 ++it) {
4946 mRequestQueue.push_back(*it);
4947 }
4948
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004949 if (lastFrameNumber != NULL) {
4950 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4951 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4952 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4953 *lastFrameNumber);
4954 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004955
Jianing Wei90e59c92014-03-12 18:29:36 -07004956 unpauseForNewRequests();
4957
4958 return OK;
4959}
4960
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004961
4962status_t Camera3Device::RequestThread::queueTrigger(
4963 RequestTrigger trigger[],
4964 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004965 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004966 Mutex::Autolock l(mTriggerMutex);
4967 status_t ret;
4968
4969 for (size_t i = 0; i < count; ++i) {
4970 ret = queueTriggerLocked(trigger[i]);
4971
4972 if (ret != OK) {
4973 return ret;
4974 }
4975 }
4976
4977 return OK;
4978}
4979
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004980const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4981 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004982 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004983 if (d != nullptr) return d->mId;
4984 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004985}
4986
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004987status_t Camera3Device::RequestThread::queueTriggerLocked(
4988 RequestTrigger trigger) {
4989
4990 uint32_t tag = trigger.metadataTag;
4991 ssize_t index = mTriggerMap.indexOfKey(tag);
4992
4993 switch (trigger.getTagType()) {
4994 case TYPE_BYTE:
4995 // fall-through
4996 case TYPE_INT32:
4997 break;
4998 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004999 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
5000 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005001 return INVALID_OPERATION;
5002 }
5003
5004 /**
5005 * Collect only the latest trigger, since we only have 1 field
5006 * in the request settings per trigger tag, and can't send more than 1
5007 * trigger per request.
5008 */
5009 if (index != NAME_NOT_FOUND) {
5010 mTriggerMap.editValueAt(index) = trigger;
5011 } else {
5012 mTriggerMap.add(tag, trigger);
5013 }
5014
5015 return OK;
5016}
5017
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005018status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005019 const RequestList &requests,
5020 /*out*/
5021 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005022 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005023 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005024 if (lastFrameNumber != NULL) {
5025 *lastFrameNumber = mRepeatingLastFrameNumber;
5026 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005027 mRepeatingRequests.clear();
5028 mRepeatingRequests.insert(mRepeatingRequests.begin(),
5029 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005030
5031 unpauseForNewRequests();
5032
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005033 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005034 return OK;
5035}
5036
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07005037bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005038 if (mRepeatingRequests.empty()) {
5039 return false;
5040 }
5041 int32_t requestId = requestIn->mResultExtras.requestId;
5042 const RequestList &repeatRequests = mRepeatingRequests;
5043 // All repeating requests are guaranteed to have same id so only check first quest
5044 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
5045 return (firstRequest->mResultExtras.requestId == requestId);
5046}
5047
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005048status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005049 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005050 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005051 return clearRepeatingRequestsLocked(lastFrameNumber);
5052
5053}
5054
5055status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005056 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005057 if (lastFrameNumber != NULL) {
5058 *lastFrameNumber = mRepeatingLastFrameNumber;
5059 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005060 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005061 return OK;
5062}
5063
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005064status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005065 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005066 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005067 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005068 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005069
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005070 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005071
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005072 // Send errors for all requests pending in the request queue, including
5073 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005074 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005075 if (listener != NULL) {
5076 for (RequestList::iterator it = mRequestQueue.begin();
5077 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005078 // Abort the input buffers for reprocess requests.
5079 if ((*it)->mInputStream != NULL) {
5080 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07005081 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
5082 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005083 if (res != OK) {
5084 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
5085 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5086 } else {
5087 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
5088 if (res != OK) {
5089 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
5090 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5091 }
5092 }
5093 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005094 // Set the frame number this request would have had, if it
5095 // had been submitted; this frame number will not be reused.
5096 // The requestId and burstId fields were set when the request was
5097 // submitted originally (in convertMetadataListToRequestListLocked)
5098 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005099 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005100 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005101 }
5102 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005103 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08005104
5105 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005106 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005107 if (lastFrameNumber != NULL) {
5108 *lastFrameNumber = mRepeatingLastFrameNumber;
5109 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005110 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005111 return OK;
5112}
5113
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005114status_t Camera3Device::RequestThread::flush() {
5115 ATRACE_CALL();
5116 Mutex::Autolock l(mFlushLock);
5117
Emilian Peev08dd2452017-04-06 16:55:14 +01005118 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005119}
5120
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005121void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005122 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005123 Mutex::Autolock l(mPauseLock);
5124 mDoPause = paused;
5125 mDoPauseSignal.signal();
5126}
5127
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005128status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
5129 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005130 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005131 Mutex::Autolock l(mLatestRequestMutex);
5132 status_t res;
5133 while (mLatestRequestId != requestId) {
5134 nsecs_t startTime = systemTime();
5135
5136 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
5137 if (res != OK) return res;
5138
5139 timeout -= (systemTime() - startTime);
5140 }
5141
5142 return OK;
5143}
5144
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005145void Camera3Device::RequestThread::requestExit() {
5146 // Call parent to set up shutdown
5147 Thread::requestExit();
5148 // The exit from any possible waits
5149 mDoPauseSignal.signal();
5150 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07005151
5152 mRequestLatency.log("ProcessCaptureRequest latency histogram");
5153 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005154}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005155
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005156void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005157 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005158 bool surfaceAbandoned = false;
5159 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005160 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005161 {
5162 Mutex::Autolock l(mRequestLock);
5163 // Check all streams needed by repeating requests are still valid. Otherwise, stop
5164 // repeating requests.
5165 for (const auto& request : mRepeatingRequests) {
5166 for (const auto& s : request->mOutputStreams) {
5167 if (s->isAbandoned()) {
5168 surfaceAbandoned = true;
5169 clearRepeatingRequestsLocked(&lastFrameNumber);
5170 break;
5171 }
5172 }
5173 if (surfaceAbandoned) {
5174 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005175 }
5176 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005177 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005178 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005179
5180 if (listener != NULL && surfaceAbandoned) {
5181 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005182 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005183}
5184
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005185bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005186 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005187 status_t res;
5188 size_t batchSize = mNextRequests.size();
5189 std::vector<camera3_capture_request_t*> requests(batchSize);
5190 uint32_t numRequestProcessed = 0;
5191 for (size_t i = 0; i < batchSize; i++) {
5192 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07005193 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005194 }
5195
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005196 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
5197
5198 bool triggerRemoveFailed = false;
5199 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
5200 for (size_t i = 0; i < numRequestProcessed; i++) {
5201 NextRequest& nextRequest = mNextRequests.editItemAt(i);
5202 nextRequest.submitted = true;
5203
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005204 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00005205
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005206 if (!triggerRemoveFailed) {
5207 // Remove any previously queued triggers (after unlock)
5208 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5209 if (removeTriggerRes != OK) {
5210 triggerRemoveFailed = true;
5211 triggerFailedRequest = nextRequest;
5212 }
5213 }
5214 }
5215
5216 if (triggerRemoveFailed) {
5217 SET_ERR("RequestThread: Unable to remove triggers "
5218 "(capture request %d, HAL device: %s (%d)",
5219 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5220 cleanUpFailedRequests(/*sendRequestError*/ false);
5221 return false;
5222 }
5223
5224 if (res != OK) {
5225 // Should only get a failure here for malformed requests or device-level
5226 // errors, so consider all errors fatal. Bad metadata failures should
5227 // come through notify.
5228 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5229 mNextRequests[numRequestProcessed].halRequest.frame_number,
5230 strerror(-res), res);
5231 cleanUpFailedRequests(/*sendRequestError*/ false);
5232 return false;
5233 }
5234 return true;
5235}
5236
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005237nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5238 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5239 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5240 find_camera_metadata_ro_entry(request,
5241 ANDROID_CONTROL_AE_MODE,
5242 &e);
5243 if (e.count == 0) return maxExpectedDuration;
5244
5245 switch (e.data.u8[0]) {
5246 case ANDROID_CONTROL_AE_MODE_OFF:
5247 find_camera_metadata_ro_entry(request,
5248 ANDROID_SENSOR_EXPOSURE_TIME,
5249 &e);
5250 if (e.count > 0) {
5251 maxExpectedDuration = e.data.i64[0];
5252 }
5253 find_camera_metadata_ro_entry(request,
5254 ANDROID_SENSOR_FRAME_DURATION,
5255 &e);
5256 if (e.count > 0) {
5257 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5258 }
5259 break;
5260 default:
5261 find_camera_metadata_ro_entry(request,
5262 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5263 &e);
5264 if (e.count > 1) {
5265 maxExpectedDuration = 1e9 / e.data.u8[0];
5266 }
5267 break;
5268 }
5269
5270 return maxExpectedDuration;
5271}
5272
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005273bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5274 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5275 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5276 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5277 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5278 return true;
5279 }
5280
5281 return false;
5282}
5283
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005284void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
5285 // Update the latest request sent to HAL
5286 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5287 Mutex::Autolock al(mLatestRequestMutex);
5288
5289 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5290 mLatestRequest.acquire(cloned);
5291
5292 mLatestPhysicalRequest.clear();
5293 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
5294 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
5295 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
5296 CameraMetadata(cloned));
5297 }
5298
5299 sp<Camera3Device> parent = mParent.promote();
5300 if (parent != NULL) {
5301 parent->monitorMetadata(TagMonitor::REQUEST,
5302 nextRequest.halRequest.frame_number,
5303 0, mLatestRequest, mLatestPhysicalRequest);
5304 }
5305 }
5306
5307 if (nextRequest.halRequest.settings != NULL) {
5308 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5309 nextRequest.halRequest.settings);
5310 }
5311
5312 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5313}
5314
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005315bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5316 ATRACE_CALL();
5317 bool updatesDetected = false;
5318
Emilian Peev4ec17882019-01-24 17:16:58 -08005319 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005320 for (auto tag : mSessionParamKeys) {
5321 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005322 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005323
5324 if (entry.count > 0) {
5325 bool isDifferent = false;
5326 if (lastEntry.count > 0) {
5327 // Have a last value, compare to see if changed
5328 if (lastEntry.type == entry.type &&
5329 lastEntry.count == entry.count) {
5330 // Same type and count, compare values
5331 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5332 size_t entryBytes = bytesPerValue * lastEntry.count;
5333 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5334 if (cmp != 0) {
5335 isDifferent = true;
5336 }
5337 } else {
5338 // Count or type has changed
5339 isDifferent = true;
5340 }
5341 } else {
5342 // No last entry, so always consider to be different
5343 isDifferent = true;
5344 }
5345
5346 if (isDifferent) {
5347 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005348 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5349 updatesDetected = true;
5350 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005351 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005352 }
5353 } else if (lastEntry.count > 0) {
5354 // Value has been removed
5355 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005356 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005357 updatesDetected = true;
5358 }
5359 }
5360
Emilian Peev4ec17882019-01-24 17:16:58 -08005361 bool reconfigureRequired;
5362 if (updatesDetected) {
5363 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5364 updatedParams);
5365 mLatestSessionParams = updatedParams;
5366 } else {
5367 reconfigureRequired = false;
5368 }
5369
5370 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005371}
5372
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005373bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005374 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005375 status_t res;
5376
5377 // Handle paused state.
5378 if (waitIfPaused()) {
5379 return true;
5380 }
5381
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005382 // Wait for the next batch of requests.
5383 waitForNextRequestBatch();
5384 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005385 return true;
5386 }
5387
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005388 // Get the latest request ID, if any
5389 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005390 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005391 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005392 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005393 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005394 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005395 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5396 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005397 }
5398
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005399 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5400 // or a single request from streaming or burst. In either case the first element
5401 // should contain the latest camera settings that we need to check for any session
5402 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005403 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005404 res = OK;
5405
5406 //Input stream buffers are already acquired at this point so an input stream
5407 //will not be able to move to idle state unless we force it.
5408 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5409 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5410 if (res != OK) {
5411 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5412 cleanUpFailedRequests(/*sendRequestError*/ false);
5413 return false;
5414 }
5415 }
5416
5417 if (res == OK) {
5418 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5419 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005420 sp<Camera3Device> parent = mParent.promote();
5421 if (parent != nullptr) {
5422 parent->pauseStateNotify(true);
5423 }
5424
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005425 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5426
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005427 if (parent != nullptr) {
5428 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5429 }
5430
5431 statusTracker->markComponentActive(mStatusId);
5432 setPaused(false);
5433 }
5434
5435 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5436 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5437 if (res != OK) {
5438 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5439 cleanUpFailedRequests(/*sendRequestError*/ false);
5440 return false;
5441 }
5442 }
5443 }
5444 }
5445
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005446 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005447 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005448 if (res == TIMED_OUT) {
5449 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005450 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005451 // Check if any stream is abandoned.
5452 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005453 return true;
5454 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005455 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005456 return false;
5457 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005458
Zhijun Hecc27e112013-10-03 16:12:43 -07005459 // Inform waitUntilRequestProcessed thread of a new request ID
5460 {
5461 Mutex::Autolock al(mLatestRequestMutex);
5462
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005463 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005464 mLatestRequestSignal.signal();
5465 }
5466
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005467 // Submit a batch of requests to HAL.
5468 // Use flush lock only when submitting multilple requests in a batch.
5469 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5470 // which may take a long time to finish so synchronizing flush() and
5471 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5472 // For now, only synchronize for high speed recording and we should figure something out for
5473 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005474 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005475
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005476 if (useFlushLock) {
5477 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005478 }
5479
Zhijun Hef0645c12016-08-02 00:58:11 -07005480 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005481 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005482
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005483 sp<Camera3Device> parent = mParent.promote();
5484 if (parent != nullptr) {
5485 parent->mRequestBufferSM.onSubmittingRequest();
5486 }
5487
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005488 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005489 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07005490 submitRequestSuccess = sendRequestsBatch();
5491
Shuzhen Wang686f6442017-06-20 16:16:04 -07005492 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5493 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005494
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005495 if (useFlushLock) {
5496 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005497 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005498
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005499 // Unset as current request
5500 {
5501 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005502 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005503 }
5504
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005505 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005506}
5507
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005508status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005509 ATRACE_CALL();
5510
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005511 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005512 for (size_t i = 0; i < mNextRequests.size(); i++) {
5513 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005514 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5515 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5516 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5517
5518 // Prepare a request to HAL
5519 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5520
5521 // Insert any queued triggers (before metadata is locked)
5522 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005523 if (res < 0) {
5524 SET_ERR("RequestThread: Unable to insert triggers "
5525 "(capture request %d, HAL device: %s (%d)",
5526 halRequest->frame_number, strerror(-res), res);
5527 return INVALID_OPERATION;
5528 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005529
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005530 int triggerCount = res;
5531 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5532 mPrevTriggers = triggerCount;
5533
5534 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005535 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5536 // Request settings are all the same within one batch, so only treat the first
5537 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005538 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005539 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005540 /**
5541 * HAL workaround:
5542 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5543 */
5544 res = addDummyTriggerIds(captureRequest);
5545 if (res != OK) {
5546 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5547 "(capture request %d, HAL device: %s (%d)",
5548 halRequest->frame_number, strerror(-res), res);
5549 return INVALID_OPERATION;
5550 }
5551
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005552 {
5553 // Correct metadata regions for distortion correction if enabled
5554 sp<Camera3Device> parent = mParent.promote();
5555 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07005556 List<PhysicalCameraSettings>::iterator it;
5557 for (it = captureRequest->mSettingsList.begin();
5558 it != captureRequest->mSettingsList.end(); it++) {
5559 if (parent->mDistortionMappers.find(it->cameraId) ==
5560 parent->mDistortionMappers.end()) {
5561 continue;
5562 }
5563 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
5564 &(it->metadata));
5565 if (res != OK) {
5566 SET_ERR("RequestThread: Unable to correct capture requests "
5567 "for lens distortion for request %d: %s (%d)",
5568 halRequest->frame_number, strerror(-res), res);
5569 return INVALID_OPERATION;
5570 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005571 }
5572 }
5573 }
5574
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005575 /**
5576 * The request should be presorted so accesses in HAL
5577 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5578 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005579 captureRequest->mSettingsList.begin()->metadata.sort();
5580 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005581 mPrevRequest = captureRequest;
5582 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5583
5584 IF_ALOGV() {
5585 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5586 find_camera_metadata_ro_entry(
5587 halRequest->settings,
5588 ANDROID_CONTROL_AF_TRIGGER,
5589 &e
5590 );
5591 if (e.count > 0) {
5592 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5593 __FUNCTION__,
5594 halRequest->frame_number,
5595 e.data.u8[0]);
5596 }
5597 }
5598 } else {
5599 // leave request.settings NULL to indicate 'reuse latest given'
5600 ALOGVV("%s: Request settings are REUSED",
5601 __FUNCTION__);
5602 }
5603
Emilian Peevaebbe412018-01-15 13:53:24 +00005604 if (captureRequest->mSettingsList.size() > 1) {
5605 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5606 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005607 if (newRequest) {
5608 halRequest->physcam_settings =
5609 new const camera_metadata* [halRequest->num_physcam_settings];
5610 } else {
5611 halRequest->physcam_settings = nullptr;
5612 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005613 auto it = ++captureRequest->mSettingsList.begin();
5614 size_t i = 0;
5615 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5616 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005617 if (newRequest) {
5618 it->metadata.sort();
5619 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5620 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005621 }
5622 }
5623
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005624 uint32_t totalNumBuffers = 0;
5625
5626 // Fill in buffers
5627 if (captureRequest->mInputStream != NULL) {
5628 halRequest->input_buffer = &captureRequest->mInputBuffer;
5629 totalNumBuffers += 1;
5630 } else {
5631 halRequest->input_buffer = NULL;
5632 }
5633
5634 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5635 captureRequest->mOutputStreams.size());
5636 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005637 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005638
5639 sp<Camera3Device> parent = mParent.promote();
5640 if (parent == NULL) {
5641 // Should not happen, and nowhere to send errors to, so just log it
5642 CLOGE("RequestThread: Parent is gone");
5643 return INVALID_OPERATION;
5644 }
5645 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5646
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005647 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005648 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005649 sp<Camera3OutputStreamInterface> outputStream =
5650 captureRequest->mOutputStreams.editItemAt(j);
5651 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005652
5653 // Prepare video buffers for high speed recording on the first video request.
5654 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5655 // Only try to prepare video stream on the first video request.
5656 mPrepareVideoStream = false;
5657
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005658 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5659 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005660 while (res == NOT_ENOUGH_DATA) {
5661 res = outputStream->prepareNextBuffer();
5662 }
5663 if (res != OK) {
5664 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5665 __FUNCTION__, strerror(-res), res);
5666 outputStream->cancelPrepare();
5667 }
5668 }
5669
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005670 std::vector<size_t> uniqueSurfaceIds;
5671 res = outputStream->getUniqueSurfaceIds(
5672 captureRequest->mOutputSurfaces[streamId],
5673 &uniqueSurfaceIds);
5674 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5675 if (res != OK && res != INVALID_OPERATION) {
5676 ALOGE("%s: failed to query stream %d unique surface IDs",
5677 __FUNCTION__, streamId);
5678 return res;
5679 }
5680 if (res == OK) {
5681 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5682 }
5683
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005684 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005685 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005686 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005687 return TIMED_OUT;
5688 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005689 // HAL will request buffer through requestStreamBuffer API
5690 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5691 buffer.stream = outputStream->asHalStream();
5692 buffer.buffer = nullptr;
5693 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5694 buffer.acquire_fence = -1;
5695 buffer.release_fence = -1;
5696 } else {
5697 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5698 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005699 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005700 if (res != OK) {
5701 // Can't get output buffer from gralloc queue - this could be due to
5702 // abandoned queue or other consumer misbehavior, so not a fatal
5703 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005704 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005705 " %s (%d)", strerror(-res), res);
5706
5707 return TIMED_OUT;
5708 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005709 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005710
5711 {
5712 sp<Camera3Device> parent = mParent.promote();
5713 if (parent != nullptr) {
5714 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5715 for (const auto& settings : captureRequest->mSettingsList) {
5716 if ((streamCameraId.isEmpty() &&
5717 parent->getId() == settings.cameraId.c_str()) ||
5718 streamCameraId == settings.cameraId.c_str()) {
5719 outputStream->fireBufferRequestForFrameNumber(
5720 captureRequest->mResultExtras.frameNumber,
5721 settings.metadata);
5722 }
5723 }
5724 }
5725 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005726
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005727 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5728
5729 if (!physicalCameraId.isEmpty()) {
5730 // Physical stream isn't supported for input request.
5731 if (halRequest->input_buffer) {
5732 CLOGE("Physical stream is not supported for input request");
5733 return INVALID_OPERATION;
5734 }
5735 requestedPhysicalCameras.insert(physicalCameraId);
5736 }
5737 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005738 }
5739 totalNumBuffers += halRequest->num_output_buffers;
5740
5741 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005742 // If this request list is for constrained high speed recording (not
5743 // preview), and the current request is not the last one in the batch,
5744 // do not send callback to the app.
5745 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005746 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005747 hasCallback = false;
5748 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005749 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005750 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005751 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5752 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5753 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5754 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5755 isStillCapture = true;
5756 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5757 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005758
5759 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5760 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5761 isZslCapture = true;
5762 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005763 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005764 res = parent->registerInFlight(halRequest->frame_number,
5765 totalNumBuffers, captureRequest->mResultExtras,
5766 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005767 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005768 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005769 requestedPhysicalCameras, isStillCapture, isZslCapture,
5770 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5771 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005772 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5773 ", burstId = %" PRId32 ".",
5774 __FUNCTION__,
5775 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5776 captureRequest->mResultExtras.burstId);
5777 if (res != OK) {
5778 SET_ERR("RequestThread: Unable to register new in-flight request:"
5779 " %s (%d)", strerror(-res), res);
5780 return INVALID_OPERATION;
5781 }
5782 }
5783
5784 return OK;
5785}
5786
Igor Murashkin1e479c02013-09-06 16:55:14 -07005787CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005788 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005789 Mutex::Autolock al(mLatestRequestMutex);
5790
5791 ALOGV("RequestThread::%s", __FUNCTION__);
5792
5793 return mLatestRequest;
5794}
5795
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005796bool Camera3Device::RequestThread::isStreamPending(
5797 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005798 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005799 Mutex::Autolock l(mRequestLock);
5800
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005801 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005802 if (!nextRequest.submitted) {
5803 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5804 if (stream == s) return true;
5805 }
5806 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005807 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005808 }
5809
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005810 for (const auto& request : mRequestQueue) {
5811 for (const auto& s : request->mOutputStreams) {
5812 if (stream == s) return true;
5813 }
5814 if (stream == request->mInputStream) return true;
5815 }
5816
5817 for (const auto& request : mRepeatingRequests) {
5818 for (const auto& s : request->mOutputStreams) {
5819 if (stream == s) return true;
5820 }
5821 if (stream == request->mInputStream) return true;
5822 }
5823
5824 return false;
5825}
Jianing Weicb0652e2014-03-12 18:29:36 -07005826
Emilian Peev40ead602017-09-26 15:46:36 +01005827bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5828 ATRACE_CALL();
5829 Mutex::Autolock l(mRequestLock);
5830
5831 for (const auto& nextRequest : mNextRequests) {
5832 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5833 if (s.first == streamId) {
5834 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5835 if (it != s.second.end()) {
5836 return true;
5837 }
5838 }
5839 }
5840 }
5841
5842 for (const auto& request : mRequestQueue) {
5843 for (const auto& s : request->mOutputSurfaces) {
5844 if (s.first == streamId) {
5845 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5846 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005847 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005848 }
5849 }
5850 }
5851 }
5852
5853 for (const auto& request : mRepeatingRequests) {
5854 for (const auto& s : request->mOutputSurfaces) {
5855 if (s.first == streamId) {
5856 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5857 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005858 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005859 }
5860 }
5861 }
5862 }
5863
5864 return false;
5865}
5866
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005867void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5868 if (!mUseHalBufManager) {
5869 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5870 return;
5871 }
5872
5873 Mutex::Autolock pl(mPauseLock);
5874 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005875 mInterface->signalPipelineDrain(streamIds);
5876 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005877 }
5878 // If request thread is still busy, wait until paused then notify HAL
5879 mNotifyPipelineDrain = true;
5880 mStreamIdsToBeDrained = streamIds;
5881}
5882
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005883nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005884 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005885 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005886 return mExpectedInflightDuration > kMinInflightDuration ?
5887 mExpectedInflightDuration : kMinInflightDuration;
5888}
5889
Emilian Peevaebbe412018-01-15 13:53:24 +00005890void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5891 camera3_capture_request_t *halRequest) {
5892 if ((request == nullptr) || (halRequest == nullptr)) {
5893 ALOGE("%s: Invalid request!", __FUNCTION__);
5894 return;
5895 }
5896
5897 if (halRequest->num_physcam_settings > 0) {
5898 if (halRequest->physcam_id != nullptr) {
5899 delete [] halRequest->physcam_id;
5900 halRequest->physcam_id = nullptr;
5901 }
5902 if (halRequest->physcam_settings != nullptr) {
5903 auto it = ++(request->mSettingsList.begin());
5904 size_t i = 0;
5905 for (; it != request->mSettingsList.end(); it++, i++) {
5906 it->metadata.unlock(halRequest->physcam_settings[i]);
5907 }
5908 delete [] halRequest->physcam_settings;
5909 halRequest->physcam_settings = nullptr;
5910 }
5911 }
5912}
5913
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005914void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5915 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005916 return;
5917 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005918
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005919 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005920 // Skip the ones that have been submitted successfully.
5921 if (nextRequest.submitted) {
5922 continue;
5923 }
5924
5925 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5926 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5927 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5928
5929 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005930 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005931 }
5932
Emilian Peevaebbe412018-01-15 13:53:24 +00005933 cleanupPhysicalSettings(captureRequest, halRequest);
5934
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005935 if (captureRequest->mInputStream != NULL) {
5936 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5937 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5938 }
5939
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005940 // No output buffer can be returned when using HAL buffer manager
5941 if (!mUseHalBufManager) {
5942 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5943 //Buffers that failed processing could still have
5944 //valid acquire fence.
5945 int acquireFence = (*outputBuffers)[i].acquire_fence;
5946 if (0 <= acquireFence) {
5947 close(acquireFence);
5948 outputBuffers->editItemAt(i).acquire_fence = -1;
5949 }
5950 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5951 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5952 /*timestampIncreasing*/true, std::vector<size_t> (),
5953 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005954 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005955 }
5956
5957 if (sendRequestError) {
5958 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005959 sp<NotificationListener> listener = mListener.promote();
5960 if (listener != NULL) {
5961 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005962 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005963 captureRequest->mResultExtras);
5964 }
5965 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005966
5967 // Remove yet-to-be submitted inflight request from inflightMap
5968 {
5969 sp<Camera3Device> parent = mParent.promote();
5970 if (parent != NULL) {
5971 Mutex::Autolock l(parent->mInFlightLock);
5972 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5973 if (idx >= 0) {
5974 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5975 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5976 parent->removeInFlightMapEntryLocked(idx);
5977 }
5978 }
5979 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005980 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005981
5982 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005983 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005984}
5985
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005986void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005987 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005988 // Optimized a bit for the simple steady-state case (single repeating
5989 // request), to avoid putting that request in the queue temporarily.
5990 Mutex::Autolock l(mRequestLock);
5991
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005992 assert(mNextRequests.empty());
5993
5994 NextRequest nextRequest;
5995 nextRequest.captureRequest = waitForNextRequestLocked();
5996 if (nextRequest.captureRequest == nullptr) {
5997 return;
5998 }
5999
6000 nextRequest.halRequest = camera3_capture_request_t();
6001 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006002 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006003
6004 // Wait for additional requests
6005 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
6006
6007 for (size_t i = 1; i < batchSize; i++) {
6008 NextRequest additionalRequest;
6009 additionalRequest.captureRequest = waitForNextRequestLocked();
6010 if (additionalRequest.captureRequest == nullptr) {
6011 break;
6012 }
6013
6014 additionalRequest.halRequest = camera3_capture_request_t();
6015 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006016 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006017 }
6018
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006019 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006020 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006021 mNextRequests.size(), batchSize);
6022 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006023 }
6024
6025 return;
6026}
6027
6028sp<Camera3Device::CaptureRequest>
6029 Camera3Device::RequestThread::waitForNextRequestLocked() {
6030 status_t res;
6031 sp<CaptureRequest> nextRequest;
6032
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006033 while (mRequestQueue.empty()) {
6034 if (!mRepeatingRequests.empty()) {
6035 // Always atomically enqueue all requests in a repeating request
6036 // list. Guarantees a complete in-sequence set of captures to
6037 // application.
6038 const RequestList &requests = mRepeatingRequests;
6039 RequestList::const_iterator firstRequest =
6040 requests.begin();
6041 nextRequest = *firstRequest;
6042 mRequestQueue.insert(mRequestQueue.end(),
6043 ++firstRequest,
6044 requests.end());
6045 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07006046
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006047 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07006048
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006049 break;
6050 }
6051
6052 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
6053
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006054 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
6055 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006056 Mutex::Autolock pl(mPauseLock);
6057 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006058 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006059 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006060 if (mNotifyPipelineDrain) {
6061 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6062 mNotifyPipelineDrain = false;
6063 mStreamIdsToBeDrained.clear();
6064 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006065 // Let the tracker know
6066 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6067 if (statusTracker != 0) {
6068 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6069 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006070 sp<Camera3Device> parent = mParent.promote();
6071 if (parent != nullptr) {
6072 parent->mRequestBufferSM.onRequestThreadPaused();
6073 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006074 }
6075 // Stop waiting for now and let thread management happen
6076 return NULL;
6077 }
6078 }
6079
6080 if (nextRequest == NULL) {
6081 // Don't have a repeating request already in hand, so queue
6082 // must have an entry now.
6083 RequestList::iterator firstRequest =
6084 mRequestQueue.begin();
6085 nextRequest = *firstRequest;
6086 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07006087 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
6088 sp<NotificationListener> listener = mListener.promote();
6089 if (listener != NULL) {
6090 listener->notifyRequestQueueEmpty();
6091 }
6092 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006093 }
6094
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006095 // In case we've been unpaused by setPaused clearing mDoPause, need to
6096 // update internal pause state (capture/setRepeatingRequest unpause
6097 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006098 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006099 if (mPaused) {
6100 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
6101 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6102 if (statusTracker != 0) {
6103 statusTracker->markComponentActive(mStatusId);
6104 }
6105 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006106 mPaused = false;
6107
6108 // Check if we've reconfigured since last time, and reset the preview
6109 // request if so. Can't use 'NULL request == repeat' across configure calls.
6110 if (mReconfigured) {
6111 mPrevRequest.clear();
6112 mReconfigured = false;
6113 }
6114
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006115 if (nextRequest != NULL) {
6116 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006117 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
6118 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006119
6120 // Since RequestThread::clear() removes buffers from the input stream,
6121 // get the right buffer here before unlocking mRequestLock
6122 if (nextRequest->mInputStream != NULL) {
6123 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
6124 if (res != OK) {
6125 // Can't get input buffer from gralloc queue - this could be due to
6126 // disconnected queue or other producer misbehavior, so not a fatal
6127 // error
6128 ALOGE("%s: Can't get input buffer, skipping request:"
6129 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006130
6131 sp<NotificationListener> listener = mListener.promote();
6132 if (listener != NULL) {
6133 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006134 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006135 nextRequest->mResultExtras);
6136 }
6137 return NULL;
6138 }
6139 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006140 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07006141
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006142 return nextRequest;
6143}
6144
6145bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006146 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006147 status_t res;
6148 Mutex::Autolock l(mPauseLock);
6149 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006150 if (mPaused == false) {
6151 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006152 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006153 if (mNotifyPipelineDrain) {
6154 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6155 mNotifyPipelineDrain = false;
6156 mStreamIdsToBeDrained.clear();
6157 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006158 // Let the tracker know
6159 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6160 if (statusTracker != 0) {
6161 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6162 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006163 sp<Camera3Device> parent = mParent.promote();
6164 if (parent != nullptr) {
6165 parent->mRequestBufferSM.onRequestThreadPaused();
6166 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006167 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006168
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006169 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006170 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006171 return true;
6172 }
6173 }
6174 // We don't set mPaused to false here, because waitForNextRequest needs
6175 // to further manage the paused state in case of starvation.
6176 return false;
6177}
6178
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006179void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006180 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006181 // With work to do, mark thread as unpaused.
6182 // If paused by request (setPaused), don't resume, to avoid
6183 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006184 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006185 Mutex::Autolock p(mPauseLock);
6186 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006187 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6188 if (mPaused) {
6189 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6190 if (statusTracker != 0) {
6191 statusTracker->markComponentActive(mStatusId);
6192 }
6193 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006194 mPaused = false;
6195 }
6196}
6197
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006198void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6199 sp<Camera3Device> parent = mParent.promote();
6200 if (parent != NULL) {
6201 va_list args;
6202 va_start(args, fmt);
6203
6204 parent->setErrorStateV(fmt, args);
6205
6206 va_end(args);
6207 }
6208}
6209
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006210status_t Camera3Device::RequestThread::insertTriggers(
6211 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006212 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006213 Mutex::Autolock al(mTriggerMutex);
6214
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006215 sp<Camera3Device> parent = mParent.promote();
6216 if (parent == NULL) {
6217 CLOGE("RequestThread: Parent is gone");
6218 return DEAD_OBJECT;
6219 }
6220
Emilian Peevaebbe412018-01-15 13:53:24 +00006221 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006222 size_t count = mTriggerMap.size();
6223
6224 for (size_t i = 0; i < count; ++i) {
6225 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006226 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006227
6228 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6229 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6230 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006231 if (isAeTrigger) {
6232 request->mResultExtras.precaptureTriggerId = triggerId;
6233 mCurrentPreCaptureTriggerId = triggerId;
6234 } else {
6235 request->mResultExtras.afTriggerId = triggerId;
6236 mCurrentAfTriggerId = triggerId;
6237 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006238 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006239 }
6240
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006241 camera_metadata_entry entry = metadata.find(tag);
6242
6243 if (entry.count > 0) {
6244 /**
6245 * Already has an entry for this trigger in the request.
6246 * Rewrite it with our requested trigger value.
6247 */
6248 RequestTrigger oldTrigger = trigger;
6249
6250 oldTrigger.entryValue = entry.data.u8[0];
6251
6252 mTriggerReplacedMap.add(tag, oldTrigger);
6253 } else {
6254 /**
6255 * More typical, no trigger entry, so we just add it
6256 */
6257 mTriggerRemovedMap.add(tag, trigger);
6258 }
6259
6260 status_t res;
6261
6262 switch (trigger.getTagType()) {
6263 case TYPE_BYTE: {
6264 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6265 res = metadata.update(tag,
6266 &entryValue,
6267 /*count*/1);
6268 break;
6269 }
6270 case TYPE_INT32:
6271 res = metadata.update(tag,
6272 &trigger.entryValue,
6273 /*count*/1);
6274 break;
6275 default:
6276 ALOGE("%s: Type not supported: 0x%x",
6277 __FUNCTION__,
6278 trigger.getTagType());
6279 return INVALID_OPERATION;
6280 }
6281
6282 if (res != OK) {
6283 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6284 ", value %d", __FUNCTION__, trigger.getTagName(),
6285 trigger.entryValue);
6286 return res;
6287 }
6288
6289 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6290 trigger.getTagName(),
6291 trigger.entryValue);
6292 }
6293
6294 mTriggerMap.clear();
6295
6296 return count;
6297}
6298
6299status_t Camera3Device::RequestThread::removeTriggers(
6300 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006301 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006302 Mutex::Autolock al(mTriggerMutex);
6303
Emilian Peevaebbe412018-01-15 13:53:24 +00006304 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006305
6306 /**
6307 * Replace all old entries with their old values.
6308 */
6309 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6310 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6311
6312 status_t res;
6313
6314 uint32_t tag = trigger.metadataTag;
6315 switch (trigger.getTagType()) {
6316 case TYPE_BYTE: {
6317 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6318 res = metadata.update(tag,
6319 &entryValue,
6320 /*count*/1);
6321 break;
6322 }
6323 case TYPE_INT32:
6324 res = metadata.update(tag,
6325 &trigger.entryValue,
6326 /*count*/1);
6327 break;
6328 default:
6329 ALOGE("%s: Type not supported: 0x%x",
6330 __FUNCTION__,
6331 trigger.getTagType());
6332 return INVALID_OPERATION;
6333 }
6334
6335 if (res != OK) {
6336 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6337 ", trigger value %d", __FUNCTION__,
6338 trigger.getTagName(), trigger.entryValue);
6339 return res;
6340 }
6341 }
6342 mTriggerReplacedMap.clear();
6343
6344 /**
6345 * Remove all new entries.
6346 */
6347 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6348 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6349 status_t res = metadata.erase(trigger.metadataTag);
6350
6351 if (res != OK) {
6352 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6353 ", trigger value %d", __FUNCTION__,
6354 trigger.getTagName(), trigger.entryValue);
6355 return res;
6356 }
6357 }
6358 mTriggerRemovedMap.clear();
6359
6360 return OK;
6361}
6362
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006363status_t Camera3Device::RequestThread::addDummyTriggerIds(
6364 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006365 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006366 static const int32_t dummyTriggerId = 1;
6367 status_t res;
6368
Emilian Peevaebbe412018-01-15 13:53:24 +00006369 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006370
6371 // If AF trigger is active, insert a dummy AF trigger ID if none already
6372 // exists
6373 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6374 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6375 if (afTrigger.count > 0 &&
6376 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6377 afId.count == 0) {
6378 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6379 if (res != OK) return res;
6380 }
6381
6382 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6383 // if none already exists
6384 camera_metadata_entry pcTrigger =
6385 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6386 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6387 if (pcTrigger.count > 0 &&
6388 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6389 pcId.count == 0) {
6390 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6391 &dummyTriggerId, 1);
6392 if (res != OK) return res;
6393 }
6394
6395 return OK;
6396}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006397
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006398/**
6399 * PreparerThread inner class methods
6400 */
6401
6402Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006403 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006404 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006405}
6406
6407Camera3Device::PreparerThread::~PreparerThread() {
6408 Thread::requestExitAndWait();
6409 if (mCurrentStream != nullptr) {
6410 mCurrentStream->cancelPrepare();
6411 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6412 mCurrentStream.clear();
6413 }
6414 clear();
6415}
6416
Ruben Brunkc78ac262015-08-13 17:58:46 -07006417status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006418 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006419 status_t res;
6420
6421 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006422 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006423
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006424 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006425 if (res == OK) {
6426 // No preparation needed, fire listener right off
6427 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006428 if (listener != NULL) {
6429 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006430 }
6431 return OK;
6432 } else if (res != NOT_ENOUGH_DATA) {
6433 return res;
6434 }
6435
6436 // Need to prepare, start up thread if necessary
6437 if (!mActive) {
6438 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6439 // isn't running
6440 Thread::requestExitAndWait();
6441 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6442 if (res != OK) {
6443 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006444 if (listener != NULL) {
6445 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006446 }
6447 return res;
6448 }
6449 mCancelNow = false;
6450 mActive = true;
6451 ALOGV("%s: Preparer stream started", __FUNCTION__);
6452 }
6453
6454 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006455 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006456 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6457
6458 return OK;
6459}
6460
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006461void Camera3Device::PreparerThread::pause() {
6462 ATRACE_CALL();
6463
6464 Mutex::Autolock l(mLock);
6465
6466 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6467 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6468 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6469 int currentMaxCount = mCurrentMaxCount;
6470 mPendingStreams.clear();
6471 mCancelNow = true;
6472 while (mActive) {
6473 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6474 if (res == TIMED_OUT) {
6475 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6476 return;
6477 } else if (res != OK) {
6478 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6479 return;
6480 }
6481 }
6482
6483 //Check whether the prepare thread was able to complete the current
6484 //stream. In case work is still pending emplace it along with the rest
6485 //of the streams in the pending list.
6486 if (currentStream != nullptr) {
6487 if (!mCurrentPrepareComplete) {
6488 pendingStreams.emplace(currentMaxCount, currentStream);
6489 }
6490 }
6491
6492 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6493 for (const auto& it : mPendingStreams) {
6494 it.second->cancelPrepare();
6495 }
6496}
6497
6498status_t Camera3Device::PreparerThread::resume() {
6499 ATRACE_CALL();
6500 status_t res;
6501
6502 Mutex::Autolock l(mLock);
6503 sp<NotificationListener> listener = mListener.promote();
6504
6505 if (mActive) {
6506 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6507 return NO_INIT;
6508 }
6509
6510 auto it = mPendingStreams.begin();
6511 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006512 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006513 if (res == OK) {
6514 if (listener != NULL) {
6515 listener->notifyPrepared(it->second->getId());
6516 }
6517 it = mPendingStreams.erase(it);
6518 } else if (res != NOT_ENOUGH_DATA) {
6519 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6520 res, strerror(-res));
6521 it = mPendingStreams.erase(it);
6522 } else {
6523 it++;
6524 }
6525 }
6526
6527 if (mPendingStreams.empty()) {
6528 return OK;
6529 }
6530
6531 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6532 if (res != OK) {
6533 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6534 __FUNCTION__, res, strerror(-res));
6535 return res;
6536 }
6537 mCancelNow = false;
6538 mActive = true;
6539 ALOGV("%s: Preparer stream started", __FUNCTION__);
6540
6541 return OK;
6542}
6543
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006544status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006545 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006546 Mutex::Autolock l(mLock);
6547
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006548 for (const auto& it : mPendingStreams) {
6549 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006550 }
6551 mPendingStreams.clear();
6552 mCancelNow = true;
6553
6554 return OK;
6555}
6556
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006557void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006558 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006559 Mutex::Autolock l(mLock);
6560 mListener = listener;
6561}
6562
6563bool Camera3Device::PreparerThread::threadLoop() {
6564 status_t res;
6565 {
6566 Mutex::Autolock l(mLock);
6567 if (mCurrentStream == nullptr) {
6568 // End thread if done with work
6569 if (mPendingStreams.empty()) {
6570 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6571 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6572 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6573 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006574 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006575 return false;
6576 }
6577
6578 // Get next stream to prepare
6579 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006580 mCurrentStream = it->second;
6581 mCurrentMaxCount = it->first;
6582 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006583 mPendingStreams.erase(it);
6584 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6585 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6586 } else if (mCancelNow) {
6587 mCurrentStream->cancelPrepare();
6588 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6589 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6590 mCurrentStream.clear();
6591 mCancelNow = false;
6592 return true;
6593 }
6594 }
6595
6596 res = mCurrentStream->prepareNextBuffer();
6597 if (res == NOT_ENOUGH_DATA) return true;
6598 if (res != OK) {
6599 // Something bad happened; try to recover by cancelling prepare and
6600 // signalling listener anyway
6601 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6602 mCurrentStream->getId(), res, strerror(-res));
6603 mCurrentStream->cancelPrepare();
6604 }
6605
6606 // This stream has finished, notify listener
6607 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006608 sp<NotificationListener> listener = mListener.promote();
6609 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006610 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6611 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006612 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006613 }
6614
6615 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6616 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006617 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006618
6619 return true;
6620}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006621
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006622status_t Camera3Device::RequestBufferStateMachine::initialize(
6623 sp<camera3::StatusTracker> statusTracker) {
6624 if (statusTracker == nullptr) {
6625 ALOGE("%s: statusTracker is null", __FUNCTION__);
6626 return BAD_VALUE;
6627 }
6628
6629 std::lock_guard<std::mutex> lock(mLock);
6630 mStatusTracker = statusTracker;
6631 mRequestBufferStatusId = statusTracker->addComponent();
6632 return OK;
6633}
6634
6635bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6636 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006637 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006638 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006639 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006640 return true;
6641 }
6642 return false;
6643}
6644
6645void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6646 std::lock_guard<std::mutex> lock(mLock);
6647 if (!mRequestBufferOngoing) {
6648 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6649 return;
6650 }
6651 mRequestBufferOngoing = false;
6652 if (mStatus == RB_STATUS_PENDING_STOP) {
6653 checkSwitchToStopLocked();
6654 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006655 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006656}
6657
6658void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6659 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006660 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006661 return;
6662}
6663
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006664void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006665 std::lock_guard<std::mutex> lock(mLock);
6666 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006667 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6668 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006669 mInflightMapEmpty = false;
6670 if (mStatus == RB_STATUS_STOPPED) {
6671 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006672 }
6673 return;
6674}
6675
6676void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6677 std::lock_guard<std::mutex> lock(mLock);
6678 mRequestThreadPaused = true;
6679 if (mStatus == RB_STATUS_PENDING_STOP) {
6680 checkSwitchToStopLocked();
6681 }
6682 return;
6683}
6684
6685void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6686 std::lock_guard<std::mutex> lock(mLock);
6687 mInflightMapEmpty = true;
6688 if (mStatus == RB_STATUS_PENDING_STOP) {
6689 checkSwitchToStopLocked();
6690 }
6691 return;
6692}
6693
6694void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6695 std::lock_guard<std::mutex> lock(mLock);
6696 if (!checkSwitchToStopLocked()) {
6697 mStatus = RB_STATUS_PENDING_STOP;
6698 }
6699 return;
6700}
6701
6702void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6703 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6704 if (statusTracker != nullptr) {
6705 if (active) {
6706 statusTracker->markComponentActive(mRequestBufferStatusId);
6707 } else {
6708 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6709 }
6710 }
6711}
6712
6713bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6714 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6715 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006716 return true;
6717 }
6718 return false;
6719}
6720
Shuzhen Wang268a1362018-10-16 16:32:59 -07006721status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6722 CameraMetadata& resultMetadata) {
6723 status_t res = OK;
6724 if (!mNeedFixupMonochromeTags) {
6725 return res;
6726 }
6727
6728 // Remove tags that are not applicable to monochrome camera.
6729 int32_t tagsToRemove[] = {
6730 ANDROID_SENSOR_GREEN_SPLIT,
6731 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6732 ANDROID_COLOR_CORRECTION_MODE,
6733 ANDROID_COLOR_CORRECTION_TRANSFORM,
6734 ANDROID_COLOR_CORRECTION_GAINS,
6735 };
6736 for (auto tag : tagsToRemove) {
6737 res = resultMetadata.erase(tag);
6738 if (res != OK) {
6739 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6740 return res;
6741 }
6742 }
6743
6744 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6745 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6746 for (size_t i = 1; i < blEntry.count; i++) {
6747 blEntry.data.f[i] = blEntry.data.f[0];
6748 }
6749
6750 // ANDROID_SENSOR_NOISE_PROFILE
6751 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6752 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6753 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6754 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6755 if (res != OK) {
6756 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6757 __FUNCTION__, strerror(-res), res);
6758 return res;
6759 }
6760 }
6761
6762 // ANDROID_STATISTICS_LENS_SHADING_MAP
6763 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6764 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6765 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6766 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6767 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6768 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6769 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6770 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6771 }
6772 }
6773
6774 // ANDROID_TONEMAP_CURVE_BLUE
6775 // ANDROID_TONEMAP_CURVE_GREEN
6776 // ANDROID_TONEMAP_CURVE_RED
6777 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6778 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6779 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6780 if (tcbEntry.count > 0
6781 && tcbEntry.count == tcgEntry.count
6782 && tcbEntry.count == tcrEntry.count) {
6783 for (size_t i = 0; i < tcbEntry.count; i++) {
6784 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6785 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6786 }
6787 }
6788
6789 return res;
6790}
6791
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006792}; // namespace android