blob: 4e5c8d624171d1b01df85e8642c14da99fa8dd26 [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"
Yin-Chia Yehb978c382019-10-30 00:22:37 -070061#include "device3/Camera3OfflineSession.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080064
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080065#include <tuple>
66
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080068using namespace android::hardware::camera;
69using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080070
71namespace android {
72
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080073Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080074 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080075 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070076 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070077 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070078 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070079 mUsePartialResult(false),
80 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080081 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070082 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070083 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070084 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070085 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070086 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070087 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000088 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010089 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070090 mLastTemplateId(-1),
91 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080092{
93 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080094 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080095}
96
97Camera3Device::~Camera3Device()
98{
99 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800100 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700101 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102}
103
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800104const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800105 return mId;
106}
107
Emilian Peevbd8c5032018-02-14 23:05:40 +0000108status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800109 ATRACE_CALL();
110 Mutex::Autolock il(mInterfaceLock);
111 Mutex::Autolock l(mLock);
112
113 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
114 if (mStatus != STATUS_UNINITIALIZED) {
115 CLOGE("Already initialized!");
116 return INVALID_OPERATION;
117 }
118 if (manager == nullptr) return INVALID_OPERATION;
119
120 sp<ICameraDeviceSession> session;
121 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800122 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 /*out*/ &session);
124 ATRACE_END();
125 if (res != OK) {
126 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
127 return res;
128 }
129
Steven Moreland5ff9c912017-03-09 23:13:00 -0800130 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800131 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700132 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800133 session->close();
134 return res;
135 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800136
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700137 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700138 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700139 if (isLogical) {
140 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700141 res = manager->getCameraCharacteristics(
142 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700143 if (res != OK) {
144 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
145 physicalId.c_str(), strerror(-res), res);
146 session->close();
147 return res;
148 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700149
150 if (DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId])) {
151 mDistortionMappers[physicalId].setupStaticInfo(mPhysicalDeviceInfoMap[physicalId]);
152 if (res != OK) {
153 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
154 "correction", physicalId.c_str());
155 session->close();
156 return res;
157 }
158 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700159 }
160 }
161
Yifan Hongf79b5542017-04-11 14:44:25 -0700162 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700163 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
164 [&queue](const auto& descriptor) {
165 queue = std::make_shared<RequestMetadataQueue>(descriptor);
166 if (!queue->isValid() || queue->availableToWrite() <= 0) {
167 ALOGE("HAL returns empty request metadata fmq, not use it");
168 queue = nullptr;
169 // don't use the queue onwards.
170 }
171 });
172 if (!requestQueueRet.isOk()) {
173 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
174 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700175 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700176 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700177
178 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700179 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700180 [&resQueue](const auto& descriptor) {
181 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
182 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700183 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700184 resQueue = nullptr;
185 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700186 }
187 });
188 if (!resultQueueRet.isOk()) {
189 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
190 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700191 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700192 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700193 IF_ALOGV() {
194 session->interfaceChain([](
195 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
196 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800197 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700198 ALOGV(" %s", iface.c_str());
199 }
200 });
201 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700202
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800203 camera_metadata_entry bufMgrMode =
204 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
205 if (bufMgrMode.count > 0) {
206 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
207 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
208 }
209
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700210 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
211 for (size_t i = 0; i < capabilities.count; i++) {
212 uint8_t capability = capabilities.data.u8[i];
213 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
214 mSupportOfflineProcessing = true;
215 }
216 }
217
218 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000219 std::string providerType;
220 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000221 mTagMonitor.initialize(mVendorTagId);
222 if (!monitorTags.isEmpty()) {
223 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
224 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800225
Shuzhen Wang268a1362018-10-16 16:32:59 -0700226 // Metadata tags needs fixup for monochrome camera device version less
227 // than 3.5.
228 hardware::hidl_version maxVersion{0,0};
229 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
230 if (res != OK) {
231 ALOGE("%s: Error in getting camera device version id: %s (%d)",
232 __FUNCTION__, strerror(-res), res);
233 return res;
234 }
235 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
236 maxVersion.get_major(), maxVersion.get_minor());
237
238 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700239 for (size_t i = 0; i < capabilities.count; i++) {
240 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700241 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
242 isMonochrome = true;
243 }
244 }
245 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
246
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800247 return initializeCommonLocked();
248}
249
250status_t Camera3Device::initializeCommonLocked() {
251
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700252 /** Start up status tracker thread */
253 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800254 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700255 if (res != OK) {
256 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
257 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800258 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700259 mStatusTracker.clear();
260 return res;
261 }
262
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700263 /** Register in-flight map to the status tracker */
264 mInFlightStatusId = mStatusTracker->addComponent();
265
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700266 if (mUseHalBufManager) {
267 res = mRequestBufferSM.initialize(mStatusTracker);
268 if (res != OK) {
269 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
270 strerror(-res), res);
271 mInterface->close();
272 mStatusTracker.clear();
273 return res;
274 }
275 }
276
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800277 /** Create buffer manager */
278 mBufferManager = new Camera3BufferManager();
279
280 Vector<int32_t> sessionParamKeys;
281 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
282 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
283 if (sessionKeysEntry.count > 0) {
284 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
285 }
286
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700287 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700288 mRequestThread = new RequestThread(
289 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800290 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800291 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700292 SET_ERR_L("Unable to start request queue thread: %s (%d)",
293 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800294 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800295 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800296 return res;
297 }
298
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700299 mPreparerThread = new PreparerThread();
300
Ruben Brunk183f0562015-08-12 12:55:02 -0700301 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800302 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700303 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700304 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700305 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800306
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800307 // Measure the clock domain offset between camera and video/hw_composer
308 camera_metadata_entry timestampSource =
309 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
310 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
311 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
312 mTimestampOffset = getMonoToBoottimeOffset();
313 }
314
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700315 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100316 camera_metadata_entry partialResultsCount =
317 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
318 if (partialResultsCount.count > 0) {
319 mNumPartialResults = partialResultsCount.data.i32[0];
320 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700321 }
322
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700323 camera_metadata_entry configs =
324 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
325 for (uint32_t i = 0; i < configs.count; i += 4) {
326 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
327 configs.data.i32[i + 3] ==
328 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
329 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
330 configs.data.i32[i + 2]));
331 }
332 }
333
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700334 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700335 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700336 if (res != OK) {
337 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
338 return res;
339 }
340 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800341 return OK;
342}
343
344status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700345 return disconnectImpl();
346}
347
348status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800349 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700350 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800351
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700352 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800353
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700354 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700355 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700356 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700357 {
358 Mutex::Autolock l(mLock);
359 if (mStatus == STATUS_UNINITIALIZED) return res;
360
361 if (mStatus == STATUS_ACTIVE ||
362 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
363 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700364 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700365 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700366 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700367 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700368 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700369 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700370 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
371 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700372 // Continue to close device even in case of error
373 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700374 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800375 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800376
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700377 if (mStatus == STATUS_ERROR) {
378 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700379 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700380
381 if (mStatusTracker != NULL) {
382 mStatusTracker->requestExit();
383 }
384
385 if (mRequestThread != NULL) {
386 mRequestThread->requestExit();
387 }
388
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700389 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
390 for (size_t i = 0; i < mOutputStreams.size(); i++) {
391 streams.push_back(mOutputStreams[i]);
392 }
393 if (mInputStream != nullptr) {
394 streams.push_back(mInputStream);
395 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700396 }
397
398 // Joining done without holding mLock, otherwise deadlocks may ensue
399 // as the threads try to access parent state
400 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
401 // HAL may be in a bad state, so waiting for request thread
402 // (which may be stuck in the HAL processCaptureRequest call)
403 // could be dangerous.
404 mRequestThread->join();
405 }
406
407 if (mStatusTracker != NULL) {
408 mStatusTracker->join();
409 }
410
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800411 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700412 {
413 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800414 mRequestThread.clear();
Emilian Peev2843c362018-09-26 08:49:40 +0100415 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700416 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800417 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700418 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800419
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700420 // Call close without internal mutex held, as the HAL close may need to
421 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800422 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700423
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700424 flushInflightRequests();
425
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700426 {
427 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800428 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700429 mOutputStreams.clear();
430 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700431 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700432 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700433 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700434 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800435
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700436 for (auto& weakStream : streams) {
437 sp<Camera3StreamInterface> stream = weakStream.promote();
438 if (stream != nullptr) {
439 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
440 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
441 }
442 }
443
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700444 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700445 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800446}
447
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700448// For dumping/debugging only -
449// try to acquire a lock a few times, eventually give up to proceed with
450// debug/dump operations
451bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
452 bool gotLock = false;
453 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
454 if (lock.tryLock() == NO_ERROR) {
455 gotLock = true;
456 break;
457 } else {
458 usleep(kDumpSleepDuration);
459 }
460 }
461 return gotLock;
462}
463
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700464Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
465 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100466 const int STREAM_CONFIGURATION_SIZE = 4;
467 const int STREAM_FORMAT_OFFSET = 0;
468 const int STREAM_WIDTH_OFFSET = 1;
469 const int STREAM_HEIGHT_OFFSET = 2;
470 const int STREAM_IS_INPUT_OFFSET = 3;
471 camera_metadata_ro_entry_t availableStreamConfigs =
472 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
473 if (availableStreamConfigs.count == 0 ||
474 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
475 return Size(0, 0);
476 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700477
Emilian Peev08dd2452017-04-06 16:55:14 +0100478 // Get max jpeg size (area-wise).
479 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
480 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
481 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
482 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
483 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
484 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
485 && format == HAL_PIXEL_FORMAT_BLOB &&
486 (width * height > maxJpegWidth * maxJpegHeight)) {
487 maxJpegWidth = width;
488 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700489 }
490 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100491
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700492 return Size(maxJpegWidth, maxJpegHeight);
493}
494
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800495nsecs_t Camera3Device::getMonoToBoottimeOffset() {
496 // try three times to get the clock offset, choose the one
497 // with the minimum gap in measurements.
498 const int tries = 3;
499 nsecs_t bestGap, measured;
500 for (int i = 0; i < tries; ++i) {
501 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
502 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
503 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
504 const nsecs_t gap = tmono2 - tmono;
505 if (i == 0 || gap < bestGap) {
506 bestGap = gap;
507 measured = tbase - ((tmono + tmono2) >> 1);
508 }
509 }
510 return measured;
511}
512
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800513hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
514 int frameworkFormat) {
515 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
516}
517
518DataspaceFlags Camera3Device::mapToHidlDataspace(
519 android_dataspace dataSpace) {
520 return dataSpace;
521}
522
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700523BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100524 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700525 return usage;
526}
527
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800528StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
529 switch (rotation) {
530 case CAMERA3_STREAM_ROTATION_0:
531 return StreamRotation::ROTATION_0;
532 case CAMERA3_STREAM_ROTATION_90:
533 return StreamRotation::ROTATION_90;
534 case CAMERA3_STREAM_ROTATION_180:
535 return StreamRotation::ROTATION_180;
536 case CAMERA3_STREAM_ROTATION_270:
537 return StreamRotation::ROTATION_270;
538 }
539 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
540 return StreamRotation::ROTATION_0;
541}
542
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800543status_t Camera3Device::mapToStreamConfigurationMode(
544 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
545 if (mode == nullptr) return BAD_VALUE;
546 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
547 switch(operationMode) {
548 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
549 *mode = StreamConfigurationMode::NORMAL_MODE;
550 break;
551 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
552 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
553 break;
554 default:
555 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
556 return BAD_VALUE;
557 }
558 } else {
559 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800560 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800561 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800562}
563
564camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
565 switch (status) {
566 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
567 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
568 }
569 return CAMERA3_BUFFER_STATUS_ERROR;
570}
571
572int Camera3Device::mapToFrameworkFormat(
573 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
574 return static_cast<uint32_t>(pixelFormat);
575}
576
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700577android_dataspace Camera3Device::mapToFrameworkDataspace(
578 DataspaceFlags dataSpace) {
579 return static_cast<android_dataspace>(dataSpace);
580}
581
Emilian Peev050f5dc2017-05-18 14:43:56 +0100582uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700583 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700584 return usage;
585}
586
Emilian Peev050f5dc2017-05-18 14:43:56 +0100587uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700588 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700589 return usage;
590}
591
Zhijun Hef7da0962014-04-24 13:27:56 -0700592ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700593 // Get max jpeg size (area-wise).
594 Size maxJpegResolution = getMaxJpegResolution();
595 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800596 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
597 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700598 return BAD_VALUE;
599 }
600
Zhijun Hef7da0962014-04-24 13:27:56 -0700601 // Get max jpeg buffer size
602 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700603 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
604 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800605 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
606 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700607 return BAD_VALUE;
608 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700609 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800610 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700611
612 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700613 float scaleFactor = ((float) (width * height)) /
614 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800615 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
616 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700617 if (jpegBufferSize > maxJpegBufferSize) {
618 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700619 }
620
621 return jpegBufferSize;
622}
623
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700624ssize_t Camera3Device::getPointCloudBufferSize() const {
625 const int FLOATS_PER_POINT=4;
626 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
627 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800628 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
629 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700630 return BAD_VALUE;
631 }
632 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
633 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
634 return maxBytesForPointCloud;
635}
636
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800637ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800638 const int PER_CONFIGURATION_SIZE = 3;
639 const int WIDTH_OFFSET = 0;
640 const int HEIGHT_OFFSET = 1;
641 const int SIZE_OFFSET = 2;
642 camera_metadata_ro_entry rawOpaqueSizes =
643 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800644 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800645 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800646 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
647 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800648 return BAD_VALUE;
649 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700650
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800651 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
652 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
653 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
654 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
655 }
656 }
657
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800658 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
659 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800660 return BAD_VALUE;
661}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700662
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800663status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
664 ATRACE_CALL();
665 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700666
667 // Try to lock, but continue in case of failure (to avoid blocking in
668 // deadlocks)
669 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
670 bool gotLock = tryLockSpinRightRound(mLock);
671
672 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800673 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
674 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700675 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800676 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
677 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700678
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800679 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700680
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800681 String16 templatesOption("-t");
682 int n = args.size();
683 for (int i = 0; i < n; i++) {
684 if (args[i] == templatesOption) {
685 dumpTemplates = true;
686 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000687 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700688 if (i + 1 < n) {
689 String8 monitorTags = String8(args[i + 1]);
690 if (monitorTags == "off") {
691 mTagMonitor.disableMonitoring();
692 } else {
693 mTagMonitor.parseTagsToMonitor(monitorTags);
694 }
695 } else {
696 mTagMonitor.disableMonitoring();
697 }
698 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800699 }
700
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800701 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800702
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800703 const char *status =
704 mStatus == STATUS_ERROR ? "ERROR" :
705 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700706 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
707 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800708 mStatus == STATUS_ACTIVE ? "ACTIVE" :
709 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700710
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800711 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700712 if (mStatus == STATUS_ERROR) {
713 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
714 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800715 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800716 const char *mode =
717 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
718 mOperatingMode == static_cast<int>(
719 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
720 "CUSTOM";
721 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800722
723 if (mInputStream != NULL) {
724 write(fd, lines.string(), lines.size());
725 mInputStream->dump(fd, args);
726 } else {
727 lines.appendFormat(" No input stream.\n");
728 write(fd, lines.string(), lines.size());
729 }
730 for (size_t i = 0; i < mOutputStreams.size(); i++) {
731 mOutputStreams[i]->dump(fd,args);
732 }
733
Zhijun He431503c2016-03-07 17:30:16 -0800734 if (mBufferManager != NULL) {
735 lines = String8(" Camera3 Buffer Manager:\n");
736 write(fd, lines.string(), lines.size());
737 mBufferManager->dump(fd, args);
738 }
Zhijun He125684a2015-12-26 15:07:30 -0800739
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700740 lines = String8(" In-flight requests:\n");
741 if (mInFlightMap.size() == 0) {
742 lines.append(" None\n");
743 } else {
744 for (size_t i = 0; i < mInFlightMap.size(); i++) {
745 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700746 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700747 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800748 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700749 r.numBuffersLeft);
750 }
751 }
752 write(fd, lines.string(), lines.size());
753
Shuzhen Wang686f6442017-06-20 16:16:04 -0700754 if (mRequestThread != NULL) {
755 mRequestThread->dumpCaptureRequestLatency(fd,
756 " ProcessCaptureRequest latency histogram:");
757 }
758
Igor Murashkin1e479c02013-09-06 16:55:14 -0700759 {
760 lines = String8(" Last request sent:\n");
761 write(fd, lines.string(), lines.size());
762
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700763 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700764 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
765 }
766
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800767 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800768 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800769 "TEMPLATE_PREVIEW",
770 "TEMPLATE_STILL_CAPTURE",
771 "TEMPLATE_VIDEO_RECORD",
772 "TEMPLATE_VIDEO_SNAPSHOT",
773 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800774 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800775 };
776
777 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800778 camera_metadata_t *templateRequest = nullptr;
779 mInterface->constructDefaultRequestSettings(
780 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800781 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800782 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800783 lines.append(" Not supported\n");
784 write(fd, lines.string(), lines.size());
785 } else {
786 write(fd, lines.string(), lines.size());
787 dump_indented_camera_metadata(templateRequest,
788 fd, /*verbosity*/2, /*indentation*/8);
789 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800790 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800791 }
792 }
793
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700794 mTagMonitor.dumpMonitoredMetadata(fd);
795
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800796 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800797 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800798 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800799 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800800 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800801
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700802 if (gotLock) mLock.unlock();
803 if (gotInterfaceLock) mInterfaceLock.unlock();
804
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800805 return OK;
806}
807
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700808const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800809 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800810 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
811 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700812 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800813 mStatus == STATUS_ERROR ?
814 "when in error state" : "before init");
815 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700816 if (physicalId.isEmpty()) {
817 return mDeviceInfo;
818 } else {
819 std::string id(physicalId.c_str());
820 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
821 return mPhysicalDeviceInfoMap.at(id);
822 } else {
823 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
824 return mDeviceInfo;
825 }
826 }
827}
828
829const CameraMetadata& Camera3Device::info() const {
830 String8 emptyId;
831 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800832}
833
Jianing Wei90e59c92014-03-12 18:29:36 -0700834status_t Camera3Device::checkStatusOkToCaptureLocked() {
835 switch (mStatus) {
836 case STATUS_ERROR:
837 CLOGE("Device has encountered a serious error");
838 return INVALID_OPERATION;
839 case STATUS_UNINITIALIZED:
840 CLOGE("Device not initialized");
841 return INVALID_OPERATION;
842 case STATUS_UNCONFIGURED:
843 case STATUS_CONFIGURED:
844 case STATUS_ACTIVE:
845 // OK
846 break;
847 default:
848 SET_ERR_L("Unexpected status: %d", mStatus);
849 return INVALID_OPERATION;
850 }
851 return OK;
852}
853
854status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000855 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700856 const std::list<const SurfaceMap> &surfaceMaps,
857 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700858 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700859 if (requestList == NULL) {
860 CLOGE("requestList cannot be NULL.");
861 return BAD_VALUE;
862 }
863
Jianing Weicb0652e2014-03-12 18:29:36 -0700864 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000865 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700866 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
867 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
868 ++metadataIt, ++surfaceMapIt) {
869 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700870 if (newRequest == 0) {
871 CLOGE("Can't create capture request");
872 return BAD_VALUE;
873 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700874
Shuzhen Wang9d066012016-09-30 11:30:20 -0700875 newRequest->mRepeating = repeating;
876
Jianing Weicb0652e2014-03-12 18:29:36 -0700877 // Setup burst Id and request Id
878 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000879 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
880 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700881 CLOGE("RequestID entry exists; but must not be empty in metadata");
882 return BAD_VALUE;
883 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000884 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
885 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700886 } else {
887 CLOGE("RequestID does not exist in metadata");
888 return BAD_VALUE;
889 }
890
Jianing Wei90e59c92014-03-12 18:29:36 -0700891 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700892
893 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700894 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700895 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
896 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
897 return BAD_VALUE;
898 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700899
900 // Setup batch size if this is a high speed video recording request.
901 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
902 auto firstRequest = requestList->begin();
903 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
904 if (outputStream->isVideoStream()) {
905 (*firstRequest)->mBatchSize = requestList->size();
906 break;
907 }
908 }
909 }
910
Jianing Wei90e59c92014-03-12 18:29:36 -0700911 return OK;
912}
913
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800914status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800915 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800916
Emilian Peevaebbe412018-01-15 13:53:24 +0000917 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700918 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000919 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700920
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800921 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700922}
923
Emilian Peevaebbe412018-01-15 13:53:24 +0000924void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700925 std::list<const SurfaceMap>& surfaceMaps,
926 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000927 PhysicalCameraSettingsList requestList;
928 requestList.push_back({std::string(getId().string()), request});
929 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700930
931 SurfaceMap surfaceMap;
932 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
933 // With no surface list passed in, stream and surface will have 1-to-1
934 // mapping. So the surface index is 0 for each stream in the surfaceMap.
935 for (size_t i = 0; i < streams.count; i++) {
936 surfaceMap[streams.data.i32[i]].push_back(0);
937 }
938 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800939}
940
Jianing Wei90e59c92014-03-12 18:29:36 -0700941status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000942 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700943 const std::list<const SurfaceMap> &surfaceMaps,
944 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700945 /*out*/
946 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700947 ATRACE_CALL();
948 Mutex::Autolock il(mInterfaceLock);
949 Mutex::Autolock l(mLock);
950
951 status_t res = checkStatusOkToCaptureLocked();
952 if (res != OK) {
953 // error logged by previous call
954 return res;
955 }
956
957 RequestList requestList;
958
Shuzhen Wang0129d522016-10-30 22:43:41 -0700959 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
960 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700961 if (res != OK) {
962 // error logged by previous call
963 return res;
964 }
965
966 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700967 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700968 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700969 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700970 }
971
972 if (res == OK) {
973 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
974 if (res != OK) {
975 SET_ERR_L("Can't transition to active in %f seconds!",
976 kActiveTimeout/1e9);
977 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800978 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700979 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700980 } else {
981 CLOGE("Cannot queue request. Impossible.");
982 return BAD_VALUE;
983 }
984
985 return res;
986}
987
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700988hardware::Return<void> Camera3Device::requestStreamBuffers(
989 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
990 requestStreamBuffers_cb _hidl_cb) {
991 using hardware::camera::device::V3_5::BufferRequestStatus;
992 using hardware::camera::device::V3_5::StreamBufferRet;
993 using hardware::camera::device::V3_5::StreamBufferRequestError;
994
995 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
996
997 hardware::hidl_vec<StreamBufferRet> bufRets;
998 if (!mUseHalBufManager) {
999 ALOGE("%s: Camera %s does not support HAL buffer management",
1000 __FUNCTION__, mId.string());
1001 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1002 return hardware::Void();
1003 }
1004
1005 SortedVector<int32_t> streamIds;
1006 ssize_t sz = streamIds.setCapacity(bufReqs.size());
1007 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
1008 ALOGE("%s: failed to allocate memory for %zu buffer requests",
1009 __FUNCTION__, bufReqs.size());
1010 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1011 return hardware::Void();
1012 }
1013
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001014 if (bufReqs.size() > mOutputStreams.size()) {
1015 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
1016 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
1017 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1018 return hardware::Void();
1019 }
1020
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001021 // Check for repeated streamId
1022 for (const auto& bufReq : bufReqs) {
1023 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
1024 ALOGE("%s: Stream %d appear multiple times in buffer requests",
1025 __FUNCTION__, bufReq.streamId);
1026 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1027 return hardware::Void();
1028 }
1029 streamIds.add(bufReq.streamId);
1030 }
1031
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001032 if (!mRequestBufferSM.startRequestBuffer()) {
1033 ALOGE("%s: request buffer disallowed while camera service is configuring",
1034 __FUNCTION__);
1035 _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001036 return hardware::Void();
1037 }
1038
1039 bufRets.resize(bufReqs.size());
1040
1041 bool allReqsSucceeds = true;
1042 bool oneReqSucceeds = false;
1043 for (size_t i = 0; i < bufReqs.size(); i++) {
1044 const auto& bufReq = bufReqs[i];
1045 auto& bufRet = bufRets[i];
1046 int32_t streamId = bufReq.streamId;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001047 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
1048 if (outputStream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001049 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
1050 hardware::hidl_vec<StreamBufferRet> emptyBufRets;
1051 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001052 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001053 return hardware::Void();
1054 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001055
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001056 if (outputStream->isAbandoned()) {
1057 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1058 allReqsSucceeds = false;
1059 continue;
1060 }
1061
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001062 bufRet.streamId = streamId;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001063 size_t handOutBufferCount = outputStream->getOutstandingBuffersCount();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001064 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001065 size_t totalHandout = handOutBufferCount + numBuffersRequested;
1066 uint32_t maxBuffers = outputStream->asHalStream()->max_buffers;
1067 if (totalHandout > maxBuffers) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001068 // Not able to allocate enough buffer. Exit early for this stream
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001069 ALOGE("%s: request too much buffers for stream %d: at HAL: %zu + requesting: %d"
1070 " > max: %d", __FUNCTION__, streamId, handOutBufferCount,
1071 numBuffersRequested, maxBuffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001072 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1073 allReqsSucceeds = false;
1074 continue;
1075 }
1076
1077 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1078 bool currentReqSucceeds = true;
1079 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1080 size_t numAllocatedBuffers = 0;
1081 size_t numPushedInflightBuffers = 0;
1082 for (size_t b = 0; b < numBuffersRequested; b++) {
1083 camera3_stream_buffer_t& sb = streamBuffers[b];
1084 // Since this method can run concurrently with request thread
1085 // We need to update the wait duration everytime we call getbuffer
1086 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1087 status_t res = outputStream->getBuffer(&sb, waitDuration);
1088 if (res != OK) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001089 if (res == NO_INIT || res == DEAD_OBJECT) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001090 ALOGV("%s: Can't get output buffer for stream %d: %s (%d)",
1091 __FUNCTION__, streamId, strerror(-res), res);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001092 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001093 } else {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001094 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1095 __FUNCTION__, streamId, strerror(-res), res);
1096 if (res == TIMED_OUT || res == NO_MEMORY) {
1097 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1098 } else {
1099 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1100 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001101 }
1102 currentReqSucceeds = false;
1103 break;
1104 }
1105 numAllocatedBuffers++;
1106
1107 buffer_handle_t *buffer = sb.buffer;
1108 auto pair = mInterface->getBufferId(*buffer, streamId);
1109 bool isNewBuffer = pair.first;
1110 uint64_t bufferId = pair.second;
1111 StreamBuffer& hBuf = tmpRetBuffers[b];
1112
1113 hBuf.streamId = streamId;
1114 hBuf.bufferId = bufferId;
1115 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1116 hBuf.status = BufferStatus::OK;
1117 hBuf.releaseFence = nullptr;
1118
1119 native_handle_t *acquireFence = nullptr;
1120 if (sb.acquire_fence != -1) {
1121 acquireFence = native_handle_create(1,0);
1122 acquireFence->data[0] = sb.acquire_fence;
1123 }
1124 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1125 hBuf.releaseFence = nullptr;
1126
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08001127 res = mInterface->pushInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001128 if (res != OK) {
1129 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1130 __FUNCTION__, streamId, strerror(-res), res);
1131 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1132 currentReqSucceeds = false;
1133 break;
1134 }
1135 numPushedInflightBuffers++;
1136 }
1137 if (currentReqSucceeds) {
1138 bufRet.val.buffers(std::move(tmpRetBuffers));
1139 oneReqSucceeds = true;
1140 } else {
1141 allReqsSucceeds = false;
1142 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1143 StreamBuffer& hBuf = tmpRetBuffers[b];
1144 buffer_handle_t* buffer;
1145 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1146 if (res != OK) {
1147 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1148 __FUNCTION__, streamId, strerror(-res), res);
1149 }
1150 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001151 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1152 camera3_stream_buffer_t& sb = streamBuffers[b];
1153 sb.acquire_fence = -1;
1154 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1155 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001156 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1157 }
1158 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001159
1160 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1161 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1162 BufferRequestStatus::FAILED_UNKNOWN,
1163 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001164 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001165 return hardware::Void();
1166}
1167
1168hardware::Return<void> Camera3Device::returnStreamBuffers(
1169 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1170 if (!mUseHalBufManager) {
1171 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1172 __FUNCTION__, mId.string());
1173 return hardware::Void();
1174 }
1175
1176 for (const auto& buf : buffers) {
1177 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1178 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1179 continue;
1180 }
1181
1182 buffer_handle_t* buffer;
1183 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1184
1185 if (res != OK) {
1186 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1187 __FUNCTION__, buf.bufferId, buf.streamId);
1188 continue;
1189 }
1190
1191 camera3_stream_buffer_t streamBuffer;
1192 streamBuffer.buffer = buffer;
1193 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1194 streamBuffer.acquire_fence = -1;
1195 streamBuffer.release_fence = -1;
1196
1197 if (buf.releaseFence == nullptr) {
1198 streamBuffer.release_fence = -1;
1199 } else if (buf.releaseFence->numFds == 1) {
1200 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1201 } else {
1202 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1203 __FUNCTION__, buf.releaseFence->numFds);
1204 continue;
1205 }
1206
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001207 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1208 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001209 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1210 continue;
1211 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001212 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001213 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1214 }
1215 return hardware::Void();
1216}
1217
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001218hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001219 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001220 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001221 // Ideally we should grab mLock, but that can lead to deadlock, and
1222 // it's not super important to get up to date value of mStatus for this
1223 // warning print, hence skipping the lock here
1224 if (mStatus == STATUS_ERROR) {
1225 // Per API contract, HAL should act as closed after device error
1226 // But mStatus can be set to error by framework as well, so just log
1227 // a warning here.
1228 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001229 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001230
1231 if (mProcessCaptureResultLock.tryLock() != OK) {
1232 // This should never happen; it indicates a wrong client implementation
1233 // that doesn't follow the contract. But, we can be tolerant here.
1234 ALOGE("%s: callback overlapped! waiting 1s...",
1235 __FUNCTION__);
1236 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1237 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1238 __FUNCTION__);
1239 // really don't know what to do, so bail out.
1240 return hardware::Void();
1241 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001242 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001243 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001244 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001245 }
1246 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001247 return hardware::Void();
1248}
1249
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001250// Only one processCaptureResult should be called at a time, so
1251// the locks won't block. The locks are present here simply to enforce this.
1252hardware::Return<void> Camera3Device::processCaptureResult(
1253 const hardware::hidl_vec<
1254 hardware::camera::device::V3_2::CaptureResult>& results) {
1255 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1256
1257 // Ideally we should grab mLock, but that can lead to deadlock, and
1258 // it's not super important to get up to date value of mStatus for this
1259 // warning print, hence skipping the lock here
1260 if (mStatus == STATUS_ERROR) {
1261 // Per API contract, HAL should act as closed after device error
1262 // But mStatus can be set to error by framework as well, so just log
1263 // a warning here.
1264 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1265 }
1266
1267 if (mProcessCaptureResultLock.tryLock() != OK) {
1268 // This should never happen; it indicates a wrong client implementation
1269 // that doesn't follow the contract. But, we can be tolerant here.
1270 ALOGE("%s: callback overlapped! waiting 1s...",
1271 __FUNCTION__);
1272 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1273 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1274 __FUNCTION__);
1275 // really don't know what to do, so bail out.
1276 return hardware::Void();
1277 }
1278 }
1279 for (const auto& result : results) {
1280 processOneCaptureResultLocked(result, noPhysMetadata);
1281 }
1282 mProcessCaptureResultLock.unlock();
1283 return hardware::Void();
1284}
1285
1286status_t Camera3Device::readOneCameraMetadataLocked(
1287 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1288 const hardware::camera::device::V3_2::CameraMetadata& result) {
1289 if (fmqResultSize > 0) {
1290 resultMetadata.resize(fmqResultSize);
1291 if (mResultMetadataQueue == nullptr) {
1292 return NO_MEMORY; // logged in initialize()
1293 }
1294 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1295 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1296 __FUNCTION__, fmqResultSize);
1297 return INVALID_OPERATION;
1298 }
1299 } else {
1300 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1301 result.size());
1302 }
1303
1304 if (resultMetadata.size() != 0) {
1305 status_t res;
1306 const camera_metadata_t* metadata =
1307 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1308 size_t expected_metadata_size = resultMetadata.size();
1309 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1310 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1311 __FUNCTION__, strerror(-res), res);
1312 return INVALID_OPERATION;
1313 }
1314 }
1315
1316 return OK;
1317}
1318
Yifan Honga640c5a2017-04-12 16:30:31 -07001319void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001320 const hardware::camera::device::V3_2::CaptureResult& result,
1321 const hardware::hidl_vec<
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001322 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadata) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001323 camera3_capture_result r;
1324 status_t res;
1325 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001326
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001327 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001328 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001329 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1330 if (res != OK) {
1331 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1332 __FUNCTION__, result.frameNumber);
1333 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001334 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001335 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001336
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001337 // Read and validate physical camera metadata
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001338 size_t physResultCount = physicalCameraMetadata.size();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001339 std::vector<const char*> physCamIds(physResultCount);
1340 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1341 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1342 physResultMetadata.resize(physResultCount);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001343 for (size_t i = 0; i < physicalCameraMetadata.size(); i++) {
1344 res = readOneCameraMetadataLocked(physicalCameraMetadata[i].fmqMetadataSize,
1345 physResultMetadata[i], physicalCameraMetadata[i].metadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001346 if (res != OK) {
1347 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1348 __FUNCTION__, result.frameNumber,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001349 physicalCameraMetadata[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001350 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001351 }
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001352 physCamIds[i] = physicalCameraMetadata[i].physicalCameraId.c_str();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001353 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1354 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001355 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001356 r.num_physcam_metadata = physResultCount;
1357 r.physcam_ids = physCamIds.data();
1358 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001359
1360 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1361 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1362 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1363 auto& bDst = outputBuffers[i];
1364 const StreamBuffer &bSrc = result.outputBuffers[i];
1365
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001366 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1367 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001368 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1369 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001370 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001371 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001372 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001373
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001374 bool noBufferReturned = false;
1375 buffer_handle_t *buffer = nullptr;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001376 if (mUseHalBufManager) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001377 // This is suspicious most of the time but can be correct during flush where HAL
1378 // has to return capture result before a buffer is requested
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001379 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001380 if (bSrc.status == BufferStatus::OK) {
1381 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1382 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1383 // Still proceeds so other buffers can be returned
1384 }
1385 noBufferReturned = true;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001386 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001387 if (noBufferReturned) {
1388 res = OK;
1389 } else {
1390 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1391 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001392 } else {
1393 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1394 }
1395
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001396 if (res != OK) {
1397 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1398 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001399 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001400 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001401
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001402 bDst.buffer = buffer;
1403 bDst.status = mapHidlBufferStatus(bSrc.status);
1404 bDst.acquire_fence = -1;
1405 if (bSrc.releaseFence == nullptr) {
1406 bDst.release_fence = -1;
1407 } else if (bSrc.releaseFence->numFds == 1) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001408 if (noBufferReturned) {
1409 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
1410 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001411 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1412 } else {
1413 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1414 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001415 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001416 }
1417 }
1418 r.num_output_buffers = outputBuffers.size();
1419 r.output_buffers = outputBuffers.data();
1420
1421 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001422 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001423 r.input_buffer = nullptr;
1424 } else {
1425 if (mInputStream->getId() != result.inputBuffer.streamId) {
1426 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1427 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001428 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001429 }
1430 inputBuffer.stream = mInputStream->asHalStream();
1431 buffer_handle_t *buffer;
1432 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1433 &buffer);
1434 if (res != OK) {
1435 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1436 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001437 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001438 }
1439 inputBuffer.buffer = buffer;
1440 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1441 inputBuffer.acquire_fence = -1;
1442 if (result.inputBuffer.releaseFence == nullptr) {
1443 inputBuffer.release_fence = -1;
1444 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1445 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1446 } else {
1447 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1448 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001449 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001450 }
1451 r.input_buffer = &inputBuffer;
1452 }
1453
1454 r.partial_result = result.partialResult;
1455
1456 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001457}
1458
1459hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001460 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001461 // Ideally we should grab mLock, but that can lead to deadlock, and
1462 // it's not super important to get up to date value of mStatus for this
1463 // warning print, hence skipping the lock here
1464 if (mStatus == STATUS_ERROR) {
1465 // Per API contract, HAL should act as closed after device error
1466 // But mStatus can be set to error by framework as well, so just log
1467 // a warning here.
1468 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001469 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001470
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001471 for (const auto& msg : msgs) {
1472 notify(msg);
1473 }
1474 return hardware::Void();
1475}
1476
1477void Camera3Device::notify(
1478 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1479
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001480 camera3_notify_msg m;
1481 switch (msg.type) {
1482 case MsgType::ERROR:
1483 m.type = CAMERA3_MSG_ERROR;
1484 m.message.error.frame_number = msg.msg.error.frameNumber;
1485 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001486 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1487 if (stream == nullptr) {
1488 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1489 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001490 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001491 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001492 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001493 } else {
1494 m.message.error.error_stream = nullptr;
1495 }
1496 switch (msg.msg.error.errorCode) {
1497 case ErrorCode::ERROR_DEVICE:
1498 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1499 break;
1500 case ErrorCode::ERROR_REQUEST:
1501 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1502 break;
1503 case ErrorCode::ERROR_RESULT:
1504 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1505 break;
1506 case ErrorCode::ERROR_BUFFER:
1507 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1508 break;
1509 }
1510 break;
1511 case MsgType::SHUTTER:
1512 m.type = CAMERA3_MSG_SHUTTER;
1513 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1514 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1515 break;
1516 }
1517 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001518}
1519
Emilian Peevaebbe412018-01-15 13:53:24 +00001520status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001521 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001522 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001523 ATRACE_CALL();
1524
Emilian Peevaebbe412018-01-15 13:53:24 +00001525 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001526}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001527
Jianing Weicb0652e2014-03-12 18:29:36 -07001528status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1529 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001530 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001531
Emilian Peevaebbe412018-01-15 13:53:24 +00001532 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001533 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001534 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001535
Emilian Peevaebbe412018-01-15 13:53:24 +00001536 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001537 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538}
1539
Emilian Peevaebbe412018-01-15 13:53:24 +00001540status_t Camera3Device::setStreamingRequestList(
1541 const List<const PhysicalCameraSettingsList> &requestsList,
1542 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001543 ATRACE_CALL();
1544
Emilian Peevaebbe412018-01-15 13:53:24 +00001545 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001546}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001547
1548sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001549 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 status_t res;
1551
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001553 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1554 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001555 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1556 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001557 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001559 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001560 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001561 } else if (mStatus == STATUS_UNCONFIGURED) {
1562 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001563 CLOGE("No streams configured");
1564 return NULL;
1565 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001566 }
1567
Shuzhen Wang0129d522016-10-30 22:43:41 -07001568 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001570}
1571
Jianing Weicb0652e2014-03-12 18:29:36 -07001572status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001573 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001574 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001576
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001577 switch (mStatus) {
1578 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001579 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001580 return INVALID_OPERATION;
1581 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001582 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001584 case STATUS_UNCONFIGURED:
1585 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001586 case STATUS_ACTIVE:
1587 // OK
1588 break;
1589 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001590 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001591 return INVALID_OPERATION;
1592 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001593 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001594
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001595 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001596}
1597
1598status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1599 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001600 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001601
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001602 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001603}
1604
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001605status_t Camera3Device::createInputStream(
1606 uint32_t width, uint32_t height, int format, int *id) {
1607 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001608 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001609 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001610 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001611 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1612 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001613
1614 status_t res;
1615 bool wasActive = false;
1616
1617 switch (mStatus) {
1618 case STATUS_ERROR:
1619 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1620 return INVALID_OPERATION;
1621 case STATUS_UNINITIALIZED:
1622 ALOGE("%s: Device not initialized", __FUNCTION__);
1623 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001624 case STATUS_UNCONFIGURED:
1625 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001626 // OK
1627 break;
1628 case STATUS_ACTIVE:
1629 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001630 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001631 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001632 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001633 return res;
1634 }
1635 wasActive = true;
1636 break;
1637 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001638 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001639 return INVALID_OPERATION;
1640 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001641 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001642
1643 if (mInputStream != 0) {
1644 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1645 return INVALID_OPERATION;
1646 }
1647
1648 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1649 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001650 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001651
1652 mInputStream = newStream;
1653
1654 *id = mNextStreamId++;
1655
1656 // Continue captures if active at start
1657 if (wasActive) {
1658 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001659 // Reuse current operating mode and session parameters for new stream config
1660 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001661 if (res != OK) {
1662 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1663 __FUNCTION__, mNextStreamId, strerror(-res), res);
1664 return res;
1665 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001666 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001667 }
1668
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001669 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001670 return OK;
1671}
1672
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001673status_t Camera3Device::StreamSet::add(
1674 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1675 if (stream == nullptr) {
1676 ALOGE("%s: cannot add null stream", __FUNCTION__);
1677 return BAD_VALUE;
1678 }
1679 std::lock_guard<std::mutex> lock(mLock);
1680 return mData.add(streamId, stream);
1681}
1682
1683ssize_t Camera3Device::StreamSet::remove(int streamId) {
1684 std::lock_guard<std::mutex> lock(mLock);
1685 return mData.removeItem(streamId);
1686}
1687
1688sp<camera3::Camera3OutputStreamInterface>
1689Camera3Device::StreamSet::get(int streamId) {
1690 std::lock_guard<std::mutex> lock(mLock);
1691 ssize_t idx = mData.indexOfKey(streamId);
1692 if (idx == NAME_NOT_FOUND) {
1693 return nullptr;
1694 }
1695 return mData.editValueAt(idx);
1696}
1697
1698sp<camera3::Camera3OutputStreamInterface>
1699Camera3Device::StreamSet::operator[] (size_t index) {
1700 std::lock_guard<std::mutex> lock(mLock);
1701 return mData.editValueAt(index);
1702}
1703
1704size_t Camera3Device::StreamSet::size() const {
1705 std::lock_guard<std::mutex> lock(mLock);
1706 return mData.size();
1707}
1708
1709void Camera3Device::StreamSet::clear() {
1710 std::lock_guard<std::mutex> lock(mLock);
1711 return mData.clear();
1712}
1713
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001714std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1715 std::lock_guard<std::mutex> lock(mLock);
1716 std::vector<int> streamIds(mData.size());
1717 for (size_t i = 0; i < mData.size(); i++) {
1718 streamIds[i] = mData.keyAt(i);
1719 }
1720 return streamIds;
1721}
1722
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001723status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001724 uint32_t width, uint32_t height, int format,
1725 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001726 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001727 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001728 ATRACE_CALL();
1729
1730 if (consumer == nullptr) {
1731 ALOGE("%s: consumer must not be null", __FUNCTION__);
1732 return BAD_VALUE;
1733 }
1734
1735 std::vector<sp<Surface>> consumers;
1736 consumers.push_back(consumer);
1737
1738 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001739 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1740 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001741}
1742
1743status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1744 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1745 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001746 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001747 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001748 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001749
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001750 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001751 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001752 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001753 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001754 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1755 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1756 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001757
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001758 status_t res;
1759 bool wasActive = false;
1760
1761 switch (mStatus) {
1762 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001763 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001764 return INVALID_OPERATION;
1765 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001766 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001767 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001768 case STATUS_UNCONFIGURED:
1769 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001770 // OK
1771 break;
1772 case STATUS_ACTIVE:
1773 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001774 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001775 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001776 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001777 return res;
1778 }
1779 wasActive = true;
1780 break;
1781 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001782 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001783 return INVALID_OPERATION;
1784 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001785 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001786
1787 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001788
Shuzhen Wang0129d522016-10-30 22:43:41 -07001789 if (consumers.size() == 0 && !hasDeferredConsumer) {
1790 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1791 return BAD_VALUE;
1792 }
Zhijun He5d677d12016-05-29 16:52:39 -07001793
Shuzhen Wang0129d522016-10-30 22:43:41 -07001794 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001795 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1796 return BAD_VALUE;
1797 }
1798
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001799 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001800 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001801 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001802 blobBufferSize = getPointCloudBufferSize();
1803 if (blobBufferSize <= 0) {
1804 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1805 return BAD_VALUE;
1806 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001807 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1808 blobBufferSize = width * height;
1809 } else {
1810 blobBufferSize = getJpegBufferSize(width, height);
1811 if (blobBufferSize <= 0) {
1812 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1813 return BAD_VALUE;
1814 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001815 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001816 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001817 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001818 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001819 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1820 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1821 if (rawOpaqueBufferSize <= 0) {
1822 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1823 return BAD_VALUE;
1824 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001825 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001826 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001827 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001828 } else if (isShared) {
1829 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1830 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001831 mTimestampOffset, physicalCameraId, streamSetId,
1832 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001833 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001834 newStream = new Camera3OutputStream(mNextStreamId,
1835 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001836 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001837 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001838 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001839 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001840 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001841 }
Emilian Peev40ead602017-09-26 15:46:36 +01001842
1843 size_t consumerCount = consumers.size();
1844 for (size_t i = 0; i < consumerCount; i++) {
1845 int id = newStream->getSurfaceId(consumers[i]);
1846 if (id < 0) {
1847 SET_ERR_L("Invalid surface id");
1848 return BAD_VALUE;
1849 }
1850 if (surfaceIds != nullptr) {
1851 surfaceIds->push_back(id);
1852 }
1853 }
1854
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001855 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001856
Emilian Peev08dd2452017-04-06 16:55:14 +01001857 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001858
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001859 res = mOutputStreams.add(mNextStreamId, newStream);
1860 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001861 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001862 return res;
1863 }
1864
1865 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001866 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001867
1868 // Continue captures if active at start
1869 if (wasActive) {
1870 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001871 // Reuse current operating mode and session parameters for new stream config
1872 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001873 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001874 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1875 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001876 return res;
1877 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001878 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001879 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001880 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001881 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001882}
1883
Emilian Peev710c1422017-08-30 11:19:38 +01001884status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001885 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001886 if (nullptr == streamInfo) {
1887 return BAD_VALUE;
1888 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001889 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001890 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001891
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001892 switch (mStatus) {
1893 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001894 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001895 return INVALID_OPERATION;
1896 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001897 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001898 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001899 case STATUS_UNCONFIGURED:
1900 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001901 case STATUS_ACTIVE:
1902 // OK
1903 break;
1904 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001905 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001906 return INVALID_OPERATION;
1907 }
1908
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001909 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1910 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001911 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001912 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001913 }
1914
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001915 streamInfo->width = stream->getWidth();
1916 streamInfo->height = stream->getHeight();
1917 streamInfo->format = stream->getFormat();
1918 streamInfo->dataSpace = stream->getDataSpace();
1919 streamInfo->formatOverridden = stream->isFormatOverridden();
1920 streamInfo->originalFormat = stream->getOriginalFormat();
1921 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1922 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001923 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001924}
1925
1926status_t Camera3Device::setStreamTransform(int id,
1927 int transform) {
1928 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001929 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001930 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001931
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001932 switch (mStatus) {
1933 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001934 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001935 return INVALID_OPERATION;
1936 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001937 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001938 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001939 case STATUS_UNCONFIGURED:
1940 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001941 case STATUS_ACTIVE:
1942 // OK
1943 break;
1944 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001945 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001946 return INVALID_OPERATION;
1947 }
1948
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001949 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1950 if (stream == nullptr) {
1951 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001952 return BAD_VALUE;
1953 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001954 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001955}
1956
1957status_t Camera3Device::deleteStream(int id) {
1958 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001959 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001960 Mutex::Autolock l(mLock);
1961 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001962
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001963 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001964
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001965 // CameraDevice semantics require device to already be idle before
1966 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001967 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001968 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001969 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001970 }
1971
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001972 if (mStatus == STATUS_ERROR) {
1973 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1974 __FUNCTION__, mId.string());
1975 return -EBUSY;
1976 }
1977
Igor Murashkin2fba5842013-04-22 14:03:54 -07001978 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001979 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001980 if (mInputStream != NULL && id == mInputStream->getId()) {
1981 deletedStream = mInputStream;
1982 mInputStream.clear();
1983 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001984 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001985 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001986 return BAD_VALUE;
1987 }
Zhijun He5f446352014-01-22 09:49:33 -08001988 }
1989
1990 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001991 if (stream != nullptr) {
1992 deletedStream = stream;
1993 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001994 }
1995
1996 // Free up the stream endpoint so that it can be used by some other stream
1997 res = deletedStream->disconnect();
1998 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001999 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002000 // fall through since we want to still list the stream as deleted.
2001 }
2002 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002003 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002004
2005 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002006}
2007
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002008status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07002009 ATRACE_CALL();
2010 ALOGV("%s: E", __FUNCTION__);
2011
2012 Mutex::Autolock il(mInterfaceLock);
2013 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07002014
Emilian Peev811d2952018-05-25 11:08:40 +01002015 // In case the client doesn't include any session parameter, try a
2016 // speculative configuration using the values from the last cached
2017 // default request.
2018 if (sessionParams.isEmpty() &&
2019 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
2020 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
2021 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
2022 mLastTemplateId);
2023 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
2024 operatingMode);
2025 }
2026
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002027 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
2028}
2029
2030status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
2031 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002032 //Filter out any incoming session parameters
2033 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002034 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
2035 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002036 CameraMetadata filteredParams(availableSessionKeys.count);
2037 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2038 filteredParams.getAndLock());
2039 set_camera_metadata_vendor_id(meta, mVendorTagId);
2040 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002041 if (availableSessionKeys.count > 0) {
2042 for (size_t i = 0; i < availableSessionKeys.count; i++) {
2043 camera_metadata_ro_entry entry = params.find(
2044 availableSessionKeys.data.i32[i]);
2045 if (entry.count > 0) {
2046 filteredParams.update(entry);
2047 }
2048 }
2049 }
2050
2051 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07002052}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002053
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002054status_t Camera3Device::getInputBufferProducer(
2055 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002056 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002057 Mutex::Autolock il(mInterfaceLock);
2058 Mutex::Autolock l(mLock);
2059
2060 if (producer == NULL) {
2061 return BAD_VALUE;
2062 } else if (mInputStream == NULL) {
2063 return INVALID_OPERATION;
2064 }
2065
2066 return mInputStream->getInputBufferProducer(producer);
2067}
2068
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002069status_t Camera3Device::createDefaultRequest(int templateId,
2070 CameraMetadata *request) {
2071 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002072 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002073
2074 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2075 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002076 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002077 return BAD_VALUE;
2078 }
2079
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002080 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002081
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002082 {
2083 Mutex::Autolock l(mLock);
2084 switch (mStatus) {
2085 case STATUS_ERROR:
2086 CLOGE("Device has encountered a serious error");
2087 return INVALID_OPERATION;
2088 case STATUS_UNINITIALIZED:
2089 CLOGE("Device is not initialized!");
2090 return INVALID_OPERATION;
2091 case STATUS_UNCONFIGURED:
2092 case STATUS_CONFIGURED:
2093 case STATUS_ACTIVE:
2094 // OK
2095 break;
2096 default:
2097 SET_ERR_L("Unexpected status: %d", mStatus);
2098 return INVALID_OPERATION;
2099 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002100
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002101 if (!mRequestTemplateCache[templateId].isEmpty()) {
2102 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002103 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002104 return OK;
2105 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002106 }
2107
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002108 camera_metadata_t *rawRequest;
2109 status_t res = mInterface->constructDefaultRequestSettings(
2110 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002111
2112 {
2113 Mutex::Autolock l(mLock);
2114 if (res == BAD_VALUE) {
2115 ALOGI("%s: template %d is not supported on this camera device",
2116 __FUNCTION__, templateId);
2117 return res;
2118 } else if (res != OK) {
2119 CLOGE("Unable to construct request template %d: %s (%d)",
2120 templateId, strerror(-res), res);
2121 return res;
2122 }
2123
2124 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2125 mRequestTemplateCache[templateId].acquire(rawRequest);
2126
2127 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002128 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002129 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002130 return OK;
2131}
2132
2133status_t Camera3Device::waitUntilDrained() {
2134 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002135 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002136 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002137 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002138
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002139 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002140}
2141
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002142status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002143 switch (mStatus) {
2144 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002145 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002146 ALOGV("%s: Already idle", __FUNCTION__);
2147 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002148 case STATUS_CONFIGURED:
2149 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002150 case STATUS_ERROR:
2151 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002152 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002153 break;
2154 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002155 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002156 return INVALID_OPERATION;
2157 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002158 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2159 maxExpectedDuration);
2160 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002161 if (res != OK) {
2162 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2163 res);
2164 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002165 return res;
2166}
2167
Ruben Brunk183f0562015-08-12 12:55:02 -07002168
2169void Camera3Device::internalUpdateStatusLocked(Status status) {
2170 mStatus = status;
2171 mRecentStatusUpdates.add(mStatus);
2172 mStatusChanged.broadcast();
2173}
2174
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002175void Camera3Device::pauseStateNotify(bool enable) {
2176 Mutex::Autolock il(mInterfaceLock);
2177 Mutex::Autolock l(mLock);
2178
2179 mPauseStateNotify = enable;
2180}
2181
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002182// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002183status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08002184 if (mRequestThread.get() != nullptr) {
2185 mRequestThread->setPaused(true);
2186 } else {
2187 return NO_INIT;
2188 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002189
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002190 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2191 maxExpectedDuration);
2192 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002193 if (res != OK) {
2194 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002195 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002196 }
2197
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002198 return res;
2199}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002200
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002201// Resume after internalPauseAndWaitLocked
2202status_t Camera3Device::internalResumeLocked() {
2203 status_t res;
2204
2205 mRequestThread->setPaused(false);
2206
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002207 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2208 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002209 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2210 if (res != OK) {
2211 SET_ERR_L("Can't transition to active in %f seconds!",
2212 kActiveTimeout/1e9);
2213 }
2214 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002215 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002216}
2217
Ruben Brunk183f0562015-08-12 12:55:02 -07002218status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002219 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002220
2221 size_t startIndex = 0;
2222 if (mStatusWaiters == 0) {
2223 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2224 // this status list
2225 mRecentStatusUpdates.clear();
2226 } else {
2227 // If other threads are waiting on updates to this status list, set the position of the
2228 // first element that this list will check rather than clearing the list.
2229 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002230 }
2231
Ruben Brunk183f0562015-08-12 12:55:02 -07002232 mStatusWaiters++;
2233
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002234 if (!active && mUseHalBufManager) {
2235 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08002236 if (mStatus == STATUS_ACTIVE) {
2237 mRequestThread->signalPipelineDrain(streamIds);
2238 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002239 mRequestBufferSM.onWaitUntilIdle();
2240 }
2241
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002242 bool stateSeen = false;
2243 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002244 if (active == (mStatus == STATUS_ACTIVE)) {
2245 // Desired state is current
2246 break;
2247 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002248
2249 res = mStatusChanged.waitRelative(mLock, timeout);
2250 if (res != OK) break;
2251
Ruben Brunk183f0562015-08-12 12:55:02 -07002252 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2253 // transitions.
2254 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2255 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2256 __FUNCTION__);
2257
2258 // Encountered desired state since we began waiting
2259 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002260 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2261 stateSeen = true;
2262 break;
2263 }
2264 }
2265 } while (!stateSeen);
2266
Ruben Brunk183f0562015-08-12 12:55:02 -07002267 mStatusWaiters--;
2268
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002269 return res;
2270}
2271
2272
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002273status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002274 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002275 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002276
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002277 if (listener != NULL && mListener != NULL) {
2278 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2279 }
2280 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002281 mRequestThread->setNotificationListener(listener);
2282 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002283
2284 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002285}
2286
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002287bool Camera3Device::willNotify3A() {
2288 return false;
2289}
2290
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002291status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002292 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002293 status_t res;
2294 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002295
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002296 while (mResultQueue.empty()) {
2297 res = mResultSignal.waitRelative(mOutputLock, timeout);
2298 if (res == TIMED_OUT) {
2299 return res;
2300 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002301 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2302 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002303 return res;
2304 }
2305 }
2306 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002307}
2308
Jianing Weicb0652e2014-03-12 18:29:36 -07002309status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002310 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002311 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002312
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002313 if (mResultQueue.empty()) {
2314 return NOT_ENOUGH_DATA;
2315 }
2316
Jianing Weicb0652e2014-03-12 18:29:36 -07002317 if (frame == NULL) {
2318 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2319 return BAD_VALUE;
2320 }
2321
2322 CaptureResult &result = *(mResultQueue.begin());
2323 frame->mResultExtras = result.mResultExtras;
2324 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002325 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002326 mResultQueue.erase(mResultQueue.begin());
2327
2328 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002329}
2330
2331status_t Camera3Device::triggerAutofocus(uint32_t id) {
2332 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002333 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002334
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002335 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2336 // Mix-in this trigger into the next request and only the next request.
2337 RequestTrigger trigger[] = {
2338 {
2339 ANDROID_CONTROL_AF_TRIGGER,
2340 ANDROID_CONTROL_AF_TRIGGER_START
2341 },
2342 {
2343 ANDROID_CONTROL_AF_TRIGGER_ID,
2344 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002345 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002346 };
2347
2348 return mRequestThread->queueTrigger(trigger,
2349 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002350}
2351
2352status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2353 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002354 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002355
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002356 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2357 // Mix-in this trigger into the next request and only the next request.
2358 RequestTrigger trigger[] = {
2359 {
2360 ANDROID_CONTROL_AF_TRIGGER,
2361 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2362 },
2363 {
2364 ANDROID_CONTROL_AF_TRIGGER_ID,
2365 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002366 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002367 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002368
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002369 return mRequestThread->queueTrigger(trigger,
2370 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002371}
2372
2373status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2374 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002375 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002376
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002377 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2378 // Mix-in this trigger into the next request and only the next request.
2379 RequestTrigger trigger[] = {
2380 {
2381 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2382 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2383 },
2384 {
2385 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2386 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002387 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002388 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002389
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002390 return mRequestThread->queueTrigger(trigger,
2391 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002392}
2393
Jianing Weicb0652e2014-03-12 18:29:36 -07002394status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002395 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002396 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002397 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002398
Zhijun He7ef20392014-04-21 16:04:17 -07002399 {
2400 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002401
2402 // b/116514106 "disconnect()" can get called twice for the same device. The
2403 // camera device will not be initialized during the second run.
2404 if (mStatus == STATUS_UNINITIALIZED) {
2405 return OK;
2406 }
2407
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002408 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002409 }
2410
Emilian Peev08dd2452017-04-06 16:55:14 +01002411 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002412}
2413
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002414status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002415 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2416}
2417
2418status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002419 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002420 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002421 Mutex::Autolock il(mInterfaceLock);
2422 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002423
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002424 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2425 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002426 CLOGE("Stream %d does not exist", streamId);
2427 return BAD_VALUE;
2428 }
2429
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002430 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002431 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002432 return BAD_VALUE;
2433 }
2434
2435 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002436 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002437 return BAD_VALUE;
2438 }
2439
Ruben Brunkc78ac262015-08-13 17:58:46 -07002440 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002441}
2442
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002443status_t Camera3Device::tearDown(int streamId) {
2444 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002445 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002446 Mutex::Autolock il(mInterfaceLock);
2447 Mutex::Autolock l(mLock);
2448
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002449 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2450 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002451 CLOGE("Stream %d does not exist", streamId);
2452 return BAD_VALUE;
2453 }
2454
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002455 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2456 CLOGE("Stream %d is a target of a in-progress request", streamId);
2457 return BAD_VALUE;
2458 }
2459
2460 return stream->tearDown();
2461}
2462
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002463status_t Camera3Device::addBufferListenerForStream(int streamId,
2464 wp<Camera3StreamBufferListener> listener) {
2465 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002466 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002467 Mutex::Autolock il(mInterfaceLock);
2468 Mutex::Autolock l(mLock);
2469
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002470 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2471 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002472 CLOGE("Stream %d does not exist", streamId);
2473 return BAD_VALUE;
2474 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002475 stream->addBufferListener(listener);
2476
2477 return OK;
2478}
2479
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002480/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002481 * Methods called by subclasses
2482 */
2483
2484void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002485 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002486 {
2487 // Need mLock to safely update state and synchronize to current
2488 // state of methods in flight.
2489 Mutex::Autolock l(mLock);
2490 // We can get various system-idle notices from the status tracker
2491 // while starting up. Only care about them if we've actually sent
2492 // in some requests recently.
2493 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2494 return;
2495 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002496 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2497 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002498 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002499
2500 // Skip notifying listener if we're doing some user-transparent
2501 // state changes
2502 if (mPauseStateNotify) return;
2503 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002504
2505 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002506 {
2507 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002508 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002509 }
2510 if (idle && listener != NULL) {
2511 listener->notifyIdle();
2512 }
2513}
2514
Shuzhen Wang758c2152017-01-10 18:26:18 -08002515status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002516 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002517 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002518 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2519 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002520
2521 if (surfaceIds == nullptr) {
2522 return BAD_VALUE;
2523 }
2524
Zhijun He5d677d12016-05-29 16:52:39 -07002525 Mutex::Autolock il(mInterfaceLock);
2526 Mutex::Autolock l(mLock);
2527
Shuzhen Wang758c2152017-01-10 18:26:18 -08002528 if (consumers.size() == 0) {
2529 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002530 return BAD_VALUE;
2531 }
2532
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002533 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2534 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002535 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002536 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002537 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002538
2539 // isConsumerConfigurationDeferred will be off after setConsumers
2540 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002541 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002542 if (res != OK) {
2543 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2544 return res;
2545 }
2546
Emilian Peev40ead602017-09-26 15:46:36 +01002547 for (auto &consumer : consumers) {
2548 int id = stream->getSurfaceId(consumer);
2549 if (id < 0) {
2550 CLOGE("Invalid surface id!");
2551 return BAD_VALUE;
2552 }
2553 surfaceIds->push_back(id);
2554 }
2555
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002556 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002557 if (!stream->isConfiguring()) {
2558 CLOGE("Stream %d was already fully configured.", streamId);
2559 return INVALID_OPERATION;
2560 }
Zhijun He5d677d12016-05-29 16:52:39 -07002561
Shuzhen Wang0129d522016-10-30 22:43:41 -07002562 res = stream->finishConfiguration();
2563 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002564 // If finishConfiguration fails due to abandoned surface, do not set
2565 // device to error state.
2566 bool isSurfaceAbandoned =
2567 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2568 if (!isSurfaceAbandoned) {
2569 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2570 stream->getId(), strerror(-res), res);
2571 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002572 return res;
2573 }
Zhijun He5d677d12016-05-29 16:52:39 -07002574 }
2575
2576 return OK;
2577}
2578
Emilian Peev40ead602017-09-26 15:46:36 +01002579status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2580 const std::vector<OutputStreamInfo> &outputInfo,
2581 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2582 Mutex::Autolock il(mInterfaceLock);
2583 Mutex::Autolock l(mLock);
2584
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002585 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2586 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002587 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002588 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002589 }
2590
2591 for (const auto &it : removedSurfaceIds) {
2592 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2593 CLOGE("Shared surface still part of a pending request!");
2594 return -EBUSY;
2595 }
2596 }
2597
Emilian Peev40ead602017-09-26 15:46:36 +01002598 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2599 if (res != OK) {
2600 CLOGE("Stream %d failed to update stream (error %d %s) ",
2601 streamId, res, strerror(-res));
2602 if (res == UNKNOWN_ERROR) {
2603 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2604 __FUNCTION__);
2605 }
2606 return res;
2607 }
2608
2609 return res;
2610}
2611
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002612status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2613 Mutex::Autolock il(mInterfaceLock);
2614 Mutex::Autolock l(mLock);
2615
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002616 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2617 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002618 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2619 return BAD_VALUE;
2620 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002621 return stream->dropBuffers(dropping);
2622}
2623
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002624/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002625 * Camera3Device private methods
2626 */
2627
2628sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002629 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002630 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002631
2632 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002633 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002634
2635 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002636 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002637 if (inputStreams.count > 0) {
2638 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002639 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002640 CLOGE("Request references unknown input stream %d",
2641 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002642 return NULL;
2643 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002644
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002645 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002646 SET_ERR_L("%s: input stream %d is not configured!",
2647 __FUNCTION__, mInputStream->getId());
2648 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002649 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002650 // Check if stream prepare is blocking requests.
2651 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002652 CLOGE("Request references an input stream that's being prepared!");
2653 return NULL;
2654 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002655
2656 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002657 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002658 }
2659
2660 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002661 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002662 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002663 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002664 return NULL;
2665 }
2666
2667 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002668 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2669 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002670 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002671 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002672 return NULL;
2673 }
Zhijun He5d677d12016-05-29 16:52:39 -07002674 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002675 auto iter = surfaceMap.find(streams.data.i32[i]);
2676 if (iter != surfaceMap.end()) {
2677 const std::vector<size_t>& surfaces = iter->second;
2678 for (const auto& surface : surfaces) {
2679 if (stream->isConsumerConfigurationDeferred(surface)) {
2680 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2681 "due to deferred consumer", stream->getId(), surface);
2682 return NULL;
2683 }
2684 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002685 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002686 }
2687
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002688 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002689 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2690 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002691 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002692 // Check if stream prepare is blocking requests.
2693 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002694 CLOGE("Request references an output stream that's being prepared!");
2695 return NULL;
2696 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002697
2698 newRequest->mOutputStreams.push(stream);
2699 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002700 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002701 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002702
2703 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002704}
2705
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002706bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2707 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2708 Size size = mSupportedOpaqueInputSizes[i];
2709 if (size.width == width && size.height == height) {
2710 return true;
2711 }
2712 }
2713
2714 return false;
2715}
2716
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002717void Camera3Device::cancelStreamsConfigurationLocked() {
2718 int res = OK;
2719 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2720 res = mInputStream->cancelConfiguration();
2721 if (res != OK) {
2722 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2723 mInputStream->getId(), strerror(-res), res);
2724 }
2725 }
2726
2727 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002728 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002729 if (outputStream->isConfiguring()) {
2730 res = outputStream->cancelConfiguration();
2731 if (res != OK) {
2732 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2733 outputStream->getId(), strerror(-res), res);
2734 }
2735 }
2736 }
2737
2738 // Return state to that at start of call, so that future configures
2739 // properly clean things up
2740 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2741 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002742
2743 res = mPreparerThread->resume();
2744 if (res != OK) {
2745 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2746 }
2747}
2748
2749bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2750 ATRACE_CALL();
2751 bool ret = false;
2752
2753 Mutex::Autolock il(mInterfaceLock);
2754 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2755
2756 Mutex::Autolock l(mLock);
2757 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2758 if (rc == NO_ERROR) {
2759 mNeedConfig = true;
2760 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2761 if (rc == NO_ERROR) {
2762 ret = true;
2763 mPauseStateNotify = false;
2764 //Moving to active state while holding 'mLock' is important.
2765 //There could be pending calls to 'create-/deleteStream' which
2766 //will trigger another stream configuration while the already
2767 //present streams end up with outstanding buffers that will
2768 //not get drained.
2769 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002770 } else if (rc == DEAD_OBJECT) {
2771 // DEAD_OBJECT can be returned if either the consumer surface is
2772 // abandoned, or the HAL has died.
2773 // - If the HAL has died, configureStreamsLocked call will set
2774 // device to error state,
2775 // - If surface is abandoned, we should not set device to error
2776 // state.
2777 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002778 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002779 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002780 }
2781 } else {
2782 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2783 }
2784
2785 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002786}
2787
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002788status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002789 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002790 ATRACE_CALL();
2791 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002792
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002793 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002794 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002795 return INVALID_OPERATION;
2796 }
2797
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002798 if (operatingMode < 0) {
2799 CLOGE("Invalid operating mode: %d", operatingMode);
2800 return BAD_VALUE;
2801 }
2802
2803 bool isConstrainedHighSpeed =
2804 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2805 operatingMode;
2806
2807 if (mOperatingMode != operatingMode) {
2808 mNeedConfig = true;
2809 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2810 mOperatingMode = operatingMode;
2811 }
2812
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002813 // In case called from configureStreams, abort queued input buffers not belonging to
2814 // any pending requests.
2815 if (mInputStream != NULL && notifyRequestThread) {
2816 while (true) {
2817 camera3_stream_buffer_t inputBuffer;
2818 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2819 /*respectHalLimit*/ false);
2820 if (res != OK) {
2821 // Exhausted acquiring all input buffers.
2822 break;
2823 }
2824
2825 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2826 res = mInputStream->returnInputBuffer(inputBuffer);
2827 if (res != OK) {
2828 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2829 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2830 }
2831 }
2832 }
2833
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002834 if (!mNeedConfig) {
2835 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2836 return OK;
2837 }
2838
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002839 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2840 // adding a dummy stream instead.
2841 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2842 if (mOutputStreams.size() == 0) {
2843 addDummyStreamLocked();
2844 } else {
2845 tryRemoveDummyStreamLocked();
2846 }
2847
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002848 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002849 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002850
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002851 mPreparerThread->pause();
2852
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002853 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002854 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002855 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2856
2857 Vector<camera3_stream_t*> streams;
2858 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002859 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002860
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002861
2862 if (mInputStream != NULL) {
2863 camera3_stream_t *inputStream;
2864 inputStream = mInputStream->startConfiguration();
2865 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002866 CLOGE("Can't start input stream configuration");
2867 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002868 return INVALID_OPERATION;
2869 }
2870 streams.add(inputStream);
2871 }
2872
2873 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002874
2875 // Don't configure bidi streams twice, nor add them twice to the list
2876 if (mOutputStreams[i].get() ==
2877 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2878
2879 config.num_streams--;
2880 continue;
2881 }
2882
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002883 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002884 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002885 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002886 CLOGE("Can't start output stream configuration");
2887 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002888 return INVALID_OPERATION;
2889 }
2890 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002891
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002892 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002893 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2894 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002895 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2896 bufferSizes[k] = static_cast<uint32_t>(
2897 getJpegBufferSize(outputStream->width, outputStream->height));
2898 } else if (outputStream->data_space ==
2899 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2900 bufferSizes[k] = outputStream->width * outputStream->height;
2901 } else {
2902 ALOGW("%s: Blob dataSpace %d not supported",
2903 __FUNCTION__, outputStream->data_space);
2904 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002905 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002906 }
2907
2908 config.streams = streams.editArray();
2909
2910 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002911 // max_buffers, usage, and priv fields, as well as data_space and format
2912 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002913
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002914 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002915 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002916 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002917
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002918 if (res == BAD_VALUE) {
2919 // HAL rejected this set of streams as unsupported, clean up config
2920 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002921 CLOGE("Set of requested inputs/outputs not supported by HAL");
2922 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002923 return BAD_VALUE;
2924 } else if (res != OK) {
2925 // Some other kind of error from configure_streams - this is not
2926 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002927 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2928 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002929 return res;
2930 }
2931
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002932 // Finish all stream configuration immediately.
2933 // TODO: Try to relax this later back to lazy completion, which should be
2934 // faster
2935
Igor Murashkin073f8572013-05-02 14:59:28 -07002936 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002937 bool streamReConfigured = false;
2938 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002939 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002940 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002941 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002942 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002943 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2944 return DEAD_OBJECT;
2945 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002946 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002947 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002948 if (streamReConfigured) {
2949 mInterface->onStreamReConfigured(mInputStream->getId());
2950 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002951 }
2952
2953 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002954 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002955 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002956 bool streamReConfigured = false;
2957 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002958 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002959 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002960 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002961 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002962 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2963 return DEAD_OBJECT;
2964 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002965 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002966 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002967 if (streamReConfigured) {
2968 mInterface->onStreamReConfigured(outputStream->getId());
2969 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002970 }
2971 }
2972
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002973 // Request thread needs to know to avoid using repeat-last-settings protocol
2974 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002975 if (notifyRequestThread) {
2976 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2977 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002978
Zhijun He90f7c372016-08-16 16:19:43 -07002979 char value[PROPERTY_VALUE_MAX];
2980 property_get("camera.fifo.disable", value, "0");
2981 int32_t disableFifo = atoi(value);
2982 if (disableFifo != 1) {
2983 // Boost priority of request thread to SCHED_FIFO.
2984 pid_t requestThreadTid = mRequestThread->getTid();
2985 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002986 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002987 if (res != OK) {
2988 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2989 strerror(-res), res);
2990 } else {
2991 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2992 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002993 }
2994
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002995 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002996 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2997 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2998 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2999 sessionParams.unlock(newSessionParams);
3000 mSessionParams.unlock(currentSessionParams);
3001 if (updateSessionParams) {
3002 mSessionParams = sessionParams;
3003 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003004
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07003005 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003006
Ruben Brunk183f0562015-08-12 12:55:02 -07003007 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
3008 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003009
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003010 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003011
Zhijun He0a210512014-07-24 13:45:15 -07003012 // tear down the deleted streams after configure streams.
3013 mDeletedStreams.clear();
3014
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003015 auto rc = mPreparerThread->resume();
3016 if (rc != OK) {
3017 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
3018 return rc;
3019 }
3020
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003021 if (mDummyStreamId == NO_STREAM) {
3022 mRequestBufferSM.onStreamsConfigured();
3023 }
3024
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003025 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003026}
3027
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003028status_t Camera3Device::addDummyStreamLocked() {
3029 ATRACE_CALL();
3030 status_t res;
3031
3032 if (mDummyStreamId != NO_STREAM) {
3033 // Should never be adding a second dummy stream when one is already
3034 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003035 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
3036 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003037 return INVALID_OPERATION;
3038 }
3039
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003040 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003041
3042 sp<Camera3OutputStreamInterface> dummyStream =
3043 new Camera3DummyStream(mNextStreamId);
3044
3045 res = mOutputStreams.add(mNextStreamId, dummyStream);
3046 if (res < 0) {
3047 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
3048 return res;
3049 }
3050
3051 mDummyStreamId = mNextStreamId;
3052 mNextStreamId++;
3053
3054 return OK;
3055}
3056
3057status_t Camera3Device::tryRemoveDummyStreamLocked() {
3058 ATRACE_CALL();
3059 status_t res;
3060
3061 if (mDummyStreamId == NO_STREAM) return OK;
3062 if (mOutputStreams.size() == 1) return OK;
3063
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003064 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003065
3066 // Ok, have a dummy stream and there's at least one other output stream,
3067 // so remove the dummy
3068
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003069 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
3070 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003071 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3072 return INVALID_OPERATION;
3073 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003074 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003075
3076 // Free up the stream endpoint so that it can be used by some other stream
3077 res = deletedStream->disconnect();
3078 if (res != OK) {
3079 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3080 // fall through since we want to still list the stream as deleted.
3081 }
3082 mDeletedStreams.add(deletedStream);
3083 mDummyStreamId = NO_STREAM;
3084
3085 return res;
3086}
3087
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003088void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003089 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003090 Mutex::Autolock l(mLock);
3091 va_list args;
3092 va_start(args, fmt);
3093
3094 setErrorStateLockedV(fmt, args);
3095
3096 va_end(args);
3097}
3098
3099void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003100 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003101 Mutex::Autolock l(mLock);
3102 setErrorStateLockedV(fmt, args);
3103}
3104
3105void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3106 va_list args;
3107 va_start(args, fmt);
3108
3109 setErrorStateLockedV(fmt, args);
3110
3111 va_end(args);
3112}
3113
3114void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003115 // Print out all error messages to log
3116 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003117 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003118
3119 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003120 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003121
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003122 mErrorCause = errorCause;
3123
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003124 if (mRequestThread != nullptr) {
3125 mRequestThread->setPaused(true);
3126 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003127 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003128
3129 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003130 sp<NotificationListener> listener = mListener.promote();
3131 if (listener != NULL) {
3132 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003133 CaptureResultExtras());
3134 }
3135
3136 // Save stack trace. View by dumping it later.
3137 CameraTraces::saveTrace();
3138 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003139}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003140
3141/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003142 * In-flight request management
3143 */
3144
Jianing Weicb0652e2014-03-12 18:29:36 -07003145status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003146 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003147 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003148 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003149 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003150 ATRACE_CALL();
3151 Mutex::Autolock l(mInFlightLock);
3152
3153 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003154 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003155 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3156 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003157 if (res < 0) return res;
3158
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003159 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003160 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3161 // avoid a deadlock during reprocess requests.
3162 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003163 if (mStatusTracker != nullptr) {
3164 mStatusTracker->markComponentActive(mInFlightStatusId);
3165 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003166 }
3167
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003168 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003169 return OK;
3170}
3171
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003172void Camera3Device::returnOutputBuffers(
3173 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003174 nsecs_t timestamp, bool timestampIncreasing,
3175 const SurfaceMap& outputSurfaces,
3176 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003177
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003178 for (size_t i = 0; i < numBuffers; i++)
3179 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003180 if (outputBuffers[i].buffer == nullptr) {
3181 if (!mUseHalBufManager) {
3182 // With HAL buffer management API, HAL sometimes will have to return buffers that
3183 // has not got a output buffer handle filled yet. This is though illegal if HAL
3184 // buffer management API is not being used.
3185 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3186 }
3187 continue;
3188 }
3189
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003190 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3191 int streamId = stream->getId();
3192 const auto& it = outputSurfaces.find(streamId);
3193 status_t res = OK;
3194 if (it != outputSurfaces.end()) {
3195 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003196 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3197 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003198 } else {
3199 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003200 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3201 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003202 }
3203
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003204 // Note: stream may be deallocated at this point, if this buffer was
3205 // the last reference to it.
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003206 if (res == NO_INIT || res == DEAD_OBJECT) {
3207 ALOGV("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
3208 } else if (res != OK) {
3209 ALOGE("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003210 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003211
3212 // Long processing consumers can cause returnBuffer timeout for shared stream
3213 // If that happens, cancel the buffer and send a buffer error to client
3214 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3215 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3216 // cancel the buffer
3217 camera3_stream_buffer_t sb = outputBuffers[i];
3218 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003219 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3220 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003221
3222 // notify client buffer error
3223 sp<NotificationListener> listener;
3224 {
3225 Mutex::Autolock l(mOutputLock);
3226 listener = mListener.promote();
3227 }
3228
3229 if (listener != nullptr) {
3230 CaptureResultExtras extras = inResultExtras;
3231 extras.errorStreamId = streamId;
3232 listener->notifyError(
3233 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3234 extras);
3235 }
3236 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003237 }
3238}
3239
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003240void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003241 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003242 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003243 mInFlightMap.removeItemsAt(idx, 1);
3244
3245 // Indicate idle inFlightMap to the status tracker
3246 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003247 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003248 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3249 // avoid a deadlock during reprocess requests.
3250 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003251 if (mStatusTracker != nullptr) {
3252 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3253 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003254 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003255 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003256}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003257
3258void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3259
3260 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3261 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3262
3263 nsecs_t sensorTimestamp = request.sensorTimestamp;
3264 nsecs_t shutterTimestamp = request.shutterTimestamp;
3265
3266 // Check if it's okay to remove the request from InFlightMap:
3267 // In the case of a successful request:
3268 // all input and output buffers, all result metadata, shutter callback
3269 // arrived.
3270 // In the case of a unsuccessful request:
3271 // all input and output buffers arrived.
3272 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003273 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003274 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003275 if (request.stillCapture) {
3276 ATRACE_ASYNC_END("still capture", frameNumber);
3277 }
3278
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003279 ATRACE_ASYNC_END("frame capture", frameNumber);
3280
Shuzhen Wang403044a2017-02-26 23:29:04 -08003281 // Sanity check - if sensor timestamp matches shutter timestamp in the
3282 // case of request having callback.
3283 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003284 sensorTimestamp != shutterTimestamp) {
3285 SET_ERR("sensor timestamp (%" PRId64
3286 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3287 sensorTimestamp, frameNumber, shutterTimestamp);
3288 }
3289
3290 // for an unsuccessful request, it may have pending output buffers to
3291 // return.
3292 assert(request.requestStatus != OK ||
3293 request.pendingOutputBuffers.size() == 0);
3294 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003295 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3296 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003297
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003298 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003299 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3300 }
3301
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003302 // Sanity check - if we have too many in-flight frames with long total inflight duration,
3303 // something has likely gone wrong. This might still be legit only if application send in
3304 // a long burst of long exposure requests.
3305 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3306 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3307 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3308 mInFlightMap.size(), mExpectedInflightDuration);
3309 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3310 kInFlightWarnLimitHighSpeed) {
3311 CLOGW("In-flight list too large for high speed configuration: %zu,"
3312 "total inflight duration %" PRIu64,
3313 mInFlightMap.size(), mExpectedInflightDuration);
3314 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003315 }
3316}
3317
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003318void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003319 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003320 { // First return buffers cached in mInFlightMap
3321 Mutex::Autolock l(mInFlightLock);
3322 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3323 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3324 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003325 request.pendingOutputBuffers.size(), 0,
3326 /*timestampIncreasing*/true, request.outputSurfaces,
3327 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003328 }
3329 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003330 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003331 }
3332
3333 // Then return all inflight buffers not returned by HAL
3334 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3335 mInterface->getInflightBufferKeys(&inflightKeys);
3336
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003337 // Inflight buffers for HAL buffer manager
3338 std::vector<uint64_t> inflightRequestBufferKeys;
3339 mInterface->getInflightRequestBufferKeys(&inflightRequestBufferKeys);
3340
3341 // (streamId, frameNumber, buffer_handle_t*) tuple for all inflight buffers.
3342 // frameNumber will be -1 for buffers from HAL buffer manager
3343 std::vector<std::tuple<int32_t, int32_t, buffer_handle_t*>> inflightBuffers;
3344 inflightBuffers.reserve(inflightKeys.size() + inflightRequestBufferKeys.size());
3345
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003346 for (auto& pair : inflightKeys) {
3347 int32_t frameNumber = pair.first;
3348 int32_t streamId = pair.second;
3349 buffer_handle_t* buffer;
3350 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3351 if (res != OK) {
3352 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3353 __FUNCTION__, frameNumber, streamId);
3354 continue;
3355 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003356 inflightBuffers.push_back(std::make_tuple(streamId, frameNumber, buffer));
3357 }
3358
3359 for (auto& bufferId : inflightRequestBufferKeys) {
3360 int32_t streamId = -1;
3361 buffer_handle_t* buffer = nullptr;
3362 status_t res = mInterface->popInflightRequestBuffer(bufferId, &buffer, &streamId);
3363 if (res != OK) {
3364 ALOGE("%s: cannot find in-flight buffer %" PRIu64, __FUNCTION__, bufferId);
3365 continue;
3366 }
3367 inflightBuffers.push_back(std::make_tuple(streamId, /*frameNumber*/-1, buffer));
3368 }
3369
3370 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3371 for (auto& tuple : inflightBuffers) {
3372 status_t res = OK;
3373 int32_t streamId = std::get<0>(tuple);
3374 int32_t frameNumber = std::get<1>(tuple);
3375 buffer_handle_t* buffer = std::get<2>(tuple);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003376
3377 camera3_stream_buffer_t streamBuffer;
3378 streamBuffer.buffer = buffer;
3379 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3380 streamBuffer.acquire_fence = -1;
3381 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003382
3383 // First check if the buffer belongs to deleted stream
3384 bool streamDeleted = false;
3385 for (auto& stream : mDeletedStreams) {
3386 if (streamId == stream->getId()) {
3387 streamDeleted = true;
3388 // Return buffer to deleted stream
3389 camera3_stream* halStream = stream->asHalStream();
3390 streamBuffer.stream = halStream;
3391 switch (halStream->stream_type) {
3392 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003393 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3394 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003395 if (res != OK) {
3396 ALOGE("%s: Can't return output buffer for frame %d to"
3397 " stream %d: %s (%d)", __FUNCTION__,
3398 frameNumber, streamId, strerror(-res), res);
3399 }
3400 break;
3401 case CAMERA3_STREAM_INPUT:
3402 res = stream->returnInputBuffer(streamBuffer);
3403 if (res != OK) {
3404 ALOGE("%s: Can't return input buffer for frame %d to"
3405 " stream %d: %s (%d)", __FUNCTION__,
3406 frameNumber, streamId, strerror(-res), res);
3407 }
3408 break;
3409 default: // Bi-direcitonal stream is deprecated
3410 ALOGE("%s: stream %d has unknown stream type %d",
3411 __FUNCTION__, streamId, halStream->stream_type);
3412 break;
3413 }
3414 break;
3415 }
3416 }
3417 if (streamDeleted) {
3418 continue;
3419 }
3420
3421 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003422 if (streamId == inputStreamId) {
3423 streamBuffer.stream = mInputStream->asHalStream();
3424 res = mInputStream->returnInputBuffer(streamBuffer);
3425 if (res != OK) {
3426 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003427 " stream %d: %s (%d)", __FUNCTION__,
3428 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003429 }
3430 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003431 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3432 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003433 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3434 continue;
3435 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003436 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003437 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3438 }
3439 }
3440}
3441
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003442void Camera3Device::insertResultLocked(CaptureResult *result,
3443 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003444 if (result == nullptr) return;
3445
Emilian Peev71c73a22017-03-21 16:35:51 +00003446 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3447 result->mMetadata.getAndLock());
3448 set_camera_metadata_vendor_id(meta, mVendorTagId);
3449 result->mMetadata.unlock(meta);
3450
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003451 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3452 (int32_t*)&frameNumber, 1) != OK) {
3453 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3454 return;
3455 }
3456
3457 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3458 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3459 return;
3460 }
3461
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003462 // Update vendor tag id for physical metadata
3463 for (auto& physicalMetadata : result->mPhysicalMetadatas) {
3464 camera_metadata_t *pmeta = const_cast<camera_metadata_t *>(
3465 physicalMetadata.mPhysicalCameraMetadata.getAndLock());
3466 set_camera_metadata_vendor_id(pmeta, mVendorTagId);
3467 physicalMetadata.mPhysicalCameraMetadata.unlock(pmeta);
3468 }
3469
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003470 // Valid result, insert into queue
3471 List<CaptureResult>::iterator queuedResult =
3472 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3473 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3474 ", burstId = %" PRId32, __FUNCTION__,
3475 queuedResult->mResultExtras.requestId,
3476 queuedResult->mResultExtras.frameNumber,
3477 queuedResult->mResultExtras.burstId);
3478
3479 mResultSignal.signal();
3480}
3481
3482
3483void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003484 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003485 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003486 Mutex::Autolock l(mOutputLock);
3487
3488 CaptureResult captureResult;
3489 captureResult.mResultExtras = resultExtras;
3490 captureResult.mMetadata = partialResult;
3491
Shuzhen Wang268a1362018-10-16 16:32:59 -07003492 // Fix up result metadata for monochrome camera.
3493 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3494 if (res != OK) {
3495 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3496 return;
3497 }
3498
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003499 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003500}
3501
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003502
3503void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3504 CaptureResultExtras &resultExtras,
3505 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003506 uint32_t frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003507 bool reprocess, bool zslStillCapture,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003508 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003509 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003510 if (pendingMetadata.isEmpty())
3511 return;
3512
3513 Mutex::Autolock l(mOutputLock);
3514
3515 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003516 if (reprocess) {
3517 if (frameNumber < mNextReprocessResultFrameNumber) {
3518 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003519 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003520 frameNumber, mNextReprocessResultFrameNumber);
3521 return;
3522 }
3523 mNextReprocessResultFrameNumber = frameNumber + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003524 } else if (zslStillCapture) {
3525 if (frameNumber < mNextZslStillResultFrameNumber) {
3526 SET_ERR("Out-of-order ZSL still capture result metadata submitted! "
3527 "(got frame number %d, expecting %d)",
3528 frameNumber, mNextZslStillResultFrameNumber);
3529 return;
3530 }
3531 mNextZslStillResultFrameNumber = frameNumber + 1;
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003532 } else {
3533 if (frameNumber < mNextResultFrameNumber) {
3534 SET_ERR("Out-of-order capture result metadata submitted! "
3535 "(got frame number %d, expecting %d)",
3536 frameNumber, mNextResultFrameNumber);
3537 return;
3538 }
3539 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003540 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003541
3542 CaptureResult captureResult;
3543 captureResult.mResultExtras = resultExtras;
3544 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003545 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003546
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003547 // Append any previous partials to form a complete result
3548 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3549 captureResult.mMetadata.append(collectedPartialResult);
3550 }
3551
3552 captureResult.mMetadata.sort();
3553
3554 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003555 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3556 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003557 SET_ERR("No timestamp provided by HAL for frame %d!",
3558 frameNumber);
3559 return;
3560 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003561 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3562 camera_metadata_entry timestamp =
3563 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3564 if (timestamp.count == 0) {
3565 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3566 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3567 return;
3568 }
3569 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003570
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003571 // Fix up some result metadata to account for HAL-level distortion correction
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003572 status_t res =
3573 mDistortionMappers[mId.c_str()].correctCaptureResult(&captureResult.mMetadata);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003574 if (res != OK) {
3575 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3576 frameNumber, strerror(res), res);
3577 return;
3578 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003579 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3580 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3581 if (mDistortionMappers.find(cameraId8.c_str()) == mDistortionMappers.end()) {
3582 continue;
3583 }
3584 res = mDistortionMappers[cameraId8.c_str()].correctCaptureResult(
3585 &physicalMetadata.mPhysicalCameraMetadata);
3586 if (res != OK) {
3587 SET_ERR("Unable to correct physical capture result metadata for frame %d: %s (%d)",
3588 frameNumber, strerror(res), res);
3589 return;
3590 }
3591 }
3592
Shuzhen Wang268a1362018-10-16 16:32:59 -07003593 // Fix up result metadata for monochrome camera.
3594 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3595 if (res != OK) {
3596 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3597 return;
3598 }
3599 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3600 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3601 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3602 physicalMetadata.mPhysicalCameraMetadata);
3603 if (res != OK) {
3604 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3605 return;
3606 }
3607 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003608
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003609 std::unordered_map<std::string, CameraMetadata> monitoredPhysicalMetadata;
3610 for (auto& m : physicalMetadatas) {
3611 monitoredPhysicalMetadata.emplace(String8(m.mPhysicalCameraId).string(),
3612 CameraMetadata(m.mPhysicalCameraMetadata));
3613 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003614 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003615 frameNumber, timestamp.data.i64[0], captureResult.mMetadata,
3616 monitoredPhysicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003617
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003618 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003619}
3620
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003621/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003622 * Camera HAL device callback methods
3623 */
3624
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003625void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003626 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003627
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003628 status_t res;
3629
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003630 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003631 if (result->result == NULL && result->num_output_buffers == 0 &&
3632 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003633 SET_ERR("No result data provided by HAL for frame %d",
3634 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003635 return;
3636 }
Zhijun He204e3292014-07-14 17:09:23 -07003637
Zhijun He204e3292014-07-14 17:09:23 -07003638 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003639 result->result != NULL &&
3640 result->partial_result != 1) {
3641 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3642 " if partial result is not supported",
3643 frameNumber, result->partial_result);
3644 return;
3645 }
3646
3647 bool isPartialResult = false;
3648 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003649 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003650
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003651 // Get shutter timestamp and resultExtras from list of in-flight requests,
3652 // where it was added by the shutter notification for this frame. If the
3653 // shutter timestamp isn't received yet, append the output buffers to the
3654 // in-flight request and they will be returned when the shutter timestamp
3655 // arrives. Update the in-flight status and remove the in-flight entry if
3656 // all result data and shutter timestamp have been received.
3657 nsecs_t shutterTimestamp = 0;
3658
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003659 {
3660 Mutex::Autolock l(mInFlightLock);
3661 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3662 if (idx == NAME_NOT_FOUND) {
3663 SET_ERR("Unknown frame number for capture result: %d",
3664 frameNumber);
3665 return;
3666 }
3667 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003668 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3669 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003670 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003671 __FUNCTION__, request.resultExtras.requestId,
3672 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003673 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003674 // Always update the partial count to the latest one if it's not 0
3675 // (buffers only). When framework aggregates adjacent partial results
3676 // into one, the latest partial count will be used.
3677 if (result->partial_result != 0)
3678 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003679
3680 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003681 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003682 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3683 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3684 " the range of [1, %d] when metadata is included in the result",
3685 frameNumber, result->partial_result, mNumPartialResults);
3686 return;
3687 }
3688 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003689 if (isPartialResult && result->num_physcam_metadata) {
3690 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3691 " physical camera result", frameNumber);
3692 return;
3693 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003694 if (isPartialResult) {
3695 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003696 }
3697
Shuzhen Wang4a472662017-02-26 23:29:04 -08003698 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003699 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003700 sendPartialCaptureResult(result->result, request.resultExtras,
3701 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003702 }
3703 }
3704
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003705 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003706 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003707
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003708 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003709 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003710 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
Shuzhen Wang468dbb82019-07-31 11:35:33 -07003711 SET_ERR("Expected physical Camera metadata count %d not equal to actual count %d",
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003712 request.physicalCameraIds.size(), result->num_physcam_metadata);
3713 return;
3714 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003715 if (request.haveResultMetadata) {
3716 SET_ERR("Called multiple times with metadata for frame %d",
3717 frameNumber);
3718 return;
3719 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003720 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3721 String8 physicalId(result->physcam_ids[i]);
3722 std::set<String8>::iterator cameraIdIter =
3723 request.physicalCameraIds.find(physicalId);
3724 if (cameraIdIter != request.physicalCameraIds.end()) {
3725 request.physicalCameraIds.erase(cameraIdIter);
3726 } else {
3727 SET_ERR("Total result for frame %d has already returned for camera %s",
3728 frameNumber, physicalId.c_str());
3729 return;
3730 }
3731 }
Zhijun He204e3292014-07-14 17:09:23 -07003732 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003733 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003734 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003735 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003736 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003737 request.haveResultMetadata = true;
3738 }
3739
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003740 uint32_t numBuffersReturned = result->num_output_buffers;
3741 if (result->input_buffer != NULL) {
3742 if (hasInputBufferInRequest) {
3743 numBuffersReturned += 1;
3744 } else {
3745 ALOGW("%s: Input buffer should be NULL if there is no input"
3746 " buffer sent in the request",
3747 __FUNCTION__);
3748 }
3749 }
3750 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003751 if (request.numBuffersLeft < 0) {
3752 SET_ERR("Too many buffers returned for frame %d",
3753 frameNumber);
3754 return;
3755 }
3756
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003757 camera_metadata_ro_entry_t entry;
3758 res = find_camera_metadata_ro_entry(result->result,
3759 ANDROID_SENSOR_TIMESTAMP, &entry);
3760 if (res == OK && entry.count == 1) {
3761 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003762 }
3763
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003764 // If shutter event isn't received yet, append the output buffers to
3765 // the in-flight request. Otherwise, return the output buffers to
3766 // streams.
3767 if (shutterTimestamp == 0) {
3768 request.pendingOutputBuffers.appendArray(result->output_buffers,
3769 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003770 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003771 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003772 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003773 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3774 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003775 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003776
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003777 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003778 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3779 CameraMetadata physicalMetadata;
3780 physicalMetadata.append(result->physcam_metadata[i]);
3781 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3782 physicalMetadata});
3783 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003784 if (shutterTimestamp == 0) {
3785 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003786 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003787 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003788 CameraMetadata metadata;
3789 metadata = result->result;
3790 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003791 collectedPartialResult, frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003792 hasInputBufferInRequest, request.zslCapture && request.stillCapture,
3793 request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003794 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003795 }
3796
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003797 removeInFlightRequestIfReadyLocked(idx);
3798 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003799
Zhijun Hef0d962a2014-06-30 10:24:11 -07003800 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003801 if (hasInputBufferInRequest) {
3802 Camera3Stream *stream =
3803 Camera3Stream::cast(result->input_buffer->stream);
3804 res = stream->returnInputBuffer(*(result->input_buffer));
3805 // Note: stream may be deallocated at this point, if this buffer was the
3806 // last reference to it.
3807 if (res != OK) {
3808 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3809 " its stream:%s (%d)", __FUNCTION__,
3810 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003811 }
3812 } else {
3813 ALOGW("%s: Input buffer should be NULL if there is no input"
3814 " buffer sent in the request, skipping input buffer return.",
3815 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003816 }
3817 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003818}
3819
3820void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003821 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003822 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003823 {
3824 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003825 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003826 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003827
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003828 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003829 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003830 return;
3831 }
3832
3833 switch (msg->type) {
3834 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003835 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003836 break;
3837 }
3838 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003839 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003840 break;
3841 }
3842 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003843 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003844 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003845 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003846}
3847
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003848void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003849 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003850 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003851 // Map camera HAL error codes to ICameraDeviceCallback error codes
3852 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003853 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003854 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003855 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003856 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003857 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003858 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003859 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003860 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003861 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003862 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003863 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003864 };
3865
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003866 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003867 ((msg.error_code >= 0) &&
3868 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3869 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003870 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003871
3872 int streamId = 0;
Emilian Peevedec62d2019-03-19 17:59:24 -07003873 String16 physicalCameraId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003874 if (msg.error_stream != NULL) {
3875 Camera3Stream *stream =
3876 Camera3Stream::cast(msg.error_stream);
3877 streamId = stream->getId();
Emilian Peevedec62d2019-03-19 17:59:24 -07003878 physicalCameraId = String16(stream->physicalCameraId());
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003879 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003880 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3881 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003882 streamId, msg.error_code);
3883
3884 CaptureResultExtras resultExtras;
3885 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003886 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003887 // SET_ERR calls notifyError
3888 SET_ERR("Camera HAL reported serious device error");
3889 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003890 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3891 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3892 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003893 {
3894 Mutex::Autolock l(mInFlightLock);
3895 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3896 if (idx >= 0) {
3897 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3898 r.requestStatus = msg.error_code;
3899 resultExtras = r.resultExtras;
Emilian Peevedec62d2019-03-19 17:59:24 -07003900 bool logicalDeviceResultError = false;
3901 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3902 errorCode) {
3903 if (physicalCameraId.size() > 0) {
3904 String8 cameraId(physicalCameraId);
Shuzhen Wang468dbb82019-07-31 11:35:33 -07003905 auto iter = r.physicalCameraIds.find(cameraId);
3906 if (iter == r.physicalCameraIds.end()) {
Emilian Peevedec62d2019-03-19 17:59:24 -07003907 ALOGE("%s: Reported result failure for physical camera device: %s "
3908 " which is not part of the respective request!",
3909 __FUNCTION__, cameraId.string());
3910 break;
3911 }
Shuzhen Wang468dbb82019-07-31 11:35:33 -07003912 r.physicalCameraIds.erase(iter);
Emilian Peevedec62d2019-03-19 17:59:24 -07003913 resultExtras.errorPhysicalCameraId = physicalCameraId;
3914 } else {
3915 logicalDeviceResultError = true;
3916 }
3917 }
3918
3919 if (logicalDeviceResultError
Shuzhen Wang20f57342017-08-24 15:39:05 -07003920 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3921 errorCode) {
3922 r.skipResultMetadata = true;
3923 }
Emilian Peevedec62d2019-03-19 17:59:24 -07003924 if (logicalDeviceResultError) {
Emilian Peevba0fac32017-03-30 09:05:34 +01003925 // In case of missing result check whether the buffers
3926 // returned. If they returned, then remove inflight
3927 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003928 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3929 // otherwise we are depending on HAL to send the buffers back after
3930 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003931 removeInFlightRequestIfReadyLocked(idx);
3932 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003933 } else {
3934 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003935 ALOGE("Camera %s: %s: cannot find in-flight request on "
3936 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003937 resultExtras.frameNumber);
3938 }
3939 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003940 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003941 if (listener != NULL) {
3942 listener->notifyError(errorCode, resultExtras);
3943 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003944 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003945 }
3946 break;
3947 default:
3948 // SET_ERR calls notifyError
3949 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3950 break;
3951 }
3952}
3953
3954void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003955 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003956 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003957 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003958
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003959 // Set timestamp for the request in the in-flight tracking
3960 // and get the request ID to send upstream
3961 {
3962 Mutex::Autolock l(mInFlightLock);
3963 idx = mInFlightMap.indexOfKey(msg.frame_number);
3964 if (idx >= 0) {
3965 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003966
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003967 // Verify ordering of shutter notifications
3968 {
3969 Mutex::Autolock l(mOutputLock);
3970 // TODO: need to track errors for tighter bounds on expected frame number.
3971 if (r.hasInputBuffer) {
3972 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003973 SET_ERR("Reprocess shutter notification out-of-order. Expected "
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003974 "notification for frame %d, got frame %d",
3975 mNextReprocessShutterFrameNumber, msg.frame_number);
3976 return;
3977 }
3978 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003979 } else if (r.zslCapture && r.stillCapture) {
3980 if (msg.frame_number < mNextZslStillShutterFrameNumber) {
3981 SET_ERR("ZSL still capture shutter notification out-of-order. Expected "
3982 "notification for frame %d, got frame %d",
3983 mNextZslStillShutterFrameNumber, msg.frame_number);
3984 return;
3985 }
3986 mNextZslStillShutterFrameNumber = msg.frame_number + 1;
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003987 } else {
3988 if (msg.frame_number < mNextShutterFrameNumber) {
3989 SET_ERR("Shutter notification out-of-order. Expected "
3990 "notification for frame %d, got frame %d",
3991 mNextShutterFrameNumber, msg.frame_number);
3992 return;
3993 }
3994 mNextShutterFrameNumber = msg.frame_number + 1;
3995 }
3996 }
3997
Shuzhen Wang4a472662017-02-26 23:29:04 -08003998 r.shutterTimestamp = msg.timestamp;
3999 if (r.hasCallback) {
4000 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004001 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004002 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08004003 // Call listener, if any
4004 if (listener != NULL) {
4005 listener->notifyShutter(r.resultExtras, msg.timestamp);
4006 }
4007 // send pending result and buffers
4008 sendCaptureResult(r.pendingMetadata, r.resultExtras,
4009 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07004010 r.hasInputBuffer, r.zslCapture && r.stillCapture,
4011 r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004012 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004013 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004014 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004015 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
4016 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004017 r.pendingOutputBuffers.clear();
4018
4019 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004020 }
4021 }
4022 if (idx < 0) {
4023 SET_ERR("Shutter notification for non-existent frame number %d",
4024 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004025 }
4026}
4027
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004028CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07004029 ALOGV("%s", __FUNCTION__);
4030
Igor Murashkin1e479c02013-09-06 16:55:14 -07004031 CameraMetadata retVal;
4032
4033 if (mRequestThread != NULL) {
4034 retVal = mRequestThread->getLatestRequest();
4035 }
4036
Igor Murashkin1e479c02013-09-06 16:55:14 -07004037 return retVal;
4038}
4039
Jianing Weicb0652e2014-03-12 18:29:36 -07004040
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004041void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004042 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
4043 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
4044
4045 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
4046 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004047}
4048
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004049/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004050 * HalInterface inner class methods
4051 */
4052
Yifan Hongf79b5542017-04-11 14:44:25 -07004053Camera3Device::HalInterface::HalInterface(
4054 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004055 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004056 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004057 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004058 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08004059 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004060 mIsReconfigurationQuerySupported(true),
4061 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004062 // Check with hardware service manager if we can downcast these interfaces
4063 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004064 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
4065 if (castResult_3_6.isOk()) {
4066 mHidlSession_3_6 = castResult_3_6;
4067 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004068 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
4069 if (castResult_3_5.isOk()) {
4070 mHidlSession_3_5 = castResult_3_5;
4071 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004072 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4073 if (castResult_3_4.isOk()) {
4074 mHidlSession_3_4 = castResult_3_4;
4075 }
4076 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
4077 if (castResult_3_3.isOk()) {
4078 mHidlSession_3_3 = castResult_3_3;
4079 }
4080}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004081
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004082Camera3Device::HalInterface::HalInterface() :
4083 mUseHalBufManager(false),
4084 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004085
4086Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004087 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004088 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004089 mUseHalBufManager(other.mUseHalBufManager),
4090 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004091
4092bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004093 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004094}
4095
4096void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004097 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00004098 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00004099 mHidlSession_3_4.clear();
4100 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004101 mHidlSession.clear();
4102}
4103
4104status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
4105 camera3_request_template_t templateId,
4106 /*out*/ camera_metadata_t **requestTemplate) {
4107 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
4108 if (!valid()) return INVALID_OPERATION;
4109 status_t res = OK;
4110
Emilian Peev31abd0a2017-05-11 18:37:46 +01004111 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004112
4113 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01004114 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004115 status = s;
4116 if (status == common::V1_0::Status::OK) {
4117 const camera_metadata *r =
4118 reinterpret_cast<const camera_metadata_t*>(request.data());
4119 size_t expectedSize = request.size();
4120 int ret = validate_camera_metadata_structure(r, &expectedSize);
4121 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
4122 *requestTemplate = clone_camera_metadata(r);
4123 if (*requestTemplate == nullptr) {
4124 ALOGE("%s: Unable to clone camera metadata received from HAL",
4125 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004126 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004127 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004128 } else {
4129 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
4130 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004131 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004132 }
4133 };
4134 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004135 RequestTemplate id;
4136 switch (templateId) {
4137 case CAMERA3_TEMPLATE_PREVIEW:
4138 id = RequestTemplate::PREVIEW;
4139 break;
4140 case CAMERA3_TEMPLATE_STILL_CAPTURE:
4141 id = RequestTemplate::STILL_CAPTURE;
4142 break;
4143 case CAMERA3_TEMPLATE_VIDEO_RECORD:
4144 id = RequestTemplate::VIDEO_RECORD;
4145 break;
4146 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
4147 id = RequestTemplate::VIDEO_SNAPSHOT;
4148 break;
4149 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
4150 id = RequestTemplate::ZERO_SHUTTER_LAG;
4151 break;
4152 case CAMERA3_TEMPLATE_MANUAL:
4153 id = RequestTemplate::MANUAL;
4154 break;
4155 default:
4156 // Unknown template ID, or this HAL is too old to support it
4157 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004158 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004159 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004160
Emilian Peev31abd0a2017-05-11 18:37:46 +01004161 if (!err.isOk()) {
4162 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4163 res = DEAD_OBJECT;
4164 } else {
4165 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004166 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004167
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004168 return res;
4169}
4170
Emilian Peev4ec17882019-01-24 17:16:58 -08004171bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4172 CameraMetadata& newSessionParams) {
4173 // We do reconfiguration by default;
4174 bool ret = true;
4175 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4176 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4177 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4178 oldSessionParams.getAndLock());
4179 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4180 newSessionParams.getAndLock());
4181 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4182 get_camera_metadata_size(oldSessioMeta));
4183 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4184 get_camera_metadata_size(newSessioMeta));
4185 hardware::camera::common::V1_0::Status callStatus;
4186 bool required;
4187 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4188 bool requiredFlag) {
4189 callStatus = s;
4190 required = requiredFlag;
4191 };
4192 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4193 oldSessionParams.unlock(oldSessioMeta);
4194 newSessionParams.unlock(newSessioMeta);
4195 if (err.isOk()) {
4196 switch (callStatus) {
4197 case hardware::camera::common::V1_0::Status::OK:
4198 ret = required;
4199 break;
4200 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4201 mIsReconfigurationQuerySupported = false;
4202 ret = true;
4203 break;
4204 default:
4205 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4206 ret = true;
4207 }
4208 } else {
4209 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4210 ret = true;
4211 }
4212 }
4213
4214 return ret;
4215}
4216
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004217status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004218 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004219 ATRACE_NAME("CameraHal::configureStreams");
4220 if (!valid()) return INVALID_OPERATION;
4221 status_t res = OK;
4222
Emilian Peev31abd0a2017-05-11 18:37:46 +01004223 // Convert stream config to HIDL
4224 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004225 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4226 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4227 requestedConfiguration3_2.streams.resize(config->num_streams);
4228 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004229 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004230 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4231 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004232 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004233
Emilian Peev31abd0a2017-05-11 18:37:46 +01004234 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4235 cam3stream->setBufferFreedListener(this);
4236 int streamId = cam3stream->getId();
4237 StreamType streamType;
4238 switch (src->stream_type) {
4239 case CAMERA3_STREAM_OUTPUT:
4240 streamType = StreamType::OUTPUT;
4241 break;
4242 case CAMERA3_STREAM_INPUT:
4243 streamType = StreamType::INPUT;
4244 break;
4245 default:
4246 ALOGE("%s: Stream %d: Unsupported stream type %d",
4247 __FUNCTION__, streamId, config->streams[i]->stream_type);
4248 return BAD_VALUE;
4249 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004250 dst3_2.id = streamId;
4251 dst3_2.streamType = streamType;
4252 dst3_2.width = src->width;
4253 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004254 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004255 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07004256 // For HidlSession version 3.5 or newer, the format and dataSpace sent
4257 // to HAL are original, not the overriden ones.
4258 if (mHidlSession_3_5 != nullptr) {
4259 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
4260 cam3stream->getOriginalFormat() : src->format);
4261 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
4262 cam3stream->getOriginalDataSpace() : src->data_space);
4263 } else {
4264 dst3_2.format = mapToPixelFormat(src->format);
4265 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4266 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004267 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004268 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004269 if (src->physical_camera_id != nullptr) {
4270 dst3_4.physicalCameraId = src->physical_camera_id;
4271 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004272
4273 activeStreams.insert(streamId);
4274 // Create Buffer ID map if necessary
4275 if (mBufferIdMaps.count(streamId) == 0) {
4276 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4277 }
4278 }
4279 // remove BufferIdMap for deleted streams
4280 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4281 int streamId = it->first;
4282 bool active = activeStreams.count(streamId) > 0;
4283 if (!active) {
4284 it = mBufferIdMaps.erase(it);
4285 } else {
4286 ++it;
4287 }
4288 }
4289
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004290 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004291 res = mapToStreamConfigurationMode(
4292 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004293 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004294 if (res != OK) {
4295 return res;
4296 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004297 requestedConfiguration3_2.operationMode = operationMode;
4298 requestedConfiguration3_4.operationMode = operationMode;
4299 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004300 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4301 get_camera_metadata_size(sessionParams));
4302
Emilian Peev31abd0a2017-05-11 18:37:46 +01004303 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004304 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004305 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004306 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004307
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004308 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004309 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4310 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004311 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004312 };
4313
4314 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4315 (hardware::Return<void>& err) -> status_t {
4316 if (!err.isOk()) {
4317 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4318 return DEAD_OBJECT;
4319 }
4320 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4321 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4322 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4323 }
4324 return OK;
4325 };
4326
Shuzhen Wang92653952019-05-07 15:11:43 -07004327 // See which version of HAL we have
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004328 if (mHidlSession_3_5 != nullptr) {
4329 ALOGV("%s: v3.5 device found", __FUNCTION__);
4330 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4331 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4332 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4333 auto err = mHidlSession_3_5->configureStreams_3_5(
4334 requestedConfiguration3_5, configStream34Cb);
4335 res = postprocConfigStream34(err);
4336 if (res != OK) {
4337 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004338 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004339 } else if (mHidlSession_3_4 != nullptr) {
4340 // We do; use v3.4 for the call
4341 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004342 auto err = mHidlSession_3_4->configureStreams_3_4(
4343 requestedConfiguration3_4, configStream34Cb);
4344 res = postprocConfigStream34(err);
4345 if (res != OK) {
4346 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004347 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004348 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004349 // We do; use v3.3 for the call
4350 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004351 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004352 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004353 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004354 finalConfiguration = halConfiguration;
4355 status = s;
4356 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004357 if (!err.isOk()) {
4358 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4359 return DEAD_OBJECT;
4360 }
4361 } else {
4362 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4363 ALOGV("%s: v3.2 device found", __FUNCTION__);
4364 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004365 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004366 [&status, &finalConfiguration_3_2]
4367 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4368 finalConfiguration_3_2 = halConfiguration;
4369 status = s;
4370 });
4371 if (!err.isOk()) {
4372 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4373 return DEAD_OBJECT;
4374 }
4375 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4376 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4377 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4378 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004379 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004380 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004381 }
4382
4383 if (status != common::V1_0::Status::OK ) {
4384 return CameraProviderManager::mapToStatusT(status);
4385 }
4386
4387 // And convert output stream configuration from HIDL
4388
4389 for (size_t i = 0; i < config->num_streams; i++) {
4390 camera3_stream_t *dst = config->streams[i];
4391 int streamId = Camera3Stream::cast(dst)->getId();
4392
4393 // Start scan at i, with the assumption that the stream order matches
4394 size_t realIdx = i;
4395 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004396 size_t halStreamCount = finalConfiguration.streams.size();
4397 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004398 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004399 found = true;
4400 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004401 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004402 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004403 }
4404 if (!found) {
4405 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4406 __FUNCTION__, streamId);
4407 return INVALID_OPERATION;
4408 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004409 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004410
Emilian Peev710c1422017-08-30 11:19:38 +01004411 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004412 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4413 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4414
Yin-Chia Yeh90667662019-07-01 15:45:00 -07004415 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07004416 dstStream->setFormatOverride(false);
4417 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004418 if (dst->format != overrideFormat) {
4419 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4420 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004421 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004422 if (dst->data_space != overrideDataSpace) {
4423 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4424 streamId, dst->format);
4425 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004426 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07004427 bool needFormatOverride =
4428 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
4429 bool needDataspaceOverride =
4430 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004431 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07004432 dstStream->setFormatOverride(needFormatOverride);
4433 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004434 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004435 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004436 }
4437
Emilian Peev31abd0a2017-05-11 18:37:46 +01004438 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004439 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004440 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004441 __FUNCTION__, streamId);
4442 return INVALID_OPERATION;
4443 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004444 dstStream->setUsage(
4445 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004446 } else {
4447 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004448 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004449 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4450 __FUNCTION__, streamId);
4451 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004452 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004453 dstStream->setUsage(
4454 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004455 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004456 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004457 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004458
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004459 return res;
4460}
4461
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004462status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004463 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004464 /*out*/std::vector<native_handle_t*>* handlesCreated,
4465 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004466 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004467 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
4468 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
4469 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004470 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004471 }
4472
4473 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004474
4475 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004476
4477 {
4478 std::lock_guard<std::mutex> lock(mInflightLock);
4479 if (request->input_buffer != nullptr) {
4480 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4481 buffer_handle_t buf = *(request->input_buffer->buffer);
4482 auto pair = getBufferId(buf, streamId);
4483 bool isNewBuffer = pair.first;
4484 uint64_t bufferId = pair.second;
4485 captureRequest->inputBuffer.streamId = streamId;
4486 captureRequest->inputBuffer.bufferId = bufferId;
4487 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4488 captureRequest->inputBuffer.status = BufferStatus::OK;
4489 native_handle_t *acquireFence = nullptr;
4490 if (request->input_buffer->acquire_fence != -1) {
4491 acquireFence = native_handle_create(1,0);
4492 acquireFence->data[0] = request->input_buffer->acquire_fence;
4493 handlesCreated->push_back(acquireFence);
4494 }
4495 captureRequest->inputBuffer.acquireFence = acquireFence;
4496 captureRequest->inputBuffer.releaseFence = nullptr;
4497
4498 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004499 request->input_buffer->buffer);
4500 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004501 } else {
4502 captureRequest->inputBuffer.streamId = -1;
4503 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4504 }
4505
4506 captureRequest->outputBuffers.resize(request->num_output_buffers);
4507 for (size_t i = 0; i < request->num_output_buffers; i++) {
4508 const camera3_stream_buffer_t *src = request->output_buffers + i;
4509 StreamBuffer &dst = captureRequest->outputBuffers[i];
4510 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004511 if (src->buffer != nullptr) {
4512 buffer_handle_t buf = *(src->buffer);
4513 auto pair = getBufferId(buf, streamId);
4514 bool isNewBuffer = pair.first;
4515 dst.bufferId = pair.second;
4516 dst.buffer = isNewBuffer ? buf : nullptr;
4517 native_handle_t *acquireFence = nullptr;
4518 if (src->acquire_fence != -1) {
4519 acquireFence = native_handle_create(1,0);
4520 acquireFence->data[0] = src->acquire_fence;
4521 handlesCreated->push_back(acquireFence);
4522 }
4523 dst.acquireFence = acquireFence;
4524 } else if (mUseHalBufManager) {
4525 // HAL buffer management path
4526 dst.bufferId = BUFFER_ID_NO_BUFFER;
4527 dst.buffer = nullptr;
4528 dst.acquireFence = nullptr;
4529 } else {
4530 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4531 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004532 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004533 dst.streamId = streamId;
4534 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004535 dst.releaseFence = nullptr;
4536
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004537 // Output buffers are empty when using HAL buffer manager
4538 if (!mUseHalBufManager) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004539 pushInflightBufferLocked(captureRequest->frameNumber, streamId, src->buffer);
4540 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004541 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004542 }
4543 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004544 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004545}
4546
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004547void Camera3Device::HalInterface::cleanupNativeHandles(
4548 std::vector<native_handle_t*> *handles, bool closeFd) {
4549 if (handles == nullptr) {
4550 return;
4551 }
4552 if (closeFd) {
4553 for (auto& handle : *handles) {
4554 native_handle_close(handle);
4555 }
4556 }
4557 for (auto& handle : *handles) {
4558 native_handle_delete(handle);
4559 }
4560 handles->clear();
4561 return;
4562}
4563
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004564status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4565 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4566 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4567 if (!valid()) return INVALID_OPERATION;
4568
Emilian Peevaebbe412018-01-15 13:53:24 +00004569 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4570 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4571 if (castResult_3_4.isOk()) {
4572 hidlSession_3_4 = castResult_3_4;
4573 }
4574
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004575 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004576 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004577 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004578 if (hidlSession_3_4 != nullptr) {
4579 captureRequests_3_4.resize(batchSize);
4580 } else {
4581 captureRequests.resize(batchSize);
4582 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004583 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004584 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004585
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004586 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004587 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004588 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004589 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004590 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00004591 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004592 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
4593 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004594 }
4595 if (res != OK) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004596 popInflightBuffers(inflightBuffers);
4597 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004598 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004599 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004600 }
4601
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004602 std::vector<device::V3_2::BufferCache> cachesToRemove;
4603 {
4604 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4605 for (auto& pair : mFreedBuffers) {
4606 // The stream might have been removed since onBufferFreed
4607 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4608 cachesToRemove.push_back({pair.first, pair.second});
4609 }
4610 }
4611 mFreedBuffers.clear();
4612 }
4613
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004614 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4615 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004616
4617 // Write metadata to FMQ.
4618 for (size_t i = 0; i < batchSize; i++) {
4619 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004620 device::V3_2::CaptureRequest* captureRequest;
4621 if (hidlSession_3_4 != nullptr) {
4622 captureRequest = &captureRequests_3_4[i].v3_2;
4623 } else {
4624 captureRequest = &captureRequests[i];
4625 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004626
4627 if (request->settings != nullptr) {
4628 size_t settingsSize = get_camera_metadata_size(request->settings);
4629 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4630 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4631 captureRequest->settings.resize(0);
4632 captureRequest->fmqSettingsSize = settingsSize;
4633 } else {
4634 if (mRequestMetadataQueue != nullptr) {
4635 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4636 }
4637 captureRequest->settings.setToExternal(
4638 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4639 get_camera_metadata_size(request->settings));
4640 captureRequest->fmqSettingsSize = 0u;
4641 }
4642 } else {
4643 // A null request settings maps to a size-0 CameraMetadata
4644 captureRequest->settings.resize(0);
4645 captureRequest->fmqSettingsSize = 0u;
4646 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004647
4648 if (hidlSession_3_4 != nullptr) {
4649 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4650 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004651 if (request->physcam_settings != nullptr) {
4652 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4653 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4654 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4655 settingsSize)) {
4656 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4657 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4658 settingsSize;
4659 } else {
4660 if (mRequestMetadataQueue != nullptr) {
4661 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4662 }
4663 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4664 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4665 request->physcam_settings[j])),
4666 get_camera_metadata_size(request->physcam_settings[j]));
4667 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004668 }
Emilian Peev00420d22018-02-05 21:33:13 +00004669 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004670 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004671 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004672 }
4673 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4674 request->physcam_id[j];
4675 }
4676 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004677 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004678
4679 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004680 auto resultCallback =
4681 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4682 status = s;
4683 *numRequestProcessed = n;
4684 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004685 if (hidlSession_3_4 != nullptr) {
4686 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004687 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004688 } else {
4689 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004690 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004691 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004692 if (!err.isOk()) {
4693 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004694 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004695 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004696
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004697 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4698 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4699 __FUNCTION__, *numRequestProcessed, batchSize);
4700 status = common::V1_0::Status::INTERNAL_ERROR;
4701 }
4702
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004703 res = CameraProviderManager::mapToStatusT(status);
4704 if (res == OK) {
4705 if (mHidlSession->isRemote()) {
4706 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
4707 // sent to camera HAL processes)
4708 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
4709 } else {
4710 // In passthrough mode the FDs are now owned by HAL
4711 cleanupNativeHandles(&handlesCreated);
4712 }
4713 } else {
4714 popInflightBuffers(inflightBuffers);
4715 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004716 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004717 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004718}
4719
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004720status_t Camera3Device::HalInterface::flush() {
4721 ATRACE_NAME("CameraHal::flush");
4722 if (!valid()) return INVALID_OPERATION;
4723 status_t res = OK;
4724
Emilian Peev31abd0a2017-05-11 18:37:46 +01004725 auto err = mHidlSession->flush();
4726 if (!err.isOk()) {
4727 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4728 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004729 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004730 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004731 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004732
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004733 return res;
4734}
4735
Emilian Peev31abd0a2017-05-11 18:37:46 +01004736status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004737 ATRACE_NAME("CameraHal::dump");
4738 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004739
Emilian Peev31abd0a2017-05-11 18:37:46 +01004740 // Handled by CameraProviderManager::dump
4741
4742 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004743}
4744
4745status_t Camera3Device::HalInterface::close() {
4746 ATRACE_NAME("CameraHal::close()");
4747 if (!valid()) return INVALID_OPERATION;
4748 status_t res = OK;
4749
Emilian Peev31abd0a2017-05-11 18:37:46 +01004750 auto err = mHidlSession->close();
4751 // Interface will be dead shortly anyway, so don't log errors
4752 if (!err.isOk()) {
4753 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004754 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004755
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004756 return res;
4757}
4758
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004759void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4760 ATRACE_NAME("CameraHal::signalPipelineDrain");
4761 if (!valid() || mHidlSession_3_5 == nullptr) {
4762 ALOGE("%s called on invalid camera!", __FUNCTION__);
4763 return;
4764 }
4765
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004766 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004767 if (!err.isOk()) {
4768 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4769 return;
4770 }
4771}
4772
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004773status_t Camera3Device::HalInterface::switchToOffline(
4774 const std::vector<int32_t>& streamsToKeep,
4775 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
4776 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession) {
4777 ATRACE_NAME("CameraHal::switchToOffline");
4778 if (!valid() || mHidlSession_3_6 == nullptr) {
4779 ALOGE("%s called on invalid camera!", __FUNCTION__);
4780 return INVALID_OPERATION;
4781 }
4782
4783 if (offlineSessionInfo == nullptr || offlineSession == nullptr) {
4784 ALOGE("%s: offlineSessionInfo and offlineSession must not be null!", __FUNCTION__);
4785 return INVALID_OPERATION;
4786 }
4787
4788 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4789
4790 auto resultCallback =
4791 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4792 status = s;
4793 *offlineSessionInfo = info;
4794 *offlineSession = session;
4795 };
4796 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4797
4798 if (!err.isOk()) {
4799 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4800 return DEAD_OBJECT;
4801 }
4802 return CameraProviderManager::mapToStatusT(status);
4803}
4804
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004805void Camera3Device::HalInterface::getInflightBufferKeys(
4806 std::vector<std::pair<int32_t, int32_t>>* out) {
4807 std::lock_guard<std::mutex> lock(mInflightLock);
4808 out->clear();
4809 out->reserve(mInflightBufferMap.size());
4810 for (auto& pair : mInflightBufferMap) {
4811 uint64_t key = pair.first;
4812 int32_t streamId = key & 0xFFFFFFFF;
4813 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4814 out->push_back(std::make_pair(frameNumber, streamId));
4815 }
4816 return;
4817}
4818
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004819void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4820 std::vector<uint64_t>* out) {
4821 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4822 out->clear();
4823 out->reserve(mRequestedBuffers.size());
4824 for (auto& pair : mRequestedBuffers) {
4825 out->push_back(pair.first);
4826 }
4827 return;
4828}
4829
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004830status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004831 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004832 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004833 mInflightBufferMap[key] = buffer;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004834 return OK;
4835}
4836
4837status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004838 int32_t frameNumber, int32_t streamId,
4839 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004840 std::lock_guard<std::mutex> lock(mInflightLock);
4841
4842 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4843 auto it = mInflightBufferMap.find(key);
4844 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004845 if (buffer != nullptr) {
4846 *buffer = it->second;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004847 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004848 mInflightBufferMap.erase(it);
4849 return OK;
4850}
4851
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004852void Camera3Device::HalInterface::popInflightBuffers(
4853 const std::vector<std::pair<int32_t, int32_t>>& buffers) {
4854 for (const auto& pair : buffers) {
4855 int32_t frameNumber = pair.first;
4856 int32_t streamId = pair.second;
4857 popInflightBuffer(frameNumber, streamId, nullptr);
4858 }
4859}
4860
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004861status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004862 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004863 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004864 auto pair = mRequestedBuffers.insert({bufferId, {streamId, buf}});
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004865 if (!pair.second) {
4866 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4867 __FUNCTION__, bufferId);
4868 return BAD_VALUE;
4869 }
4870 return OK;
4871}
4872
4873// Find and pop a buffer_handle_t based on bufferId
4874status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004875 uint64_t bufferId,
4876 /*out*/ buffer_handle_t** buffer,
4877 /*optional out*/ int32_t* streamId) {
4878 if (buffer == nullptr) {
4879 ALOGE("%s: buffer (%p) must not be null", __FUNCTION__, buffer);
4880 return BAD_VALUE;
4881 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004882 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4883 auto it = mRequestedBuffers.find(bufferId);
4884 if (it == mRequestedBuffers.end()) {
4885 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4886 __FUNCTION__, bufferId);
4887 return BAD_VALUE;
4888 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004889 *buffer = it->second.second;
4890 if (streamId != nullptr) {
4891 *streamId = it->second.first;
4892 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004893 mRequestedBuffers.erase(it);
4894 return OK;
4895}
4896
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004897std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4898 const buffer_handle_t& buf, int streamId) {
4899 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4900
4901 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4902 auto it = bIdMap.find(buf);
4903 if (it == bIdMap.end()) {
4904 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004905 ALOGV("stream %d now have %zu buffer caches, buf %p",
4906 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004907 return std::make_pair(true, mNextBufferId - 1);
4908 } else {
4909 return std::make_pair(false, it->second);
4910 }
4911}
4912
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004913void Camera3Device::HalInterface::onBufferFreed(
4914 int streamId, const native_handle_t* handle) {
4915 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4916 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4917 auto mapIt = mBufferIdMaps.find(streamId);
4918 if (mapIt == mBufferIdMaps.end()) {
4919 // streamId might be from a deleted stream here
4920 ALOGI("%s: stream %d has been removed",
4921 __FUNCTION__, streamId);
4922 return;
4923 }
4924 BufferIdMap& bIdMap = mapIt->second;
4925 auto it = bIdMap.find(handle);
4926 if (it == bIdMap.end()) {
4927 ALOGW("%s: cannot find buffer %p in stream %d",
4928 __FUNCTION__, handle, streamId);
4929 return;
4930 } else {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004931 bufferId = it->second;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004932 bIdMap.erase(it);
4933 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4934 __FUNCTION__, streamId, bIdMap.size(), handle);
4935 }
4936 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4937}
4938
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004939void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
4940 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4941 auto mapIt = mBufferIdMaps.find(streamId);
4942 if (mapIt == mBufferIdMaps.end()) {
4943 ALOGE("%s: streamId %d not found!", __FUNCTION__, streamId);
4944 return;
4945 }
4946
4947 BufferIdMap& bIdMap = mapIt->second;
4948 for (const auto& it : bIdMap) {
4949 uint64_t bufferId = it.second;
4950 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4951 }
4952 bIdMap.clear();
4953}
4954
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004955/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004956 * RequestThread inner class methods
4957 */
4958
4959Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004960 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004961 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4962 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004963 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004964 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004965 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004966 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004967 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004968 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004969 mReconfigured(false),
4970 mDoPause(false),
4971 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004972 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004973 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004974 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004975 mCurrentAfTriggerId(0),
4976 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004977 mRepeatingLastFrameNumber(
4978 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004979 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004980 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004981 mRequestLatency(kRequestLatencyBinSize),
4982 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004983 mLatestSessionParams(sessionParamKeys.size()),
4984 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004985 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004986}
4987
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004988Camera3Device::RequestThread::~RequestThread() {}
4989
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004990void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004991 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004992 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004993 Mutex::Autolock l(mRequestLock);
4994 mListener = listener;
4995}
4996
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004997void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4998 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004999 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005000 Mutex::Autolock l(mRequestLock);
5001 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005002 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005003 // Prepare video stream for high speed recording.
5004 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005005 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005006}
5007
Jianing Wei90e59c92014-03-12 18:29:36 -07005008status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005009 List<sp<CaptureRequest> > &requests,
5010 /*out*/
5011 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005012 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07005013 Mutex::Autolock l(mRequestLock);
5014 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
5015 ++it) {
5016 mRequestQueue.push_back(*it);
5017 }
5018
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005019 if (lastFrameNumber != NULL) {
5020 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
5021 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
5022 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
5023 *lastFrameNumber);
5024 }
Jianing Weicb0652e2014-03-12 18:29:36 -07005025
Jianing Wei90e59c92014-03-12 18:29:36 -07005026 unpauseForNewRequests();
5027
5028 return OK;
5029}
5030
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005031
5032status_t Camera3Device::RequestThread::queueTrigger(
5033 RequestTrigger trigger[],
5034 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005035 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005036 Mutex::Autolock l(mTriggerMutex);
5037 status_t ret;
5038
5039 for (size_t i = 0; i < count; ++i) {
5040 ret = queueTriggerLocked(trigger[i]);
5041
5042 if (ret != OK) {
5043 return ret;
5044 }
5045 }
5046
5047 return OK;
5048}
5049
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08005050const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
5051 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005052 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08005053 if (d != nullptr) return d->mId;
5054 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005055}
5056
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005057status_t Camera3Device::RequestThread::queueTriggerLocked(
5058 RequestTrigger trigger) {
5059
5060 uint32_t tag = trigger.metadataTag;
5061 ssize_t index = mTriggerMap.indexOfKey(tag);
5062
5063 switch (trigger.getTagType()) {
5064 case TYPE_BYTE:
5065 // fall-through
5066 case TYPE_INT32:
5067 break;
5068 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005069 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
5070 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005071 return INVALID_OPERATION;
5072 }
5073
5074 /**
5075 * Collect only the latest trigger, since we only have 1 field
5076 * in the request settings per trigger tag, and can't send more than 1
5077 * trigger per request.
5078 */
5079 if (index != NAME_NOT_FOUND) {
5080 mTriggerMap.editValueAt(index) = trigger;
5081 } else {
5082 mTriggerMap.add(tag, trigger);
5083 }
5084
5085 return OK;
5086}
5087
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005088status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005089 const RequestList &requests,
5090 /*out*/
5091 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005092 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005093 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005094 if (lastFrameNumber != NULL) {
5095 *lastFrameNumber = mRepeatingLastFrameNumber;
5096 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005097 mRepeatingRequests.clear();
5098 mRepeatingRequests.insert(mRepeatingRequests.begin(),
5099 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005100
5101 unpauseForNewRequests();
5102
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005103 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005104 return OK;
5105}
5106
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07005107bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005108 if (mRepeatingRequests.empty()) {
5109 return false;
5110 }
5111 int32_t requestId = requestIn->mResultExtras.requestId;
5112 const RequestList &repeatRequests = mRepeatingRequests;
5113 // All repeating requests are guaranteed to have same id so only check first quest
5114 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
5115 return (firstRequest->mResultExtras.requestId == requestId);
5116}
5117
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005118status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005119 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005120 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005121 return clearRepeatingRequestsLocked(lastFrameNumber);
5122
5123}
5124
5125status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005126 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005127 if (lastFrameNumber != NULL) {
5128 *lastFrameNumber = mRepeatingLastFrameNumber;
5129 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005130 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005131 return OK;
5132}
5133
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005134status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005135 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005136 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005137 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005138 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005139
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005140 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005141
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005142 // Send errors for all requests pending in the request queue, including
5143 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005144 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005145 if (listener != NULL) {
5146 for (RequestList::iterator it = mRequestQueue.begin();
5147 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005148 // Abort the input buffers for reprocess requests.
5149 if ((*it)->mInputStream != NULL) {
5150 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07005151 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
5152 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005153 if (res != OK) {
5154 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
5155 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5156 } else {
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07005157 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005158 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
5159 if (res != OK) {
5160 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
5161 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5162 }
5163 }
5164 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005165 // Set the frame number this request would have had, if it
5166 // had been submitted; this frame number will not be reused.
5167 // The requestId and burstId fields were set when the request was
5168 // submitted originally (in convertMetadataListToRequestListLocked)
5169 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005170 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005171 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005172 }
5173 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005174 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08005175
5176 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005177 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005178 if (lastFrameNumber != NULL) {
5179 *lastFrameNumber = mRepeatingLastFrameNumber;
5180 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005181 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08005182 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005183 return OK;
5184}
5185
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005186status_t Camera3Device::RequestThread::flush() {
5187 ATRACE_CALL();
5188 Mutex::Autolock l(mFlushLock);
5189
Emilian Peev08dd2452017-04-06 16:55:14 +01005190 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005191}
5192
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005193void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005194 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005195 Mutex::Autolock l(mPauseLock);
5196 mDoPause = paused;
5197 mDoPauseSignal.signal();
5198}
5199
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005200status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
5201 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005202 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005203 Mutex::Autolock l(mLatestRequestMutex);
5204 status_t res;
5205 while (mLatestRequestId != requestId) {
5206 nsecs_t startTime = systemTime();
5207
5208 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
5209 if (res != OK) return res;
5210
5211 timeout -= (systemTime() - startTime);
5212 }
5213
5214 return OK;
5215}
5216
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005217void Camera3Device::RequestThread::requestExit() {
5218 // Call parent to set up shutdown
5219 Thread::requestExit();
5220 // The exit from any possible waits
5221 mDoPauseSignal.signal();
5222 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07005223
5224 mRequestLatency.log("ProcessCaptureRequest latency histogram");
5225 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005226}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005227
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005228void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005229 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005230 bool surfaceAbandoned = false;
5231 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005232 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005233 {
5234 Mutex::Autolock l(mRequestLock);
5235 // Check all streams needed by repeating requests are still valid. Otherwise, stop
5236 // repeating requests.
5237 for (const auto& request : mRepeatingRequests) {
5238 for (const auto& s : request->mOutputStreams) {
5239 if (s->isAbandoned()) {
5240 surfaceAbandoned = true;
5241 clearRepeatingRequestsLocked(&lastFrameNumber);
5242 break;
5243 }
5244 }
5245 if (surfaceAbandoned) {
5246 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005247 }
5248 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005249 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005250 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005251
5252 if (listener != NULL && surfaceAbandoned) {
5253 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005254 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005255}
5256
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005257bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005258 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005259 status_t res;
5260 size_t batchSize = mNextRequests.size();
5261 std::vector<camera3_capture_request_t*> requests(batchSize);
5262 uint32_t numRequestProcessed = 0;
5263 for (size_t i = 0; i < batchSize; i++) {
5264 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07005265 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005266 }
5267
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005268 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
5269
5270 bool triggerRemoveFailed = false;
5271 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
5272 for (size_t i = 0; i < numRequestProcessed; i++) {
5273 NextRequest& nextRequest = mNextRequests.editItemAt(i);
5274 nextRequest.submitted = true;
5275
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005276 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00005277
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005278 if (!triggerRemoveFailed) {
5279 // Remove any previously queued triggers (after unlock)
5280 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5281 if (removeTriggerRes != OK) {
5282 triggerRemoveFailed = true;
5283 triggerFailedRequest = nextRequest;
5284 }
5285 }
5286 }
5287
5288 if (triggerRemoveFailed) {
5289 SET_ERR("RequestThread: Unable to remove triggers "
5290 "(capture request %d, HAL device: %s (%d)",
5291 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5292 cleanUpFailedRequests(/*sendRequestError*/ false);
5293 return false;
5294 }
5295
5296 if (res != OK) {
5297 // Should only get a failure here for malformed requests or device-level
5298 // errors, so consider all errors fatal. Bad metadata failures should
5299 // come through notify.
5300 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5301 mNextRequests[numRequestProcessed].halRequest.frame_number,
5302 strerror(-res), res);
5303 cleanUpFailedRequests(/*sendRequestError*/ false);
5304 return false;
5305 }
5306 return true;
5307}
5308
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005309nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5310 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5311 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5312 find_camera_metadata_ro_entry(request,
5313 ANDROID_CONTROL_AE_MODE,
5314 &e);
5315 if (e.count == 0) return maxExpectedDuration;
5316
5317 switch (e.data.u8[0]) {
5318 case ANDROID_CONTROL_AE_MODE_OFF:
5319 find_camera_metadata_ro_entry(request,
5320 ANDROID_SENSOR_EXPOSURE_TIME,
5321 &e);
5322 if (e.count > 0) {
5323 maxExpectedDuration = e.data.i64[0];
5324 }
5325 find_camera_metadata_ro_entry(request,
5326 ANDROID_SENSOR_FRAME_DURATION,
5327 &e);
5328 if (e.count > 0) {
5329 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5330 }
5331 break;
5332 default:
5333 find_camera_metadata_ro_entry(request,
5334 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5335 &e);
5336 if (e.count > 1) {
5337 maxExpectedDuration = 1e9 / e.data.u8[0];
5338 }
5339 break;
5340 }
5341
5342 return maxExpectedDuration;
5343}
5344
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005345bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5346 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5347 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5348 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5349 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5350 return true;
5351 }
5352
5353 return false;
5354}
5355
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005356void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
5357 // Update the latest request sent to HAL
5358 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5359 Mutex::Autolock al(mLatestRequestMutex);
5360
5361 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5362 mLatestRequest.acquire(cloned);
5363
5364 mLatestPhysicalRequest.clear();
5365 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
5366 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
5367 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
5368 CameraMetadata(cloned));
5369 }
5370
5371 sp<Camera3Device> parent = mParent.promote();
5372 if (parent != NULL) {
5373 parent->monitorMetadata(TagMonitor::REQUEST,
5374 nextRequest.halRequest.frame_number,
5375 0, mLatestRequest, mLatestPhysicalRequest);
5376 }
5377 }
5378
5379 if (nextRequest.halRequest.settings != NULL) {
5380 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5381 nextRequest.halRequest.settings);
5382 }
5383
5384 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5385}
5386
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005387bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5388 ATRACE_CALL();
5389 bool updatesDetected = false;
5390
Emilian Peev4ec17882019-01-24 17:16:58 -08005391 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005392 for (auto tag : mSessionParamKeys) {
5393 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005394 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005395
5396 if (entry.count > 0) {
5397 bool isDifferent = false;
5398 if (lastEntry.count > 0) {
5399 // Have a last value, compare to see if changed
5400 if (lastEntry.type == entry.type &&
5401 lastEntry.count == entry.count) {
5402 // Same type and count, compare values
5403 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5404 size_t entryBytes = bytesPerValue * lastEntry.count;
5405 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5406 if (cmp != 0) {
5407 isDifferent = true;
5408 }
5409 } else {
5410 // Count or type has changed
5411 isDifferent = true;
5412 }
5413 } else {
5414 // No last entry, so always consider to be different
5415 isDifferent = true;
5416 }
5417
5418 if (isDifferent) {
5419 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005420 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5421 updatesDetected = true;
5422 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005423 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005424 }
5425 } else if (lastEntry.count > 0) {
5426 // Value has been removed
5427 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005428 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005429 updatesDetected = true;
5430 }
5431 }
5432
Emilian Peev4ec17882019-01-24 17:16:58 -08005433 bool reconfigureRequired;
5434 if (updatesDetected) {
5435 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5436 updatedParams);
5437 mLatestSessionParams = updatedParams;
5438 } else {
5439 reconfigureRequired = false;
5440 }
5441
5442 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005443}
5444
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005445bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005446 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005447 status_t res;
5448
5449 // Handle paused state.
5450 if (waitIfPaused()) {
5451 return true;
5452 }
5453
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005454 // Wait for the next batch of requests.
5455 waitForNextRequestBatch();
5456 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005457 return true;
5458 }
5459
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005460 // Get the latest request ID, if any
5461 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005462 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005463 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005464 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005465 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005466 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005467 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5468 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005469 }
5470
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005471 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5472 // or a single request from streaming or burst. In either case the first element
5473 // should contain the latest camera settings that we need to check for any session
5474 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005475 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005476 res = OK;
5477
5478 //Input stream buffers are already acquired at this point so an input stream
5479 //will not be able to move to idle state unless we force it.
5480 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5481 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5482 if (res != OK) {
5483 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5484 cleanUpFailedRequests(/*sendRequestError*/ false);
5485 return false;
5486 }
5487 }
5488
5489 if (res == OK) {
5490 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5491 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005492 sp<Camera3Device> parent = mParent.promote();
5493 if (parent != nullptr) {
5494 parent->pauseStateNotify(true);
5495 }
5496
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005497 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5498
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005499 if (parent != nullptr) {
5500 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5501 }
5502
5503 statusTracker->markComponentActive(mStatusId);
5504 setPaused(false);
5505 }
5506
5507 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5508 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5509 if (res != OK) {
5510 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5511 cleanUpFailedRequests(/*sendRequestError*/ false);
5512 return false;
5513 }
5514 }
5515 }
5516 }
5517
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005518 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005519 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005520 if (res == TIMED_OUT) {
5521 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005522 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005523 // Check if any stream is abandoned.
5524 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005525 return true;
5526 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005527 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005528 return false;
5529 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005530
Zhijun Hecc27e112013-10-03 16:12:43 -07005531 // Inform waitUntilRequestProcessed thread of a new request ID
5532 {
5533 Mutex::Autolock al(mLatestRequestMutex);
5534
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005535 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005536 mLatestRequestSignal.signal();
5537 }
5538
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005539 // Submit a batch of requests to HAL.
5540 // Use flush lock only when submitting multilple requests in a batch.
5541 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5542 // which may take a long time to finish so synchronizing flush() and
5543 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5544 // For now, only synchronize for high speed recording and we should figure something out for
5545 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005546 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005547
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005548 if (useFlushLock) {
5549 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005550 }
5551
Zhijun Hef0645c12016-08-02 00:58:11 -07005552 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005553 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005554
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005555 sp<Camera3Device> parent = mParent.promote();
5556 if (parent != nullptr) {
5557 parent->mRequestBufferSM.onSubmittingRequest();
5558 }
5559
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005560 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005561 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07005562 submitRequestSuccess = sendRequestsBatch();
5563
Shuzhen Wang686f6442017-06-20 16:16:04 -07005564 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5565 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005566
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005567 if (useFlushLock) {
5568 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005569 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005570
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005571 // Unset as current request
5572 {
5573 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005574 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005575 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005576 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005577
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005578 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005579}
5580
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005581status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005582 ATRACE_CALL();
5583
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005584 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005585 for (size_t i = 0; i < mNextRequests.size(); i++) {
5586 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005587 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5588 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5589 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5590
5591 // Prepare a request to HAL
5592 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5593
5594 // Insert any queued triggers (before metadata is locked)
5595 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005596 if (res < 0) {
5597 SET_ERR("RequestThread: Unable to insert triggers "
5598 "(capture request %d, HAL device: %s (%d)",
5599 halRequest->frame_number, strerror(-res), res);
5600 return INVALID_OPERATION;
5601 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005602
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005603 int triggerCount = res;
5604 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5605 mPrevTriggers = triggerCount;
5606
5607 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005608 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5609 // Request settings are all the same within one batch, so only treat the first
5610 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005611 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005612 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005613 /**
5614 * HAL workaround:
5615 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5616 */
5617 res = addDummyTriggerIds(captureRequest);
5618 if (res != OK) {
5619 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5620 "(capture request %d, HAL device: %s (%d)",
5621 halRequest->frame_number, strerror(-res), res);
5622 return INVALID_OPERATION;
5623 }
5624
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005625 {
5626 // Correct metadata regions for distortion correction if enabled
5627 sp<Camera3Device> parent = mParent.promote();
5628 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07005629 List<PhysicalCameraSettings>::iterator it;
5630 for (it = captureRequest->mSettingsList.begin();
5631 it != captureRequest->mSettingsList.end(); it++) {
5632 if (parent->mDistortionMappers.find(it->cameraId) ==
5633 parent->mDistortionMappers.end()) {
5634 continue;
5635 }
5636 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
5637 &(it->metadata));
5638 if (res != OK) {
5639 SET_ERR("RequestThread: Unable to correct capture requests "
5640 "for lens distortion for request %d: %s (%d)",
5641 halRequest->frame_number, strerror(-res), res);
5642 return INVALID_OPERATION;
5643 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005644 }
5645 }
5646 }
5647
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005648 /**
5649 * The request should be presorted so accesses in HAL
5650 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5651 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005652 captureRequest->mSettingsList.begin()->metadata.sort();
5653 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005654 mPrevRequest = captureRequest;
5655 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5656
5657 IF_ALOGV() {
5658 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5659 find_camera_metadata_ro_entry(
5660 halRequest->settings,
5661 ANDROID_CONTROL_AF_TRIGGER,
5662 &e
5663 );
5664 if (e.count > 0) {
5665 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5666 __FUNCTION__,
5667 halRequest->frame_number,
5668 e.data.u8[0]);
5669 }
5670 }
5671 } else {
5672 // leave request.settings NULL to indicate 'reuse latest given'
5673 ALOGVV("%s: Request settings are REUSED",
5674 __FUNCTION__);
5675 }
5676
Emilian Peevaebbe412018-01-15 13:53:24 +00005677 if (captureRequest->mSettingsList.size() > 1) {
5678 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5679 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005680 if (newRequest) {
5681 halRequest->physcam_settings =
5682 new const camera_metadata* [halRequest->num_physcam_settings];
5683 } else {
5684 halRequest->physcam_settings = nullptr;
5685 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005686 auto it = ++captureRequest->mSettingsList.begin();
5687 size_t i = 0;
5688 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5689 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005690 if (newRequest) {
5691 it->metadata.sort();
5692 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5693 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005694 }
5695 }
5696
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005697 uint32_t totalNumBuffers = 0;
5698
5699 // Fill in buffers
5700 if (captureRequest->mInputStream != NULL) {
5701 halRequest->input_buffer = &captureRequest->mInputBuffer;
5702 totalNumBuffers += 1;
5703 } else {
5704 halRequest->input_buffer = NULL;
5705 }
5706
5707 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5708 captureRequest->mOutputStreams.size());
5709 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005710 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005711
5712 sp<Camera3Device> parent = mParent.promote();
5713 if (parent == NULL) {
5714 // Should not happen, and nowhere to send errors to, so just log it
5715 CLOGE("RequestThread: Parent is gone");
5716 return INVALID_OPERATION;
5717 }
5718 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5719
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005720 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005721 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005722 sp<Camera3OutputStreamInterface> outputStream =
5723 captureRequest->mOutputStreams.editItemAt(j);
5724 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005725
5726 // Prepare video buffers for high speed recording on the first video request.
5727 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5728 // Only try to prepare video stream on the first video request.
5729 mPrepareVideoStream = false;
5730
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005731 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5732 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005733 while (res == NOT_ENOUGH_DATA) {
5734 res = outputStream->prepareNextBuffer();
5735 }
5736 if (res != OK) {
5737 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5738 __FUNCTION__, strerror(-res), res);
5739 outputStream->cancelPrepare();
5740 }
5741 }
5742
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005743 std::vector<size_t> uniqueSurfaceIds;
5744 res = outputStream->getUniqueSurfaceIds(
5745 captureRequest->mOutputSurfaces[streamId],
5746 &uniqueSurfaceIds);
5747 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5748 if (res != OK && res != INVALID_OPERATION) {
5749 ALOGE("%s: failed to query stream %d unique surface IDs",
5750 __FUNCTION__, streamId);
5751 return res;
5752 }
5753 if (res == OK) {
5754 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5755 }
5756
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005757 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005758 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005759 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005760 return TIMED_OUT;
5761 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005762 // HAL will request buffer through requestStreamBuffer API
5763 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5764 buffer.stream = outputStream->asHalStream();
5765 buffer.buffer = nullptr;
5766 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5767 buffer.acquire_fence = -1;
5768 buffer.release_fence = -1;
5769 } else {
5770 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5771 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005772 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005773 if (res != OK) {
5774 // Can't get output buffer from gralloc queue - this could be due to
5775 // abandoned queue or other consumer misbehavior, so not a fatal
5776 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005777 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005778 " %s (%d)", strerror(-res), res);
5779
5780 return TIMED_OUT;
5781 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005782 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005783
5784 {
5785 sp<Camera3Device> parent = mParent.promote();
5786 if (parent != nullptr) {
5787 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5788 for (const auto& settings : captureRequest->mSettingsList) {
5789 if ((streamCameraId.isEmpty() &&
5790 parent->getId() == settings.cameraId.c_str()) ||
5791 streamCameraId == settings.cameraId.c_str()) {
5792 outputStream->fireBufferRequestForFrameNumber(
5793 captureRequest->mResultExtras.frameNumber,
5794 settings.metadata);
5795 }
5796 }
5797 }
5798 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005799
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005800 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5801
5802 if (!physicalCameraId.isEmpty()) {
5803 // Physical stream isn't supported for input request.
5804 if (halRequest->input_buffer) {
5805 CLOGE("Physical stream is not supported for input request");
5806 return INVALID_OPERATION;
5807 }
5808 requestedPhysicalCameras.insert(physicalCameraId);
5809 }
5810 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005811 }
5812 totalNumBuffers += halRequest->num_output_buffers;
5813
5814 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005815 // If this request list is for constrained high speed recording (not
5816 // preview), and the current request is not the last one in the batch,
5817 // do not send callback to the app.
5818 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005819 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005820 hasCallback = false;
5821 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005822 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005823 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005824 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5825 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5826 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5827 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5828 isStillCapture = true;
5829 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5830 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005831
5832 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5833 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5834 isZslCapture = true;
5835 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005836 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005837 res = parent->registerInFlight(halRequest->frame_number,
5838 totalNumBuffers, captureRequest->mResultExtras,
5839 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005840 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005841 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005842 requestedPhysicalCameras, isStillCapture, isZslCapture,
5843 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5844 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005845 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5846 ", burstId = %" PRId32 ".",
5847 __FUNCTION__,
5848 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5849 captureRequest->mResultExtras.burstId);
5850 if (res != OK) {
5851 SET_ERR("RequestThread: Unable to register new in-flight request:"
5852 " %s (%d)", strerror(-res), res);
5853 return INVALID_OPERATION;
5854 }
5855 }
5856
5857 return OK;
5858}
5859
Igor Murashkin1e479c02013-09-06 16:55:14 -07005860CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005861 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005862 Mutex::Autolock al(mLatestRequestMutex);
5863
5864 ALOGV("RequestThread::%s", __FUNCTION__);
5865
5866 return mLatestRequest;
5867}
5868
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005869bool Camera3Device::RequestThread::isStreamPending(
5870 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005871 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005872 Mutex::Autolock l(mRequestLock);
5873
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005874 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005875 if (!nextRequest.submitted) {
5876 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5877 if (stream == s) return true;
5878 }
5879 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005880 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005881 }
5882
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005883 for (const auto& request : mRequestQueue) {
5884 for (const auto& s : request->mOutputStreams) {
5885 if (stream == s) return true;
5886 }
5887 if (stream == request->mInputStream) return true;
5888 }
5889
5890 for (const auto& request : mRepeatingRequests) {
5891 for (const auto& s : request->mOutputStreams) {
5892 if (stream == s) return true;
5893 }
5894 if (stream == request->mInputStream) return true;
5895 }
5896
5897 return false;
5898}
Jianing Weicb0652e2014-03-12 18:29:36 -07005899
Emilian Peev40ead602017-09-26 15:46:36 +01005900bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5901 ATRACE_CALL();
5902 Mutex::Autolock l(mRequestLock);
5903
5904 for (const auto& nextRequest : mNextRequests) {
5905 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5906 if (s.first == streamId) {
5907 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5908 if (it != s.second.end()) {
5909 return true;
5910 }
5911 }
5912 }
5913 }
5914
5915 for (const auto& request : mRequestQueue) {
5916 for (const auto& s : request->mOutputSurfaces) {
5917 if (s.first == streamId) {
5918 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5919 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005920 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005921 }
5922 }
5923 }
5924 }
5925
5926 for (const auto& request : mRepeatingRequests) {
5927 for (const auto& s : request->mOutputSurfaces) {
5928 if (s.first == streamId) {
5929 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5930 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005931 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005932 }
5933 }
5934 }
5935 }
5936
5937 return false;
5938}
5939
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005940void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5941 if (!mUseHalBufManager) {
5942 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5943 return;
5944 }
5945
5946 Mutex::Autolock pl(mPauseLock);
5947 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005948 mInterface->signalPipelineDrain(streamIds);
5949 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005950 }
5951 // If request thread is still busy, wait until paused then notify HAL
5952 mNotifyPipelineDrain = true;
5953 mStreamIdsToBeDrained = streamIds;
5954}
5955
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005956status_t Camera3Device::RequestThread::switchToOffline(
5957 const std::vector<int32_t>& streamsToKeep,
5958 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
5959 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession) {
5960 Mutex::Autolock l(mRequestLock);
5961 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
5962
5963 // Theoretically we should also check for mRepeatingRequests.empty(), but the API interface
5964 // is serialized by mInterfaceLock so skip that check.
5965 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5966 while (!queueEmpty) {
5967 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
5968 if (res == TIMED_OUT) {
5969 ALOGE("%s: request thread failed to submit a request within timeout!", __FUNCTION__);
5970 return res;
5971 } else if (res != OK) {
5972 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
5973 __FUNCTION__, strerror(-res), res);
5974 return res;
5975 }
5976 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
5977 }
5978 return mInterface->switchToOffline(
5979 streamsToKeep, offlineSessionInfo, offlineSession);
5980}
5981
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005982nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005983 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005984 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005985 return mExpectedInflightDuration > kMinInflightDuration ?
5986 mExpectedInflightDuration : kMinInflightDuration;
5987}
5988
Emilian Peevaebbe412018-01-15 13:53:24 +00005989void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5990 camera3_capture_request_t *halRequest) {
5991 if ((request == nullptr) || (halRequest == nullptr)) {
5992 ALOGE("%s: Invalid request!", __FUNCTION__);
5993 return;
5994 }
5995
5996 if (halRequest->num_physcam_settings > 0) {
5997 if (halRequest->physcam_id != nullptr) {
5998 delete [] halRequest->physcam_id;
5999 halRequest->physcam_id = nullptr;
6000 }
6001 if (halRequest->physcam_settings != nullptr) {
6002 auto it = ++(request->mSettingsList.begin());
6003 size_t i = 0;
6004 for (; it != request->mSettingsList.end(); it++, i++) {
6005 it->metadata.unlock(halRequest->physcam_settings[i]);
6006 }
6007 delete [] halRequest->physcam_settings;
6008 halRequest->physcam_settings = nullptr;
6009 }
6010 }
6011}
6012
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006013void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
6014 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006015 return;
6016 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006017
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006018 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006019 // Skip the ones that have been submitted successfully.
6020 if (nextRequest.submitted) {
6021 continue;
6022 }
6023
6024 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
6025 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
6026 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
6027
6028 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00006029 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006030 }
6031
Emilian Peevaebbe412018-01-15 13:53:24 +00006032 cleanupPhysicalSettings(captureRequest, halRequest);
6033
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006034 if (captureRequest->mInputStream != NULL) {
6035 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
6036 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
6037 }
6038
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08006039 // No output buffer can be returned when using HAL buffer manager
6040 if (!mUseHalBufManager) {
6041 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
6042 //Buffers that failed processing could still have
6043 //valid acquire fence.
6044 int acquireFence = (*outputBuffers)[i].acquire_fence;
6045 if (0 <= acquireFence) {
6046 close(acquireFence);
6047 outputBuffers->editItemAt(i).acquire_fence = -1;
6048 }
6049 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
6050 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
6051 /*timestampIncreasing*/true, std::vector<size_t> (),
6052 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01006053 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006054 }
6055
6056 if (sendRequestError) {
6057 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006058 sp<NotificationListener> listener = mListener.promote();
6059 if (listener != NULL) {
6060 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006061 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006062 captureRequest->mResultExtras);
6063 }
6064 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07006065
6066 // Remove yet-to-be submitted inflight request from inflightMap
6067 {
6068 sp<Camera3Device> parent = mParent.promote();
6069 if (parent != NULL) {
6070 Mutex::Autolock l(parent->mInFlightLock);
6071 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
6072 if (idx >= 0) {
6073 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
6074 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
6075 parent->removeInFlightMapEntryLocked(idx);
6076 }
6077 }
6078 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006079 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07006080
6081 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006082 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006083}
6084
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006085void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006086 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006087 // Optimized a bit for the simple steady-state case (single repeating
6088 // request), to avoid putting that request in the queue temporarily.
6089 Mutex::Autolock l(mRequestLock);
6090
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006091 assert(mNextRequests.empty());
6092
6093 NextRequest nextRequest;
6094 nextRequest.captureRequest = waitForNextRequestLocked();
6095 if (nextRequest.captureRequest == nullptr) {
6096 return;
6097 }
6098
6099 nextRequest.halRequest = camera3_capture_request_t();
6100 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006101 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006102
6103 // Wait for additional requests
6104 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
6105
6106 for (size_t i = 1; i < batchSize; i++) {
6107 NextRequest additionalRequest;
6108 additionalRequest.captureRequest = waitForNextRequestLocked();
6109 if (additionalRequest.captureRequest == nullptr) {
6110 break;
6111 }
6112
6113 additionalRequest.halRequest = camera3_capture_request_t();
6114 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006115 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006116 }
6117
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006118 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006119 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006120 mNextRequests.size(), batchSize);
6121 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006122 }
6123
6124 return;
6125}
6126
6127sp<Camera3Device::CaptureRequest>
6128 Camera3Device::RequestThread::waitForNextRequestLocked() {
6129 status_t res;
6130 sp<CaptureRequest> nextRequest;
6131
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006132 while (mRequestQueue.empty()) {
6133 if (!mRepeatingRequests.empty()) {
6134 // Always atomically enqueue all requests in a repeating request
6135 // list. Guarantees a complete in-sequence set of captures to
6136 // application.
6137 const RequestList &requests = mRepeatingRequests;
6138 RequestList::const_iterator firstRequest =
6139 requests.begin();
6140 nextRequest = *firstRequest;
6141 mRequestQueue.insert(mRequestQueue.end(),
6142 ++firstRequest,
6143 requests.end());
6144 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07006145
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006146 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07006147
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006148 break;
6149 }
6150
6151 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
6152
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006153 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
6154 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006155 Mutex::Autolock pl(mPauseLock);
6156 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006157 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006158 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006159 if (mNotifyPipelineDrain) {
6160 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6161 mNotifyPipelineDrain = false;
6162 mStreamIdsToBeDrained.clear();
6163 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006164 // Let the tracker know
6165 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6166 if (statusTracker != 0) {
6167 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6168 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006169 sp<Camera3Device> parent = mParent.promote();
6170 if (parent != nullptr) {
6171 parent->mRequestBufferSM.onRequestThreadPaused();
6172 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006173 }
6174 // Stop waiting for now and let thread management happen
6175 return NULL;
6176 }
6177 }
6178
6179 if (nextRequest == NULL) {
6180 // Don't have a repeating request already in hand, so queue
6181 // must have an entry now.
6182 RequestList::iterator firstRequest =
6183 mRequestQueue.begin();
6184 nextRequest = *firstRequest;
6185 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07006186 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
6187 sp<NotificationListener> listener = mListener.promote();
6188 if (listener != NULL) {
6189 listener->notifyRequestQueueEmpty();
6190 }
6191 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006192 }
6193
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006194 // In case we've been unpaused by setPaused clearing mDoPause, need to
6195 // update internal pause state (capture/setRepeatingRequest unpause
6196 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006197 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006198 if (mPaused) {
6199 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
6200 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6201 if (statusTracker != 0) {
6202 statusTracker->markComponentActive(mStatusId);
6203 }
6204 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006205 mPaused = false;
6206
6207 // Check if we've reconfigured since last time, and reset the preview
6208 // request if so. Can't use 'NULL request == repeat' across configure calls.
6209 if (mReconfigured) {
6210 mPrevRequest.clear();
6211 mReconfigured = false;
6212 }
6213
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006214 if (nextRequest != NULL) {
6215 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006216 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
6217 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006218
6219 // Since RequestThread::clear() removes buffers from the input stream,
6220 // get the right buffer here before unlocking mRequestLock
6221 if (nextRequest->mInputStream != NULL) {
6222 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
6223 if (res != OK) {
6224 // Can't get input buffer from gralloc queue - this could be due to
6225 // disconnected queue or other producer misbehavior, so not a fatal
6226 // error
6227 ALOGE("%s: Can't get input buffer, skipping request:"
6228 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006229
6230 sp<NotificationListener> listener = mListener.promote();
6231 if (listener != NULL) {
6232 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006233 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006234 nextRequest->mResultExtras);
6235 }
6236 return NULL;
6237 }
6238 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006239 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07006240
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006241 return nextRequest;
6242}
6243
6244bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006245 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006246 status_t res;
6247 Mutex::Autolock l(mPauseLock);
6248 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006249 if (mPaused == false) {
6250 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006251 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006252 if (mNotifyPipelineDrain) {
6253 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6254 mNotifyPipelineDrain = false;
6255 mStreamIdsToBeDrained.clear();
6256 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006257 // Let the tracker know
6258 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6259 if (statusTracker != 0) {
6260 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6261 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006262 sp<Camera3Device> parent = mParent.promote();
6263 if (parent != nullptr) {
6264 parent->mRequestBufferSM.onRequestThreadPaused();
6265 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006266 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006267
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006268 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006269 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006270 return true;
6271 }
6272 }
6273 // We don't set mPaused to false here, because waitForNextRequest needs
6274 // to further manage the paused state in case of starvation.
6275 return false;
6276}
6277
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006278void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006279 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006280 // With work to do, mark thread as unpaused.
6281 // If paused by request (setPaused), don't resume, to avoid
6282 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006283 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006284 Mutex::Autolock p(mPauseLock);
6285 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006286 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6287 if (mPaused) {
6288 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6289 if (statusTracker != 0) {
6290 statusTracker->markComponentActive(mStatusId);
6291 }
6292 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006293 mPaused = false;
6294 }
6295}
6296
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006297void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6298 sp<Camera3Device> parent = mParent.promote();
6299 if (parent != NULL) {
6300 va_list args;
6301 va_start(args, fmt);
6302
6303 parent->setErrorStateV(fmt, args);
6304
6305 va_end(args);
6306 }
6307}
6308
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006309status_t Camera3Device::RequestThread::insertTriggers(
6310 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006311 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006312 Mutex::Autolock al(mTriggerMutex);
6313
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006314 sp<Camera3Device> parent = mParent.promote();
6315 if (parent == NULL) {
6316 CLOGE("RequestThread: Parent is gone");
6317 return DEAD_OBJECT;
6318 }
6319
Emilian Peevaebbe412018-01-15 13:53:24 +00006320 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006321 size_t count = mTriggerMap.size();
6322
6323 for (size_t i = 0; i < count; ++i) {
6324 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006325 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006326
6327 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6328 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6329 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006330 if (isAeTrigger) {
6331 request->mResultExtras.precaptureTriggerId = triggerId;
6332 mCurrentPreCaptureTriggerId = triggerId;
6333 } else {
6334 request->mResultExtras.afTriggerId = triggerId;
6335 mCurrentAfTriggerId = triggerId;
6336 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006337 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006338 }
6339
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006340 camera_metadata_entry entry = metadata.find(tag);
6341
6342 if (entry.count > 0) {
6343 /**
6344 * Already has an entry for this trigger in the request.
6345 * Rewrite it with our requested trigger value.
6346 */
6347 RequestTrigger oldTrigger = trigger;
6348
6349 oldTrigger.entryValue = entry.data.u8[0];
6350
6351 mTriggerReplacedMap.add(tag, oldTrigger);
6352 } else {
6353 /**
6354 * More typical, no trigger entry, so we just add it
6355 */
6356 mTriggerRemovedMap.add(tag, trigger);
6357 }
6358
6359 status_t res;
6360
6361 switch (trigger.getTagType()) {
6362 case TYPE_BYTE: {
6363 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6364 res = metadata.update(tag,
6365 &entryValue,
6366 /*count*/1);
6367 break;
6368 }
6369 case TYPE_INT32:
6370 res = metadata.update(tag,
6371 &trigger.entryValue,
6372 /*count*/1);
6373 break;
6374 default:
6375 ALOGE("%s: Type not supported: 0x%x",
6376 __FUNCTION__,
6377 trigger.getTagType());
6378 return INVALID_OPERATION;
6379 }
6380
6381 if (res != OK) {
6382 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6383 ", value %d", __FUNCTION__, trigger.getTagName(),
6384 trigger.entryValue);
6385 return res;
6386 }
6387
6388 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6389 trigger.getTagName(),
6390 trigger.entryValue);
6391 }
6392
6393 mTriggerMap.clear();
6394
6395 return count;
6396}
6397
6398status_t Camera3Device::RequestThread::removeTriggers(
6399 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006400 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006401 Mutex::Autolock al(mTriggerMutex);
6402
Emilian Peevaebbe412018-01-15 13:53:24 +00006403 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006404
6405 /**
6406 * Replace all old entries with their old values.
6407 */
6408 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6409 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6410
6411 status_t res;
6412
6413 uint32_t tag = trigger.metadataTag;
6414 switch (trigger.getTagType()) {
6415 case TYPE_BYTE: {
6416 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6417 res = metadata.update(tag,
6418 &entryValue,
6419 /*count*/1);
6420 break;
6421 }
6422 case TYPE_INT32:
6423 res = metadata.update(tag,
6424 &trigger.entryValue,
6425 /*count*/1);
6426 break;
6427 default:
6428 ALOGE("%s: Type not supported: 0x%x",
6429 __FUNCTION__,
6430 trigger.getTagType());
6431 return INVALID_OPERATION;
6432 }
6433
6434 if (res != OK) {
6435 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6436 ", trigger value %d", __FUNCTION__,
6437 trigger.getTagName(), trigger.entryValue);
6438 return res;
6439 }
6440 }
6441 mTriggerReplacedMap.clear();
6442
6443 /**
6444 * Remove all new entries.
6445 */
6446 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6447 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6448 status_t res = metadata.erase(trigger.metadataTag);
6449
6450 if (res != OK) {
6451 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6452 ", trigger value %d", __FUNCTION__,
6453 trigger.getTagName(), trigger.entryValue);
6454 return res;
6455 }
6456 }
6457 mTriggerRemovedMap.clear();
6458
6459 return OK;
6460}
6461
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006462status_t Camera3Device::RequestThread::addDummyTriggerIds(
6463 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006464 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006465 static const int32_t dummyTriggerId = 1;
6466 status_t res;
6467
Emilian Peevaebbe412018-01-15 13:53:24 +00006468 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006469
6470 // If AF trigger is active, insert a dummy AF trigger ID if none already
6471 // exists
6472 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6473 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6474 if (afTrigger.count > 0 &&
6475 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6476 afId.count == 0) {
6477 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6478 if (res != OK) return res;
6479 }
6480
6481 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6482 // if none already exists
6483 camera_metadata_entry pcTrigger =
6484 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6485 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6486 if (pcTrigger.count > 0 &&
6487 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6488 pcId.count == 0) {
6489 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6490 &dummyTriggerId, 1);
6491 if (res != OK) return res;
6492 }
6493
6494 return OK;
6495}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006496
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006497/**
6498 * PreparerThread inner class methods
6499 */
6500
6501Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006502 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006503 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006504}
6505
6506Camera3Device::PreparerThread::~PreparerThread() {
6507 Thread::requestExitAndWait();
6508 if (mCurrentStream != nullptr) {
6509 mCurrentStream->cancelPrepare();
6510 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6511 mCurrentStream.clear();
6512 }
6513 clear();
6514}
6515
Ruben Brunkc78ac262015-08-13 17:58:46 -07006516status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006517 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006518 status_t res;
6519
6520 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006521 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006522
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006523 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006524 if (res == OK) {
6525 // No preparation needed, fire listener right off
6526 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006527 if (listener != NULL) {
6528 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006529 }
6530 return OK;
6531 } else if (res != NOT_ENOUGH_DATA) {
6532 return res;
6533 }
6534
6535 // Need to prepare, start up thread if necessary
6536 if (!mActive) {
6537 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6538 // isn't running
6539 Thread::requestExitAndWait();
6540 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6541 if (res != OK) {
6542 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006543 if (listener != NULL) {
6544 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006545 }
6546 return res;
6547 }
6548 mCancelNow = false;
6549 mActive = true;
6550 ALOGV("%s: Preparer stream started", __FUNCTION__);
6551 }
6552
6553 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006554 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006555 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6556
6557 return OK;
6558}
6559
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006560void Camera3Device::PreparerThread::pause() {
6561 ATRACE_CALL();
6562
6563 Mutex::Autolock l(mLock);
6564
6565 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6566 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6567 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6568 int currentMaxCount = mCurrentMaxCount;
6569 mPendingStreams.clear();
6570 mCancelNow = true;
6571 while (mActive) {
6572 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6573 if (res == TIMED_OUT) {
6574 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6575 return;
6576 } else if (res != OK) {
6577 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6578 return;
6579 }
6580 }
6581
6582 //Check whether the prepare thread was able to complete the current
6583 //stream. In case work is still pending emplace it along with the rest
6584 //of the streams in the pending list.
6585 if (currentStream != nullptr) {
6586 if (!mCurrentPrepareComplete) {
6587 pendingStreams.emplace(currentMaxCount, currentStream);
6588 }
6589 }
6590
6591 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6592 for (const auto& it : mPendingStreams) {
6593 it.second->cancelPrepare();
6594 }
6595}
6596
6597status_t Camera3Device::PreparerThread::resume() {
6598 ATRACE_CALL();
6599 status_t res;
6600
6601 Mutex::Autolock l(mLock);
6602 sp<NotificationListener> listener = mListener.promote();
6603
6604 if (mActive) {
6605 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6606 return NO_INIT;
6607 }
6608
6609 auto it = mPendingStreams.begin();
6610 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006611 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006612 if (res == OK) {
6613 if (listener != NULL) {
6614 listener->notifyPrepared(it->second->getId());
6615 }
6616 it = mPendingStreams.erase(it);
6617 } else if (res != NOT_ENOUGH_DATA) {
6618 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6619 res, strerror(-res));
6620 it = mPendingStreams.erase(it);
6621 } else {
6622 it++;
6623 }
6624 }
6625
6626 if (mPendingStreams.empty()) {
6627 return OK;
6628 }
6629
6630 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6631 if (res != OK) {
6632 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6633 __FUNCTION__, res, strerror(-res));
6634 return res;
6635 }
6636 mCancelNow = false;
6637 mActive = true;
6638 ALOGV("%s: Preparer stream started", __FUNCTION__);
6639
6640 return OK;
6641}
6642
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006643status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006644 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006645 Mutex::Autolock l(mLock);
6646
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006647 for (const auto& it : mPendingStreams) {
6648 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006649 }
6650 mPendingStreams.clear();
6651 mCancelNow = true;
6652
6653 return OK;
6654}
6655
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006656void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006657 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006658 Mutex::Autolock l(mLock);
6659 mListener = listener;
6660}
6661
6662bool Camera3Device::PreparerThread::threadLoop() {
6663 status_t res;
6664 {
6665 Mutex::Autolock l(mLock);
6666 if (mCurrentStream == nullptr) {
6667 // End thread if done with work
6668 if (mPendingStreams.empty()) {
6669 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6670 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6671 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6672 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006673 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006674 return false;
6675 }
6676
6677 // Get next stream to prepare
6678 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006679 mCurrentStream = it->second;
6680 mCurrentMaxCount = it->first;
6681 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006682 mPendingStreams.erase(it);
6683 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6684 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6685 } else if (mCancelNow) {
6686 mCurrentStream->cancelPrepare();
6687 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6688 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6689 mCurrentStream.clear();
6690 mCancelNow = false;
6691 return true;
6692 }
6693 }
6694
6695 res = mCurrentStream->prepareNextBuffer();
6696 if (res == NOT_ENOUGH_DATA) return true;
6697 if (res != OK) {
6698 // Something bad happened; try to recover by cancelling prepare and
6699 // signalling listener anyway
6700 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6701 mCurrentStream->getId(), res, strerror(-res));
6702 mCurrentStream->cancelPrepare();
6703 }
6704
6705 // This stream has finished, notify listener
6706 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006707 sp<NotificationListener> listener = mListener.promote();
6708 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006709 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6710 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006711 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006712 }
6713
6714 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6715 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006716 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006717
6718 return true;
6719}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006720
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006721status_t Camera3Device::RequestBufferStateMachine::initialize(
6722 sp<camera3::StatusTracker> statusTracker) {
6723 if (statusTracker == nullptr) {
6724 ALOGE("%s: statusTracker is null", __FUNCTION__);
6725 return BAD_VALUE;
6726 }
6727
6728 std::lock_guard<std::mutex> lock(mLock);
6729 mStatusTracker = statusTracker;
6730 mRequestBufferStatusId = statusTracker->addComponent();
6731 return OK;
6732}
6733
6734bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6735 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006736 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006737 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006738 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006739 return true;
6740 }
6741 return false;
6742}
6743
6744void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6745 std::lock_guard<std::mutex> lock(mLock);
6746 if (!mRequestBufferOngoing) {
6747 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6748 return;
6749 }
6750 mRequestBufferOngoing = false;
6751 if (mStatus == RB_STATUS_PENDING_STOP) {
6752 checkSwitchToStopLocked();
6753 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006754 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006755}
6756
6757void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6758 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006759 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006760 return;
6761}
6762
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006763void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006764 std::lock_guard<std::mutex> lock(mLock);
6765 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006766 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6767 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006768 mInflightMapEmpty = false;
6769 if (mStatus == RB_STATUS_STOPPED) {
6770 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006771 }
6772 return;
6773}
6774
6775void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6776 std::lock_guard<std::mutex> lock(mLock);
6777 mRequestThreadPaused = true;
6778 if (mStatus == RB_STATUS_PENDING_STOP) {
6779 checkSwitchToStopLocked();
6780 }
6781 return;
6782}
6783
6784void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6785 std::lock_guard<std::mutex> lock(mLock);
6786 mInflightMapEmpty = true;
6787 if (mStatus == RB_STATUS_PENDING_STOP) {
6788 checkSwitchToStopLocked();
6789 }
6790 return;
6791}
6792
6793void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6794 std::lock_guard<std::mutex> lock(mLock);
6795 if (!checkSwitchToStopLocked()) {
6796 mStatus = RB_STATUS_PENDING_STOP;
6797 }
6798 return;
6799}
6800
6801void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6802 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6803 if (statusTracker != nullptr) {
6804 if (active) {
6805 statusTracker->markComponentActive(mRequestBufferStatusId);
6806 } else {
6807 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6808 }
6809 }
6810}
6811
6812bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6813 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6814 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006815 return true;
6816 }
6817 return false;
6818}
6819
Shuzhen Wang268a1362018-10-16 16:32:59 -07006820status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6821 CameraMetadata& resultMetadata) {
6822 status_t res = OK;
6823 if (!mNeedFixupMonochromeTags) {
6824 return res;
6825 }
6826
6827 // Remove tags that are not applicable to monochrome camera.
6828 int32_t tagsToRemove[] = {
6829 ANDROID_SENSOR_GREEN_SPLIT,
6830 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6831 ANDROID_COLOR_CORRECTION_MODE,
6832 ANDROID_COLOR_CORRECTION_TRANSFORM,
6833 ANDROID_COLOR_CORRECTION_GAINS,
6834 };
6835 for (auto tag : tagsToRemove) {
6836 res = resultMetadata.erase(tag);
6837 if (res != OK) {
6838 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6839 return res;
6840 }
6841 }
6842
6843 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6844 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6845 for (size_t i = 1; i < blEntry.count; i++) {
6846 blEntry.data.f[i] = blEntry.data.f[0];
6847 }
6848
6849 // ANDROID_SENSOR_NOISE_PROFILE
6850 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6851 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6852 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6853 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6854 if (res != OK) {
6855 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6856 __FUNCTION__, strerror(-res), res);
6857 return res;
6858 }
6859 }
6860
6861 // ANDROID_STATISTICS_LENS_SHADING_MAP
6862 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6863 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6864 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6865 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6866 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6867 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6868 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6869 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6870 }
6871 }
6872
6873 // ANDROID_TONEMAP_CURVE_BLUE
6874 // ANDROID_TONEMAP_CURVE_GREEN
6875 // ANDROID_TONEMAP_CURVE_RED
6876 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6877 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6878 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6879 if (tcbEntry.count > 0
6880 && tcbEntry.count == tcgEntry.count
6881 && tcbEntry.count == tcrEntry.count) {
6882 for (size_t i = 0; i < tcbEntry.count; i++) {
6883 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6884 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6885 }
6886 }
6887
6888 return res;
6889}
6890
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006891status_t Camera3Device::switchToOffline(
6892 const std::vector<int32_t>& streamsToKeep,
6893 /*out*/ sp<CameraOfflineSessionBase>* session) {
6894 ATRACE_CALL();
6895 if (session == nullptr) {
6896 ALOGE("%s: session must not be null", __FUNCTION__);
6897 return BAD_VALUE;
6898 }
6899
6900 Mutex::Autolock il(mInterfaceLock);
6901 Mutex::Autolock l(mLock);
6902
6903 // 1. Stop repeating request, wait until request thread submitted all requests, then
6904 // call HAL switchToOffline
6905 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6906 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
6907
6908 mRequestThread->switchToOffline(streamsToKeep, &offlineSessionInfo, &offlineSession);
6909
6910
6911 // 2. Verify offlineSessionInfo
6912 // 3. create Camera3OfflineSession and transfer object ownership
6913 // (streams, inflight requests, buffer caches)
6914 *session = new Camera3OfflineSession(mId);
6915
6916 // 4. Delete unneeded streams
6917 // 5. Verify Camera3Device is in unconfigured state
6918 return OK;
6919}
6920
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006921}; // namespace android