blob: 923d17a281104a075a02676c232f2e79b7f4f21c [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
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Shuzhen Wang5c22c152017-12-31 17:12:25 -080042#include <utility>
43
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080044#include <utils/Log.h>
45#include <utils/Trace.h>
46#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070047#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070048
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080049#include <android/hardware/camera2/ICameraDeviceUser.h>
50
Igor Murashkinff3e31d2013-10-23 16:40:06 -070051#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070052#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "device3/Camera3Device.h"
54#include "device3/Camera3OutputStream.h"
55#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070056#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070057#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070058#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070059#include "utils/CameraThreadState.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080060
61using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080062using namespace android::hardware::camera;
63using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080064
65namespace android {
66
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080067Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080068 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080069 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070070 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070071 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070072 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070073 mUsePartialResult(false),
74 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080075 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070076 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070077 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070078 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070079 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000080 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010081 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070082 mLastTemplateId(-1),
83 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080084{
85 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080086 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080087}
88
89Camera3Device::~Camera3Device()
90{
91 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080092 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -070093 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080094}
95
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080096const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080097 return mId;
98}
99
Emilian Peevbd8c5032018-02-14 23:05:40 +0000100status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ATRACE_CALL();
102 Mutex::Autolock il(mInterfaceLock);
103 Mutex::Autolock l(mLock);
104
105 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
106 if (mStatus != STATUS_UNINITIALIZED) {
107 CLOGE("Already initialized!");
108 return INVALID_OPERATION;
109 }
110 if (manager == nullptr) return INVALID_OPERATION;
111
112 sp<ICameraDeviceSession> session;
113 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800114 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115 /*out*/ &session);
116 ATRACE_END();
117 if (res != OK) {
118 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
119 return res;
120 }
121
Steven Moreland5ff9c912017-03-09 23:13:00 -0800122 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700124 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125 session->close();
126 return res;
127 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800128
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700129 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700130 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700131 if (isLogical) {
132 for (auto& physicalId : physicalCameraIds) {
133 res = manager->getCameraCharacteristics(physicalId, &mPhysicalDeviceInfoMap[physicalId]);
134 if (res != OK) {
135 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
136 physicalId.c_str(), strerror(-res), res);
137 session->close();
138 return res;
139 }
140 }
141 }
142
Yifan Hongf79b5542017-04-11 14:44:25 -0700143 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700144 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
145 [&queue](const auto& descriptor) {
146 queue = std::make_shared<RequestMetadataQueue>(descriptor);
147 if (!queue->isValid() || queue->availableToWrite() <= 0) {
148 ALOGE("HAL returns empty request metadata fmq, not use it");
149 queue = nullptr;
150 // don't use the queue onwards.
151 }
152 });
153 if (!requestQueueRet.isOk()) {
154 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
155 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700156 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700157 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700158
159 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700160 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700161 [&resQueue](const auto& descriptor) {
162 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
163 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700164 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700165 resQueue = nullptr;
166 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700167 }
168 });
169 if (!resultQueueRet.isOk()) {
170 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
171 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700172 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700173 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700174 IF_ALOGV() {
175 session->interfaceChain([](
176 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
177 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800178 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700179 ALOGV(" %s", iface.c_str());
180 }
181 });
182 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700183
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800184 camera_metadata_entry bufMgrMode =
185 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
186 if (bufMgrMode.count > 0) {
187 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
188 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
189 }
190
191 mInterface = new HalInterface(session, queue, mUseHalBufManager);
Emilian Peev71c73a22017-03-21 16:35:51 +0000192 std::string providerType;
193 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000194 mTagMonitor.initialize(mVendorTagId);
195 if (!monitorTags.isEmpty()) {
196 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
197 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800198
Shuzhen Wang268a1362018-10-16 16:32:59 -0700199 // Metadata tags needs fixup for monochrome camera device version less
200 // than 3.5.
201 hardware::hidl_version maxVersion{0,0};
202 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
203 if (res != OK) {
204 ALOGE("%s: Error in getting camera device version id: %s (%d)",
205 __FUNCTION__, strerror(-res), res);
206 return res;
207 }
208 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
209 maxVersion.get_major(), maxVersion.get_minor());
210
211 bool isMonochrome = false;
212 camera_metadata_entry_t entry = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
213 for (size_t i = 0; i < entry.count; i++) {
214 uint8_t capability = entry.data.u8[i];
215 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
216 isMonochrome = true;
217 }
218 }
219 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
220
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800221 return initializeCommonLocked();
222}
223
224status_t Camera3Device::initializeCommonLocked() {
225
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700226 /** Start up status tracker thread */
227 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800228 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700229 if (res != OK) {
230 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
231 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800232 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700233 mStatusTracker.clear();
234 return res;
235 }
236
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700237 /** Register in-flight map to the status tracker */
238 mInFlightStatusId = mStatusTracker->addComponent();
239
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700240 if (mUseHalBufManager) {
241 res = mRequestBufferSM.initialize(mStatusTracker);
242 if (res != OK) {
243 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
244 strerror(-res), res);
245 mInterface->close();
246 mStatusTracker.clear();
247 return res;
248 }
249 }
250
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800251 /** Create buffer manager */
252 mBufferManager = new Camera3BufferManager();
253
254 Vector<int32_t> sessionParamKeys;
255 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
256 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
257 if (sessionKeysEntry.count > 0) {
258 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
259 }
260
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700261 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700262 mRequestThread = new RequestThread(
263 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800264 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800265 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700266 SET_ERR_L("Unable to start request queue thread: %s (%d)",
267 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800268 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800269 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800270 return res;
271 }
272
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700273 mPreparerThread = new PreparerThread();
274
Ruben Brunk183f0562015-08-12 12:55:02 -0700275 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800276 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700277 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700278 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700279 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800280
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800281 // Measure the clock domain offset between camera and video/hw_composer
282 camera_metadata_entry timestampSource =
283 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
284 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
285 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
286 mTimestampOffset = getMonoToBoottimeOffset();
287 }
288
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700289 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100290 camera_metadata_entry partialResultsCount =
291 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
292 if (partialResultsCount.count > 0) {
293 mNumPartialResults = partialResultsCount.data.i32[0];
294 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700295 }
296
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700297 camera_metadata_entry configs =
298 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
299 for (uint32_t i = 0; i < configs.count; i += 4) {
300 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
301 configs.data.i32[i + 3] ==
302 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
303 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
304 configs.data.i32[i + 2]));
305 }
306 }
307
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700308 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
309 res = mDistortionMapper.setupStaticInfo(mDeviceInfo);
310 if (res != OK) {
311 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
312 return res;
313 }
314 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800315 return OK;
316}
317
318status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700319 return disconnectImpl();
320}
321
322status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800323 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700324 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800325
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700326 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800327
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700328 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700329 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700330 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700331 {
332 Mutex::Autolock l(mLock);
333 if (mStatus == STATUS_UNINITIALIZED) return res;
334
335 if (mStatus == STATUS_ACTIVE ||
336 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
337 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700338 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700339 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700340 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700341 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700342 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700343 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700344 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
345 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700346 // Continue to close device even in case of error
347 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700348 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800349 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800350
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700351 if (mStatus == STATUS_ERROR) {
352 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700353 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700354
355 if (mStatusTracker != NULL) {
356 mStatusTracker->requestExit();
357 }
358
359 if (mRequestThread != NULL) {
360 mRequestThread->requestExit();
361 }
362
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700363 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
364 for (size_t i = 0; i < mOutputStreams.size(); i++) {
365 streams.push_back(mOutputStreams[i]);
366 }
367 if (mInputStream != nullptr) {
368 streams.push_back(mInputStream);
369 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700370 }
371
372 // Joining done without holding mLock, otherwise deadlocks may ensue
373 // as the threads try to access parent state
374 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
375 // HAL may be in a bad state, so waiting for request thread
376 // (which may be stuck in the HAL processCaptureRequest call)
377 // could be dangerous.
378 mRequestThread->join();
379 }
380
381 if (mStatusTracker != NULL) {
382 mStatusTracker->join();
383 }
384
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800385 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700386 {
387 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800388 mRequestThread.clear();
Emilian Peev2843c362018-09-26 08:49:40 +0100389 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700390 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800391 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700392 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800393
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700394 // Call close without internal mutex held, as the HAL close may need to
395 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800396 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700397
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700398 flushInflightRequests();
399
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700400 {
401 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800402 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700403 mOutputStreams.clear();
404 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700405 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700406 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700407 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700408 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800409
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700410 for (auto& weakStream : streams) {
411 sp<Camera3StreamInterface> stream = weakStream.promote();
412 if (stream != nullptr) {
413 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
414 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
415 }
416 }
417
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700418 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700419 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800420}
421
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700422// For dumping/debugging only -
423// try to acquire a lock a few times, eventually give up to proceed with
424// debug/dump operations
425bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
426 bool gotLock = false;
427 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
428 if (lock.tryLock() == NO_ERROR) {
429 gotLock = true;
430 break;
431 } else {
432 usleep(kDumpSleepDuration);
433 }
434 }
435 return gotLock;
436}
437
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700438Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
439 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100440 const int STREAM_CONFIGURATION_SIZE = 4;
441 const int STREAM_FORMAT_OFFSET = 0;
442 const int STREAM_WIDTH_OFFSET = 1;
443 const int STREAM_HEIGHT_OFFSET = 2;
444 const int STREAM_IS_INPUT_OFFSET = 3;
445 camera_metadata_ro_entry_t availableStreamConfigs =
446 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
447 if (availableStreamConfigs.count == 0 ||
448 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
449 return Size(0, 0);
450 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700451
Emilian Peev08dd2452017-04-06 16:55:14 +0100452 // Get max jpeg size (area-wise).
453 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
454 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
455 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
456 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
457 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
458 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
459 && format == HAL_PIXEL_FORMAT_BLOB &&
460 (width * height > maxJpegWidth * maxJpegHeight)) {
461 maxJpegWidth = width;
462 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700463 }
464 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100465
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700466 return Size(maxJpegWidth, maxJpegHeight);
467}
468
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800469nsecs_t Camera3Device::getMonoToBoottimeOffset() {
470 // try three times to get the clock offset, choose the one
471 // with the minimum gap in measurements.
472 const int tries = 3;
473 nsecs_t bestGap, measured;
474 for (int i = 0; i < tries; ++i) {
475 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
476 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
477 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
478 const nsecs_t gap = tmono2 - tmono;
479 if (i == 0 || gap < bestGap) {
480 bestGap = gap;
481 measured = tbase - ((tmono + tmono2) >> 1);
482 }
483 }
484 return measured;
485}
486
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800487hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
488 int frameworkFormat) {
489 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
490}
491
492DataspaceFlags Camera3Device::mapToHidlDataspace(
493 android_dataspace dataSpace) {
494 return dataSpace;
495}
496
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700497BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100498 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700499 return usage;
500}
501
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800502StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
503 switch (rotation) {
504 case CAMERA3_STREAM_ROTATION_0:
505 return StreamRotation::ROTATION_0;
506 case CAMERA3_STREAM_ROTATION_90:
507 return StreamRotation::ROTATION_90;
508 case CAMERA3_STREAM_ROTATION_180:
509 return StreamRotation::ROTATION_180;
510 case CAMERA3_STREAM_ROTATION_270:
511 return StreamRotation::ROTATION_270;
512 }
513 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
514 return StreamRotation::ROTATION_0;
515}
516
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800517status_t Camera3Device::mapToStreamConfigurationMode(
518 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
519 if (mode == nullptr) return BAD_VALUE;
520 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
521 switch(operationMode) {
522 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
523 *mode = StreamConfigurationMode::NORMAL_MODE;
524 break;
525 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
526 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
527 break;
528 default:
529 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
530 return BAD_VALUE;
531 }
532 } else {
533 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800535 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800536}
537
538camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
539 switch (status) {
540 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
541 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
542 }
543 return CAMERA3_BUFFER_STATUS_ERROR;
544}
545
546int Camera3Device::mapToFrameworkFormat(
547 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
548 return static_cast<uint32_t>(pixelFormat);
549}
550
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700551android_dataspace Camera3Device::mapToFrameworkDataspace(
552 DataspaceFlags dataSpace) {
553 return static_cast<android_dataspace>(dataSpace);
554}
555
Emilian Peev050f5dc2017-05-18 14:43:56 +0100556uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700557 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700558 return usage;
559}
560
Emilian Peev050f5dc2017-05-18 14:43:56 +0100561uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700562 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700563 return usage;
564}
565
Zhijun Hef7da0962014-04-24 13:27:56 -0700566ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700567 // Get max jpeg size (area-wise).
568 Size maxJpegResolution = getMaxJpegResolution();
569 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800570 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
571 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700572 return BAD_VALUE;
573 }
574
Zhijun Hef7da0962014-04-24 13:27:56 -0700575 // Get max jpeg buffer size
576 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700577 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
578 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800579 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
580 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700581 return BAD_VALUE;
582 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700583 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800584 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700585
586 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700587 float scaleFactor = ((float) (width * height)) /
588 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800589 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
590 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700591 if (jpegBufferSize > maxJpegBufferSize) {
592 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700593 }
594
595 return jpegBufferSize;
596}
597
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700598ssize_t Camera3Device::getPointCloudBufferSize() const {
599 const int FLOATS_PER_POINT=4;
600 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
601 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800602 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
603 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700604 return BAD_VALUE;
605 }
606 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
607 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
608 return maxBytesForPointCloud;
609}
610
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800611ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800612 const int PER_CONFIGURATION_SIZE = 3;
613 const int WIDTH_OFFSET = 0;
614 const int HEIGHT_OFFSET = 1;
615 const int SIZE_OFFSET = 2;
616 camera_metadata_ro_entry rawOpaqueSizes =
617 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800618 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800619 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800620 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
621 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800622 return BAD_VALUE;
623 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700624
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800625 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
626 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
627 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
628 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
629 }
630 }
631
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800632 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
633 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800634 return BAD_VALUE;
635}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700636
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800637status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
638 ATRACE_CALL();
639 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700640
641 // Try to lock, but continue in case of failure (to avoid blocking in
642 // deadlocks)
643 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
644 bool gotLock = tryLockSpinRightRound(mLock);
645
646 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800647 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
648 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700649 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800650 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
651 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700652
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800653 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700654
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800655 String16 templatesOption("-t");
656 int n = args.size();
657 for (int i = 0; i < n; i++) {
658 if (args[i] == templatesOption) {
659 dumpTemplates = true;
660 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000661 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700662 if (i + 1 < n) {
663 String8 monitorTags = String8(args[i + 1]);
664 if (monitorTags == "off") {
665 mTagMonitor.disableMonitoring();
666 } else {
667 mTagMonitor.parseTagsToMonitor(monitorTags);
668 }
669 } else {
670 mTagMonitor.disableMonitoring();
671 }
672 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800673 }
674
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800675 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800676
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800677 const char *status =
678 mStatus == STATUS_ERROR ? "ERROR" :
679 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700680 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
681 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800682 mStatus == STATUS_ACTIVE ? "ACTIVE" :
683 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700684
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800685 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700686 if (mStatus == STATUS_ERROR) {
687 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
688 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800689 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800690 const char *mode =
691 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
692 mOperatingMode == static_cast<int>(
693 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
694 "CUSTOM";
695 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800696
697 if (mInputStream != NULL) {
698 write(fd, lines.string(), lines.size());
699 mInputStream->dump(fd, args);
700 } else {
701 lines.appendFormat(" No input stream.\n");
702 write(fd, lines.string(), lines.size());
703 }
704 for (size_t i = 0; i < mOutputStreams.size(); i++) {
705 mOutputStreams[i]->dump(fd,args);
706 }
707
Zhijun He431503c2016-03-07 17:30:16 -0800708 if (mBufferManager != NULL) {
709 lines = String8(" Camera3 Buffer Manager:\n");
710 write(fd, lines.string(), lines.size());
711 mBufferManager->dump(fd, args);
712 }
Zhijun He125684a2015-12-26 15:07:30 -0800713
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700714 lines = String8(" In-flight requests:\n");
715 if (mInFlightMap.size() == 0) {
716 lines.append(" None\n");
717 } else {
718 for (size_t i = 0; i < mInFlightMap.size(); i++) {
719 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700720 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700721 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800722 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700723 r.numBuffersLeft);
724 }
725 }
726 write(fd, lines.string(), lines.size());
727
Shuzhen Wang686f6442017-06-20 16:16:04 -0700728 if (mRequestThread != NULL) {
729 mRequestThread->dumpCaptureRequestLatency(fd,
730 " ProcessCaptureRequest latency histogram:");
731 }
732
Igor Murashkin1e479c02013-09-06 16:55:14 -0700733 {
734 lines = String8(" Last request sent:\n");
735 write(fd, lines.string(), lines.size());
736
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700737 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700738 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
739 }
740
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800741 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800742 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800743 "TEMPLATE_PREVIEW",
744 "TEMPLATE_STILL_CAPTURE",
745 "TEMPLATE_VIDEO_RECORD",
746 "TEMPLATE_VIDEO_SNAPSHOT",
747 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800748 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800749 };
750
751 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800752 camera_metadata_t *templateRequest = nullptr;
753 mInterface->constructDefaultRequestSettings(
754 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800755 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800756 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800757 lines.append(" Not supported\n");
758 write(fd, lines.string(), lines.size());
759 } else {
760 write(fd, lines.string(), lines.size());
761 dump_indented_camera_metadata(templateRequest,
762 fd, /*verbosity*/2, /*indentation*/8);
763 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800764 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800765 }
766 }
767
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700768 mTagMonitor.dumpMonitoredMetadata(fd);
769
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800770 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800771 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800772 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800773 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800774 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800775
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700776 if (gotLock) mLock.unlock();
777 if (gotInterfaceLock) mInterfaceLock.unlock();
778
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800779 return OK;
780}
781
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700782const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800783 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800784 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
785 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700786 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800787 mStatus == STATUS_ERROR ?
788 "when in error state" : "before init");
789 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700790 if (physicalId.isEmpty()) {
791 return mDeviceInfo;
792 } else {
793 std::string id(physicalId.c_str());
794 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
795 return mPhysicalDeviceInfoMap.at(id);
796 } else {
797 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
798 return mDeviceInfo;
799 }
800 }
801}
802
803const CameraMetadata& Camera3Device::info() const {
804 String8 emptyId;
805 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800806}
807
Jianing Wei90e59c92014-03-12 18:29:36 -0700808status_t Camera3Device::checkStatusOkToCaptureLocked() {
809 switch (mStatus) {
810 case STATUS_ERROR:
811 CLOGE("Device has encountered a serious error");
812 return INVALID_OPERATION;
813 case STATUS_UNINITIALIZED:
814 CLOGE("Device not initialized");
815 return INVALID_OPERATION;
816 case STATUS_UNCONFIGURED:
817 case STATUS_CONFIGURED:
818 case STATUS_ACTIVE:
819 // OK
820 break;
821 default:
822 SET_ERR_L("Unexpected status: %d", mStatus);
823 return INVALID_OPERATION;
824 }
825 return OK;
826}
827
828status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000829 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700830 const std::list<const SurfaceMap> &surfaceMaps,
831 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700832 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700833 if (requestList == NULL) {
834 CLOGE("requestList cannot be NULL.");
835 return BAD_VALUE;
836 }
837
Jianing Weicb0652e2014-03-12 18:29:36 -0700838 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000839 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700840 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
841 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
842 ++metadataIt, ++surfaceMapIt) {
843 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700844 if (newRequest == 0) {
845 CLOGE("Can't create capture request");
846 return BAD_VALUE;
847 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700848
Shuzhen Wang9d066012016-09-30 11:30:20 -0700849 newRequest->mRepeating = repeating;
850
Jianing Weicb0652e2014-03-12 18:29:36 -0700851 // Setup burst Id and request Id
852 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000853 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
854 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700855 CLOGE("RequestID entry exists; but must not be empty in metadata");
856 return BAD_VALUE;
857 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000858 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
859 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700860 } else {
861 CLOGE("RequestID does not exist in metadata");
862 return BAD_VALUE;
863 }
864
Jianing Wei90e59c92014-03-12 18:29:36 -0700865 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700866
867 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700868 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700869 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
870 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
871 return BAD_VALUE;
872 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700873
874 // Setup batch size if this is a high speed video recording request.
875 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
876 auto firstRequest = requestList->begin();
877 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
878 if (outputStream->isVideoStream()) {
879 (*firstRequest)->mBatchSize = requestList->size();
880 break;
881 }
882 }
883 }
884
Jianing Wei90e59c92014-03-12 18:29:36 -0700885 return OK;
886}
887
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800888status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800889 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800890
Emilian Peevaebbe412018-01-15 13:53:24 +0000891 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700892 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000893 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700894
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800895 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700896}
897
Emilian Peevaebbe412018-01-15 13:53:24 +0000898void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700899 std::list<const SurfaceMap>& surfaceMaps,
900 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000901 PhysicalCameraSettingsList requestList;
902 requestList.push_back({std::string(getId().string()), request});
903 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700904
905 SurfaceMap surfaceMap;
906 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
907 // With no surface list passed in, stream and surface will have 1-to-1
908 // mapping. So the surface index is 0 for each stream in the surfaceMap.
909 for (size_t i = 0; i < streams.count; i++) {
910 surfaceMap[streams.data.i32[i]].push_back(0);
911 }
912 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800913}
914
Jianing Wei90e59c92014-03-12 18:29:36 -0700915status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000916 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700917 const std::list<const SurfaceMap> &surfaceMaps,
918 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700919 /*out*/
920 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700921 ATRACE_CALL();
922 Mutex::Autolock il(mInterfaceLock);
923 Mutex::Autolock l(mLock);
924
925 status_t res = checkStatusOkToCaptureLocked();
926 if (res != OK) {
927 // error logged by previous call
928 return res;
929 }
930
931 RequestList requestList;
932
Shuzhen Wang0129d522016-10-30 22:43:41 -0700933 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
934 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700935 if (res != OK) {
936 // error logged by previous call
937 return res;
938 }
939
940 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700941 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700942 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700943 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700944 }
945
946 if (res == OK) {
947 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
948 if (res != OK) {
949 SET_ERR_L("Can't transition to active in %f seconds!",
950 kActiveTimeout/1e9);
951 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800952 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700953 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700954 } else {
955 CLOGE("Cannot queue request. Impossible.");
956 return BAD_VALUE;
957 }
958
959 return res;
960}
961
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700962hardware::Return<void> Camera3Device::requestStreamBuffers(
963 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
964 requestStreamBuffers_cb _hidl_cb) {
965 using hardware::camera::device::V3_5::BufferRequestStatus;
966 using hardware::camera::device::V3_5::StreamBufferRet;
967 using hardware::camera::device::V3_5::StreamBufferRequestError;
968
969 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
970
971 hardware::hidl_vec<StreamBufferRet> bufRets;
972 if (!mUseHalBufManager) {
973 ALOGE("%s: Camera %s does not support HAL buffer management",
974 __FUNCTION__, mId.string());
975 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
976 return hardware::Void();
977 }
978
979 SortedVector<int32_t> streamIds;
980 ssize_t sz = streamIds.setCapacity(bufReqs.size());
981 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
982 ALOGE("%s: failed to allocate memory for %zu buffer requests",
983 __FUNCTION__, bufReqs.size());
984 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
985 return hardware::Void();
986 }
987
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700988 if (bufReqs.size() > mOutputStreams.size()) {
989 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
990 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
991 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
992 return hardware::Void();
993 }
994
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700995 // Check for repeated streamId
996 for (const auto& bufReq : bufReqs) {
997 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
998 ALOGE("%s: Stream %d appear multiple times in buffer requests",
999 __FUNCTION__, bufReq.streamId);
1000 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1001 return hardware::Void();
1002 }
1003 streamIds.add(bufReq.streamId);
1004 }
1005
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001006 if (!mRequestBufferSM.startRequestBuffer()) {
1007 ALOGE("%s: request buffer disallowed while camera service is configuring",
1008 __FUNCTION__);
1009 _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001010 return hardware::Void();
1011 }
1012
1013 bufRets.resize(bufReqs.size());
1014
1015 bool allReqsSucceeds = true;
1016 bool oneReqSucceeds = false;
1017 for (size_t i = 0; i < bufReqs.size(); i++) {
1018 const auto& bufReq = bufReqs[i];
1019 auto& bufRet = bufRets[i];
1020 int32_t streamId = bufReq.streamId;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001021 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
1022 if (outputStream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001023 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
1024 hardware::hidl_vec<StreamBufferRet> emptyBufRets;
1025 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001026 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001027 return hardware::Void();
1028 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001029
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001030 if (outputStream->isAbandoned()) {
1031 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1032 allReqsSucceeds = false;
1033 continue;
1034 }
1035
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001036 bufRet.streamId = streamId;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001037 size_t handOutBufferCount = outputStream->getOutstandingBuffersCount();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001038 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001039 size_t totalHandout = handOutBufferCount + numBuffersRequested;
1040 uint32_t maxBuffers = outputStream->asHalStream()->max_buffers;
1041 if (totalHandout > maxBuffers) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001042 // Not able to allocate enough buffer. Exit early for this stream
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001043 ALOGE("%s: request too much buffers for stream %d: at HAL: %zu + requesting: %d"
1044 " > max: %d", __FUNCTION__, streamId, handOutBufferCount,
1045 numBuffersRequested, maxBuffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001046 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1047 allReqsSucceeds = false;
1048 continue;
1049 }
1050
1051 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1052 bool currentReqSucceeds = true;
1053 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1054 size_t numAllocatedBuffers = 0;
1055 size_t numPushedInflightBuffers = 0;
1056 for (size_t b = 0; b < numBuffersRequested; b++) {
1057 camera3_stream_buffer_t& sb = streamBuffers[b];
1058 // Since this method can run concurrently with request thread
1059 // We need to update the wait duration everytime we call getbuffer
1060 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1061 status_t res = outputStream->getBuffer(&sb, waitDuration);
1062 if (res != OK) {
1063 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1064 __FUNCTION__, streamId, strerror(-res), res);
1065 if (res == NO_INIT || res == DEAD_OBJECT) {
1066 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1067 } else if (res == TIMED_OUT || res == NO_MEMORY) {
1068 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1069 } else {
1070 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1071 }
1072 currentReqSucceeds = false;
1073 break;
1074 }
1075 numAllocatedBuffers++;
1076
1077 buffer_handle_t *buffer = sb.buffer;
1078 auto pair = mInterface->getBufferId(*buffer, streamId);
1079 bool isNewBuffer = pair.first;
1080 uint64_t bufferId = pair.second;
1081 StreamBuffer& hBuf = tmpRetBuffers[b];
1082
1083 hBuf.streamId = streamId;
1084 hBuf.bufferId = bufferId;
1085 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1086 hBuf.status = BufferStatus::OK;
1087 hBuf.releaseFence = nullptr;
1088
1089 native_handle_t *acquireFence = nullptr;
1090 if (sb.acquire_fence != -1) {
1091 acquireFence = native_handle_create(1,0);
1092 acquireFence->data[0] = sb.acquire_fence;
1093 }
1094 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1095 hBuf.releaseFence = nullptr;
1096
1097 res = mInterface->pushInflightRequestBuffer(bufferId, buffer);
1098 if (res != OK) {
1099 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1100 __FUNCTION__, streamId, strerror(-res), res);
1101 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1102 currentReqSucceeds = false;
1103 break;
1104 }
1105 numPushedInflightBuffers++;
1106 }
1107 if (currentReqSucceeds) {
1108 bufRet.val.buffers(std::move(tmpRetBuffers));
1109 oneReqSucceeds = true;
1110 } else {
1111 allReqsSucceeds = false;
1112 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1113 StreamBuffer& hBuf = tmpRetBuffers[b];
1114 buffer_handle_t* buffer;
1115 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1116 if (res != OK) {
1117 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1118 __FUNCTION__, streamId, strerror(-res), res);
1119 }
1120 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001121 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1122 camera3_stream_buffer_t& sb = streamBuffers[b];
1123 sb.acquire_fence = -1;
1124 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1125 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001126 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1127 }
1128 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001129
1130 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1131 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1132 BufferRequestStatus::FAILED_UNKNOWN,
1133 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001134 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001135 return hardware::Void();
1136}
1137
1138hardware::Return<void> Camera3Device::returnStreamBuffers(
1139 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1140 if (!mUseHalBufManager) {
1141 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1142 __FUNCTION__, mId.string());
1143 return hardware::Void();
1144 }
1145
1146 for (const auto& buf : buffers) {
1147 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1148 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1149 continue;
1150 }
1151
1152 buffer_handle_t* buffer;
1153 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1154
1155 if (res != OK) {
1156 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1157 __FUNCTION__, buf.bufferId, buf.streamId);
1158 continue;
1159 }
1160
1161 camera3_stream_buffer_t streamBuffer;
1162 streamBuffer.buffer = buffer;
1163 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1164 streamBuffer.acquire_fence = -1;
1165 streamBuffer.release_fence = -1;
1166
1167 if (buf.releaseFence == nullptr) {
1168 streamBuffer.release_fence = -1;
1169 } else if (buf.releaseFence->numFds == 1) {
1170 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1171 } else {
1172 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1173 __FUNCTION__, buf.releaseFence->numFds);
1174 continue;
1175 }
1176
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001177 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1178 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001179 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1180 continue;
1181 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001182 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001183 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1184 }
1185 return hardware::Void();
1186}
1187
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001188hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001189 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001190 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001191 // Ideally we should grab mLock, but that can lead to deadlock, and
1192 // it's not super important to get up to date value of mStatus for this
1193 // warning print, hence skipping the lock here
1194 if (mStatus == STATUS_ERROR) {
1195 // Per API contract, HAL should act as closed after device error
1196 // But mStatus can be set to error by framework as well, so just log
1197 // a warning here.
1198 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001199 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001200
1201 if (mProcessCaptureResultLock.tryLock() != OK) {
1202 // This should never happen; it indicates a wrong client implementation
1203 // that doesn't follow the contract. But, we can be tolerant here.
1204 ALOGE("%s: callback overlapped! waiting 1s...",
1205 __FUNCTION__);
1206 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1207 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1208 __FUNCTION__);
1209 // really don't know what to do, so bail out.
1210 return hardware::Void();
1211 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001212 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001213 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001214 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001215 }
1216 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001217 return hardware::Void();
1218}
1219
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001220// Only one processCaptureResult should be called at a time, so
1221// the locks won't block. The locks are present here simply to enforce this.
1222hardware::Return<void> Camera3Device::processCaptureResult(
1223 const hardware::hidl_vec<
1224 hardware::camera::device::V3_2::CaptureResult>& results) {
1225 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1226
1227 // Ideally we should grab mLock, but that can lead to deadlock, and
1228 // it's not super important to get up to date value of mStatus for this
1229 // warning print, hence skipping the lock here
1230 if (mStatus == STATUS_ERROR) {
1231 // Per API contract, HAL should act as closed after device error
1232 // But mStatus can be set to error by framework as well, so just log
1233 // a warning here.
1234 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1235 }
1236
1237 if (mProcessCaptureResultLock.tryLock() != OK) {
1238 // This should never happen; it indicates a wrong client implementation
1239 // that doesn't follow the contract. But, we can be tolerant here.
1240 ALOGE("%s: callback overlapped! waiting 1s...",
1241 __FUNCTION__);
1242 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1243 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1244 __FUNCTION__);
1245 // really don't know what to do, so bail out.
1246 return hardware::Void();
1247 }
1248 }
1249 for (const auto& result : results) {
1250 processOneCaptureResultLocked(result, noPhysMetadata);
1251 }
1252 mProcessCaptureResultLock.unlock();
1253 return hardware::Void();
1254}
1255
1256status_t Camera3Device::readOneCameraMetadataLocked(
1257 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1258 const hardware::camera::device::V3_2::CameraMetadata& result) {
1259 if (fmqResultSize > 0) {
1260 resultMetadata.resize(fmqResultSize);
1261 if (mResultMetadataQueue == nullptr) {
1262 return NO_MEMORY; // logged in initialize()
1263 }
1264 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1265 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1266 __FUNCTION__, fmqResultSize);
1267 return INVALID_OPERATION;
1268 }
1269 } else {
1270 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1271 result.size());
1272 }
1273
1274 if (resultMetadata.size() != 0) {
1275 status_t res;
1276 const camera_metadata_t* metadata =
1277 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1278 size_t expected_metadata_size = resultMetadata.size();
1279 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1280 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1281 __FUNCTION__, strerror(-res), res);
1282 return INVALID_OPERATION;
1283 }
1284 }
1285
1286 return OK;
1287}
1288
Yifan Honga640c5a2017-04-12 16:30:31 -07001289void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001290 const hardware::camera::device::V3_2::CaptureResult& result,
1291 const hardware::hidl_vec<
1292 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001293 camera3_capture_result r;
1294 status_t res;
1295 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001296
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001297 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001298 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001299 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1300 if (res != OK) {
1301 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1302 __FUNCTION__, result.frameNumber);
1303 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001304 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001305 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001306
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001307 // Read and validate physical camera metadata
1308 size_t physResultCount = physicalCameraMetadatas.size();
1309 std::vector<const char*> physCamIds(physResultCount);
1310 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1311 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1312 physResultMetadata.resize(physResultCount);
1313 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1314 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1315 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1316 if (res != OK) {
1317 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1318 __FUNCTION__, result.frameNumber,
1319 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001320 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001321 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001322 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1323 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1324 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001325 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001326 r.num_physcam_metadata = physResultCount;
1327 r.physcam_ids = physCamIds.data();
1328 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001329
1330 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1331 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1332 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1333 auto& bDst = outputBuffers[i];
1334 const StreamBuffer &bSrc = result.outputBuffers[i];
1335
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001336 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1337 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001338 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1339 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001340 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001341 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001342 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001343
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001344 bool noBufferReturned = false;
1345 buffer_handle_t *buffer = nullptr;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001346 if (mUseHalBufManager) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001347 // This is suspicious most of the time but can be correct during flush where HAL
1348 // has to return capture result before a buffer is requested
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001349 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001350 if (bSrc.status == BufferStatus::OK) {
1351 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1352 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1353 // Still proceeds so other buffers can be returned
1354 }
1355 noBufferReturned = true;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001356 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001357 if (noBufferReturned) {
1358 res = OK;
1359 } else {
1360 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1361 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001362 } else {
1363 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1364 }
1365
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001366 if (res != OK) {
1367 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1368 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001369 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001370 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001371
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001372 bDst.buffer = buffer;
1373 bDst.status = mapHidlBufferStatus(bSrc.status);
1374 bDst.acquire_fence = -1;
1375 if (bSrc.releaseFence == nullptr) {
1376 bDst.release_fence = -1;
1377 } else if (bSrc.releaseFence->numFds == 1) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001378 if (noBufferReturned) {
1379 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
1380 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001381 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1382 } else {
1383 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1384 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001385 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001386 }
1387 }
1388 r.num_output_buffers = outputBuffers.size();
1389 r.output_buffers = outputBuffers.data();
1390
1391 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001392 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001393 r.input_buffer = nullptr;
1394 } else {
1395 if (mInputStream->getId() != result.inputBuffer.streamId) {
1396 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1397 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001398 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001399 }
1400 inputBuffer.stream = mInputStream->asHalStream();
1401 buffer_handle_t *buffer;
1402 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1403 &buffer);
1404 if (res != OK) {
1405 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1406 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001407 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001408 }
1409 inputBuffer.buffer = buffer;
1410 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1411 inputBuffer.acquire_fence = -1;
1412 if (result.inputBuffer.releaseFence == nullptr) {
1413 inputBuffer.release_fence = -1;
1414 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1415 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1416 } else {
1417 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1418 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001419 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001420 }
1421 r.input_buffer = &inputBuffer;
1422 }
1423
1424 r.partial_result = result.partialResult;
1425
1426 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001427}
1428
1429hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001430 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001431 // Ideally we should grab mLock, but that can lead to deadlock, and
1432 // it's not super important to get up to date value of mStatus for this
1433 // warning print, hence skipping the lock here
1434 if (mStatus == STATUS_ERROR) {
1435 // Per API contract, HAL should act as closed after device error
1436 // But mStatus can be set to error by framework as well, so just log
1437 // a warning here.
1438 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001439 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001440
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001441 for (const auto& msg : msgs) {
1442 notify(msg);
1443 }
1444 return hardware::Void();
1445}
1446
1447void Camera3Device::notify(
1448 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1449
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001450 camera3_notify_msg m;
1451 switch (msg.type) {
1452 case MsgType::ERROR:
1453 m.type = CAMERA3_MSG_ERROR;
1454 m.message.error.frame_number = msg.msg.error.frameNumber;
1455 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001456 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1457 if (stream == nullptr) {
1458 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1459 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001460 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001461 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001462 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001463 } else {
1464 m.message.error.error_stream = nullptr;
1465 }
1466 switch (msg.msg.error.errorCode) {
1467 case ErrorCode::ERROR_DEVICE:
1468 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1469 break;
1470 case ErrorCode::ERROR_REQUEST:
1471 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1472 break;
1473 case ErrorCode::ERROR_RESULT:
1474 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1475 break;
1476 case ErrorCode::ERROR_BUFFER:
1477 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1478 break;
1479 }
1480 break;
1481 case MsgType::SHUTTER:
1482 m.type = CAMERA3_MSG_SHUTTER;
1483 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1484 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1485 break;
1486 }
1487 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001488}
1489
Emilian Peevaebbe412018-01-15 13:53:24 +00001490status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001491 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001492 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001493 ATRACE_CALL();
1494
Emilian Peevaebbe412018-01-15 13:53:24 +00001495 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001496}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001497
Jianing Weicb0652e2014-03-12 18:29:36 -07001498status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1499 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001500 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001501
Emilian Peevaebbe412018-01-15 13:53:24 +00001502 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001503 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001504 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001505
Emilian Peevaebbe412018-01-15 13:53:24 +00001506 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001507 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001508}
1509
Emilian Peevaebbe412018-01-15 13:53:24 +00001510status_t Camera3Device::setStreamingRequestList(
1511 const List<const PhysicalCameraSettingsList> &requestsList,
1512 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001513 ATRACE_CALL();
1514
Emilian Peevaebbe412018-01-15 13:53:24 +00001515 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001516}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001517
1518sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001519 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001520 status_t res;
1521
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001522 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001523 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1524 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001525 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1526 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001527 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001529 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001531 } else if (mStatus == STATUS_UNCONFIGURED) {
1532 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001533 CLOGE("No streams configured");
1534 return NULL;
1535 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 }
1537
Shuzhen Wang0129d522016-10-30 22:43:41 -07001538 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001540}
1541
Jianing Weicb0652e2014-03-12 18:29:36 -07001542status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001543 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001544 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001546
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001547 switch (mStatus) {
1548 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001549 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 return INVALID_OPERATION;
1551 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001552 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001554 case STATUS_UNCONFIGURED:
1555 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 case STATUS_ACTIVE:
1557 // OK
1558 break;
1559 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001560 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001561 return INVALID_OPERATION;
1562 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001563 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001564
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001565 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001566}
1567
1568status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1569 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001570 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001571
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001572 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001573}
1574
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001575status_t Camera3Device::createInputStream(
1576 uint32_t width, uint32_t height, int format, int *id) {
1577 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001578 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001579 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001580 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001581 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1582 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001583
1584 status_t res;
1585 bool wasActive = false;
1586
1587 switch (mStatus) {
1588 case STATUS_ERROR:
1589 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1590 return INVALID_OPERATION;
1591 case STATUS_UNINITIALIZED:
1592 ALOGE("%s: Device not initialized", __FUNCTION__);
1593 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001594 case STATUS_UNCONFIGURED:
1595 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001596 // OK
1597 break;
1598 case STATUS_ACTIVE:
1599 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001600 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001601 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001602 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001603 return res;
1604 }
1605 wasActive = true;
1606 break;
1607 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001608 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001609 return INVALID_OPERATION;
1610 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001611 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001612
1613 if (mInputStream != 0) {
1614 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1615 return INVALID_OPERATION;
1616 }
1617
1618 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1619 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001620 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001621
1622 mInputStream = newStream;
1623
1624 *id = mNextStreamId++;
1625
1626 // Continue captures if active at start
1627 if (wasActive) {
1628 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001629 // Reuse current operating mode and session parameters for new stream config
1630 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001631 if (res != OK) {
1632 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1633 __FUNCTION__, mNextStreamId, strerror(-res), res);
1634 return res;
1635 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001636 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001637 }
1638
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001639 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001640 return OK;
1641}
1642
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001643status_t Camera3Device::StreamSet::add(
1644 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1645 if (stream == nullptr) {
1646 ALOGE("%s: cannot add null stream", __FUNCTION__);
1647 return BAD_VALUE;
1648 }
1649 std::lock_guard<std::mutex> lock(mLock);
1650 return mData.add(streamId, stream);
1651}
1652
1653ssize_t Camera3Device::StreamSet::remove(int streamId) {
1654 std::lock_guard<std::mutex> lock(mLock);
1655 return mData.removeItem(streamId);
1656}
1657
1658sp<camera3::Camera3OutputStreamInterface>
1659Camera3Device::StreamSet::get(int streamId) {
1660 std::lock_guard<std::mutex> lock(mLock);
1661 ssize_t idx = mData.indexOfKey(streamId);
1662 if (idx == NAME_NOT_FOUND) {
1663 return nullptr;
1664 }
1665 return mData.editValueAt(idx);
1666}
1667
1668sp<camera3::Camera3OutputStreamInterface>
1669Camera3Device::StreamSet::operator[] (size_t index) {
1670 std::lock_guard<std::mutex> lock(mLock);
1671 return mData.editValueAt(index);
1672}
1673
1674size_t Camera3Device::StreamSet::size() const {
1675 std::lock_guard<std::mutex> lock(mLock);
1676 return mData.size();
1677}
1678
1679void Camera3Device::StreamSet::clear() {
1680 std::lock_guard<std::mutex> lock(mLock);
1681 return mData.clear();
1682}
1683
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001684std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1685 std::lock_guard<std::mutex> lock(mLock);
1686 std::vector<int> streamIds(mData.size());
1687 for (size_t i = 0; i < mData.size(); i++) {
1688 streamIds[i] = mData.keyAt(i);
1689 }
1690 return streamIds;
1691}
1692
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001693status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001694 uint32_t width, uint32_t height, int format,
1695 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001696 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001697 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001698 ATRACE_CALL();
1699
1700 if (consumer == nullptr) {
1701 ALOGE("%s: consumer must not be null", __FUNCTION__);
1702 return BAD_VALUE;
1703 }
1704
1705 std::vector<sp<Surface>> consumers;
1706 consumers.push_back(consumer);
1707
1708 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001709 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1710 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001711}
1712
1713status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1714 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1715 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001716 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001717 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001718 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001719
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001720 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001721 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001722 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001723 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001724 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1725 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1726 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001727
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001728 status_t res;
1729 bool wasActive = false;
1730
1731 switch (mStatus) {
1732 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001733 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001734 return INVALID_OPERATION;
1735 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001736 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001737 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001738 case STATUS_UNCONFIGURED:
1739 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001740 // OK
1741 break;
1742 case STATUS_ACTIVE:
1743 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001744 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001745 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001746 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001747 return res;
1748 }
1749 wasActive = true;
1750 break;
1751 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001752 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001753 return INVALID_OPERATION;
1754 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001755 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001756
1757 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001758
Shuzhen Wang0129d522016-10-30 22:43:41 -07001759 if (consumers.size() == 0 && !hasDeferredConsumer) {
1760 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1761 return BAD_VALUE;
1762 }
Zhijun He5d677d12016-05-29 16:52:39 -07001763
Shuzhen Wang0129d522016-10-30 22:43:41 -07001764 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001765 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1766 return BAD_VALUE;
1767 }
1768
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001769 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001770 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001771 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001772 blobBufferSize = getPointCloudBufferSize();
1773 if (blobBufferSize <= 0) {
1774 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1775 return BAD_VALUE;
1776 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001777 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1778 blobBufferSize = width * height;
1779 } else {
1780 blobBufferSize = getJpegBufferSize(width, height);
1781 if (blobBufferSize <= 0) {
1782 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1783 return BAD_VALUE;
1784 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001785 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001786 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001787 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001788 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001789 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1790 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1791 if (rawOpaqueBufferSize <= 0) {
1792 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1793 return BAD_VALUE;
1794 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001795 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001796 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001797 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001798 } else if (isShared) {
1799 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1800 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001801 mTimestampOffset, physicalCameraId, streamSetId,
1802 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001803 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001804 newStream = new Camera3OutputStream(mNextStreamId,
1805 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001806 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001807 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001808 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001809 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001810 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001811 }
Emilian Peev40ead602017-09-26 15:46:36 +01001812
1813 size_t consumerCount = consumers.size();
1814 for (size_t i = 0; i < consumerCount; i++) {
1815 int id = newStream->getSurfaceId(consumers[i]);
1816 if (id < 0) {
1817 SET_ERR_L("Invalid surface id");
1818 return BAD_VALUE;
1819 }
1820 if (surfaceIds != nullptr) {
1821 surfaceIds->push_back(id);
1822 }
1823 }
1824
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001825 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001826
Emilian Peev08dd2452017-04-06 16:55:14 +01001827 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001828
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001829 res = mOutputStreams.add(mNextStreamId, newStream);
1830 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001831 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001832 return res;
1833 }
1834
1835 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001836 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001837
1838 // Continue captures if active at start
1839 if (wasActive) {
1840 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001841 // Reuse current operating mode and session parameters for new stream config
1842 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001843 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001844 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1845 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001846 return res;
1847 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001848 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001849 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001850 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001851 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001852}
1853
Emilian Peev710c1422017-08-30 11:19:38 +01001854status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001855 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001856 if (nullptr == streamInfo) {
1857 return BAD_VALUE;
1858 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001859 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001860 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001861
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001862 switch (mStatus) {
1863 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001864 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001865 return INVALID_OPERATION;
1866 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001867 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001868 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001869 case STATUS_UNCONFIGURED:
1870 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001871 case STATUS_ACTIVE:
1872 // OK
1873 break;
1874 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001875 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001876 return INVALID_OPERATION;
1877 }
1878
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001879 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1880 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001881 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001882 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001883 }
1884
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001885 streamInfo->width = stream->getWidth();
1886 streamInfo->height = stream->getHeight();
1887 streamInfo->format = stream->getFormat();
1888 streamInfo->dataSpace = stream->getDataSpace();
1889 streamInfo->formatOverridden = stream->isFormatOverridden();
1890 streamInfo->originalFormat = stream->getOriginalFormat();
1891 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1892 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001893 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001894}
1895
1896status_t Camera3Device::setStreamTransform(int id,
1897 int transform) {
1898 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001899 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001900 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001901
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001902 switch (mStatus) {
1903 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001904 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001905 return INVALID_OPERATION;
1906 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001907 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001908 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001909 case STATUS_UNCONFIGURED:
1910 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001911 case STATUS_ACTIVE:
1912 // OK
1913 break;
1914 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001915 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001916 return INVALID_OPERATION;
1917 }
1918
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001919 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1920 if (stream == nullptr) {
1921 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001922 return BAD_VALUE;
1923 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001924 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001925}
1926
1927status_t Camera3Device::deleteStream(int id) {
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);
1931 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001932
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001933 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001934
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001935 // CameraDevice semantics require device to already be idle before
1936 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001937 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001938 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001939 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001940 }
1941
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001942 if (mStatus == STATUS_ERROR) {
1943 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1944 __FUNCTION__, mId.string());
1945 return -EBUSY;
1946 }
1947
Igor Murashkin2fba5842013-04-22 14:03:54 -07001948 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001949 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001950 if (mInputStream != NULL && id == mInputStream->getId()) {
1951 deletedStream = mInputStream;
1952 mInputStream.clear();
1953 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001954 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001955 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001956 return BAD_VALUE;
1957 }
Zhijun He5f446352014-01-22 09:49:33 -08001958 }
1959
1960 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001961 if (stream != nullptr) {
1962 deletedStream = stream;
1963 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001964 }
1965
1966 // Free up the stream endpoint so that it can be used by some other stream
1967 res = deletedStream->disconnect();
1968 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001969 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001970 // fall through since we want to still list the stream as deleted.
1971 }
1972 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001973 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001974
1975 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001976}
1977
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001978status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001979 ATRACE_CALL();
1980 ALOGV("%s: E", __FUNCTION__);
1981
1982 Mutex::Autolock il(mInterfaceLock);
1983 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001984
Emilian Peev811d2952018-05-25 11:08:40 +01001985 // In case the client doesn't include any session parameter, try a
1986 // speculative configuration using the values from the last cached
1987 // default request.
1988 if (sessionParams.isEmpty() &&
1989 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1990 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1991 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1992 mLastTemplateId);
1993 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1994 operatingMode);
1995 }
1996
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001997 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1998}
1999
2000status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
2001 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002002 //Filter out any incoming session parameters
2003 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002004 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
2005 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002006 CameraMetadata filteredParams(availableSessionKeys.count);
2007 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2008 filteredParams.getAndLock());
2009 set_camera_metadata_vendor_id(meta, mVendorTagId);
2010 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002011 if (availableSessionKeys.count > 0) {
2012 for (size_t i = 0; i < availableSessionKeys.count; i++) {
2013 camera_metadata_ro_entry entry = params.find(
2014 availableSessionKeys.data.i32[i]);
2015 if (entry.count > 0) {
2016 filteredParams.update(entry);
2017 }
2018 }
2019 }
2020
2021 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07002022}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002023
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002024status_t Camera3Device::getInputBufferProducer(
2025 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002026 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002027 Mutex::Autolock il(mInterfaceLock);
2028 Mutex::Autolock l(mLock);
2029
2030 if (producer == NULL) {
2031 return BAD_VALUE;
2032 } else if (mInputStream == NULL) {
2033 return INVALID_OPERATION;
2034 }
2035
2036 return mInputStream->getInputBufferProducer(producer);
2037}
2038
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002039status_t Camera3Device::createDefaultRequest(int templateId,
2040 CameraMetadata *request) {
2041 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002042 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002043
2044 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2045 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002046 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002047 return BAD_VALUE;
2048 }
2049
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002050 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002051
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002052 {
2053 Mutex::Autolock l(mLock);
2054 switch (mStatus) {
2055 case STATUS_ERROR:
2056 CLOGE("Device has encountered a serious error");
2057 return INVALID_OPERATION;
2058 case STATUS_UNINITIALIZED:
2059 CLOGE("Device is not initialized!");
2060 return INVALID_OPERATION;
2061 case STATUS_UNCONFIGURED:
2062 case STATUS_CONFIGURED:
2063 case STATUS_ACTIVE:
2064 // OK
2065 break;
2066 default:
2067 SET_ERR_L("Unexpected status: %d", mStatus);
2068 return INVALID_OPERATION;
2069 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002070
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002071 if (!mRequestTemplateCache[templateId].isEmpty()) {
2072 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002073 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002074 return OK;
2075 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002076 }
2077
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002078 camera_metadata_t *rawRequest;
2079 status_t res = mInterface->constructDefaultRequestSettings(
2080 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002081
2082 {
2083 Mutex::Autolock l(mLock);
2084 if (res == BAD_VALUE) {
2085 ALOGI("%s: template %d is not supported on this camera device",
2086 __FUNCTION__, templateId);
2087 return res;
2088 } else if (res != OK) {
2089 CLOGE("Unable to construct request template %d: %s (%d)",
2090 templateId, strerror(-res), res);
2091 return res;
2092 }
2093
2094 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2095 mRequestTemplateCache[templateId].acquire(rawRequest);
2096
2097 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002098 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002099 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002100 return OK;
2101}
2102
2103status_t Camera3Device::waitUntilDrained() {
2104 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002105 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002106 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002107 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002108
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002109 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002110}
2111
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002112status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002113 switch (mStatus) {
2114 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002115 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002116 ALOGV("%s: Already idle", __FUNCTION__);
2117 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002118 case STATUS_CONFIGURED:
2119 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002120 case STATUS_ERROR:
2121 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002122 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002123 break;
2124 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002125 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002126 return INVALID_OPERATION;
2127 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002128 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2129 maxExpectedDuration);
2130 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002131 if (res != OK) {
2132 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2133 res);
2134 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002135 return res;
2136}
2137
Ruben Brunk183f0562015-08-12 12:55:02 -07002138
2139void Camera3Device::internalUpdateStatusLocked(Status status) {
2140 mStatus = status;
2141 mRecentStatusUpdates.add(mStatus);
2142 mStatusChanged.broadcast();
2143}
2144
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002145void Camera3Device::pauseStateNotify(bool enable) {
2146 Mutex::Autolock il(mInterfaceLock);
2147 Mutex::Autolock l(mLock);
2148
2149 mPauseStateNotify = enable;
2150}
2151
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002152// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002153status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08002154 if (mRequestThread.get() != nullptr) {
2155 mRequestThread->setPaused(true);
2156 } else {
2157 return NO_INIT;
2158 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002159
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002160 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2161 maxExpectedDuration);
2162 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002163 if (res != OK) {
2164 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002165 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002166 }
2167
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002168 return res;
2169}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002170
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002171// Resume after internalPauseAndWaitLocked
2172status_t Camera3Device::internalResumeLocked() {
2173 status_t res;
2174
2175 mRequestThread->setPaused(false);
2176
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002177 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2178 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002179 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2180 if (res != OK) {
2181 SET_ERR_L("Can't transition to active in %f seconds!",
2182 kActiveTimeout/1e9);
2183 }
2184 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002185 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002186}
2187
Ruben Brunk183f0562015-08-12 12:55:02 -07002188status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002189 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002190
2191 size_t startIndex = 0;
2192 if (mStatusWaiters == 0) {
2193 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2194 // this status list
2195 mRecentStatusUpdates.clear();
2196 } else {
2197 // If other threads are waiting on updates to this status list, set the position of the
2198 // first element that this list will check rather than clearing the list.
2199 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002200 }
2201
Ruben Brunk183f0562015-08-12 12:55:02 -07002202 mStatusWaiters++;
2203
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002204 if (!active && mUseHalBufManager) {
2205 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08002206 if (mStatus == STATUS_ACTIVE) {
2207 mRequestThread->signalPipelineDrain(streamIds);
2208 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002209 mRequestBufferSM.onWaitUntilIdle();
2210 }
2211
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002212 bool stateSeen = false;
2213 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002214 if (active == (mStatus == STATUS_ACTIVE)) {
2215 // Desired state is current
2216 break;
2217 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002218
2219 res = mStatusChanged.waitRelative(mLock, timeout);
2220 if (res != OK) break;
2221
Ruben Brunk183f0562015-08-12 12:55:02 -07002222 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2223 // transitions.
2224 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2225 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2226 __FUNCTION__);
2227
2228 // Encountered desired state since we began waiting
2229 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002230 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2231 stateSeen = true;
2232 break;
2233 }
2234 }
2235 } while (!stateSeen);
2236
Ruben Brunk183f0562015-08-12 12:55:02 -07002237 mStatusWaiters--;
2238
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002239 return res;
2240}
2241
2242
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002243status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002244 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002245 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002246
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002247 if (listener != NULL && mListener != NULL) {
2248 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2249 }
2250 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002251 mRequestThread->setNotificationListener(listener);
2252 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002253
2254 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002255}
2256
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002257bool Camera3Device::willNotify3A() {
2258 return false;
2259}
2260
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002261status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002262 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002263 status_t res;
2264 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002265
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002266 while (mResultQueue.empty()) {
2267 res = mResultSignal.waitRelative(mOutputLock, timeout);
2268 if (res == TIMED_OUT) {
2269 return res;
2270 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002271 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2272 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002273 return res;
2274 }
2275 }
2276 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002277}
2278
Jianing Weicb0652e2014-03-12 18:29:36 -07002279status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002280 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002281 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002282
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002283 if (mResultQueue.empty()) {
2284 return NOT_ENOUGH_DATA;
2285 }
2286
Jianing Weicb0652e2014-03-12 18:29:36 -07002287 if (frame == NULL) {
2288 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2289 return BAD_VALUE;
2290 }
2291
2292 CaptureResult &result = *(mResultQueue.begin());
2293 frame->mResultExtras = result.mResultExtras;
2294 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002295 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002296 mResultQueue.erase(mResultQueue.begin());
2297
2298 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002299}
2300
2301status_t Camera3Device::triggerAutofocus(uint32_t id) {
2302 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002303 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002304
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002305 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2306 // Mix-in this trigger into the next request and only the next request.
2307 RequestTrigger trigger[] = {
2308 {
2309 ANDROID_CONTROL_AF_TRIGGER,
2310 ANDROID_CONTROL_AF_TRIGGER_START
2311 },
2312 {
2313 ANDROID_CONTROL_AF_TRIGGER_ID,
2314 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002315 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002316 };
2317
2318 return mRequestThread->queueTrigger(trigger,
2319 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002320}
2321
2322status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2323 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002324 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002325
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002326 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2327 // Mix-in this trigger into the next request and only the next request.
2328 RequestTrigger trigger[] = {
2329 {
2330 ANDROID_CONTROL_AF_TRIGGER,
2331 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2332 },
2333 {
2334 ANDROID_CONTROL_AF_TRIGGER_ID,
2335 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002336 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002337 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002338
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002339 return mRequestThread->queueTrigger(trigger,
2340 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002341}
2342
2343status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2344 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002345 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002346
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002347 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2348 // Mix-in this trigger into the next request and only the next request.
2349 RequestTrigger trigger[] = {
2350 {
2351 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2352 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2353 },
2354 {
2355 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2356 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002357 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002358 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002359
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002360 return mRequestThread->queueTrigger(trigger,
2361 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002362}
2363
Jianing Weicb0652e2014-03-12 18:29:36 -07002364status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002365 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002366 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002367 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002368
Zhijun He7ef20392014-04-21 16:04:17 -07002369 {
2370 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002371
2372 // b/116514106 "disconnect()" can get called twice for the same device. The
2373 // camera device will not be initialized during the second run.
2374 if (mStatus == STATUS_UNINITIALIZED) {
2375 return OK;
2376 }
2377
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002378 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002379 }
2380
Emilian Peev08dd2452017-04-06 16:55:14 +01002381 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002382}
2383
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002384status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002385 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2386}
2387
2388status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002389 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002390 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002391 Mutex::Autolock il(mInterfaceLock);
2392 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002393
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002394 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2395 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002396 CLOGE("Stream %d does not exist", streamId);
2397 return BAD_VALUE;
2398 }
2399
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002400 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002401 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002402 return BAD_VALUE;
2403 }
2404
2405 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002406 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002407 return BAD_VALUE;
2408 }
2409
Ruben Brunkc78ac262015-08-13 17:58:46 -07002410 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002411}
2412
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002413status_t Camera3Device::tearDown(int streamId) {
2414 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002415 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002416 Mutex::Autolock il(mInterfaceLock);
2417 Mutex::Autolock l(mLock);
2418
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002419 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2420 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002421 CLOGE("Stream %d does not exist", streamId);
2422 return BAD_VALUE;
2423 }
2424
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002425 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2426 CLOGE("Stream %d is a target of a in-progress request", streamId);
2427 return BAD_VALUE;
2428 }
2429
2430 return stream->tearDown();
2431}
2432
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002433status_t Camera3Device::addBufferListenerForStream(int streamId,
2434 wp<Camera3StreamBufferListener> listener) {
2435 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002436 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002437 Mutex::Autolock il(mInterfaceLock);
2438 Mutex::Autolock l(mLock);
2439
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002440 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2441 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002442 CLOGE("Stream %d does not exist", streamId);
2443 return BAD_VALUE;
2444 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002445 stream->addBufferListener(listener);
2446
2447 return OK;
2448}
2449
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002450/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002451 * Methods called by subclasses
2452 */
2453
2454void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002455 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002456 {
2457 // Need mLock to safely update state and synchronize to current
2458 // state of methods in flight.
2459 Mutex::Autolock l(mLock);
2460 // We can get various system-idle notices from the status tracker
2461 // while starting up. Only care about them if we've actually sent
2462 // in some requests recently.
2463 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2464 return;
2465 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002466 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2467 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002468 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002469
2470 // Skip notifying listener if we're doing some user-transparent
2471 // state changes
2472 if (mPauseStateNotify) return;
2473 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002474
2475 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002476 {
2477 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002478 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002479 }
2480 if (idle && listener != NULL) {
2481 listener->notifyIdle();
2482 }
2483}
2484
Shuzhen Wang758c2152017-01-10 18:26:18 -08002485status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002486 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002487 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002488 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2489 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002490
2491 if (surfaceIds == nullptr) {
2492 return BAD_VALUE;
2493 }
2494
Zhijun He5d677d12016-05-29 16:52:39 -07002495 Mutex::Autolock il(mInterfaceLock);
2496 Mutex::Autolock l(mLock);
2497
Shuzhen Wang758c2152017-01-10 18:26:18 -08002498 if (consumers.size() == 0) {
2499 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002500 return BAD_VALUE;
2501 }
2502
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002503 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2504 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002505 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002506 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002507 }
Shuzhen Wang758c2152017-01-10 18:26:18 -08002508 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002509 if (res != OK) {
2510 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2511 return res;
2512 }
2513
Emilian Peev40ead602017-09-26 15:46:36 +01002514 for (auto &consumer : consumers) {
2515 int id = stream->getSurfaceId(consumer);
2516 if (id < 0) {
2517 CLOGE("Invalid surface id!");
2518 return BAD_VALUE;
2519 }
2520 surfaceIds->push_back(id);
2521 }
2522
Shuzhen Wang0129d522016-10-30 22:43:41 -07002523 if (stream->isConsumerConfigurationDeferred()) {
2524 if (!stream->isConfiguring()) {
2525 CLOGE("Stream %d was already fully configured.", streamId);
2526 return INVALID_OPERATION;
2527 }
Zhijun He5d677d12016-05-29 16:52:39 -07002528
Shuzhen Wang0129d522016-10-30 22:43:41 -07002529 res = stream->finishConfiguration();
2530 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002531 // If finishConfiguration fails due to abandoned surface, do not set
2532 // device to error state.
2533 bool isSurfaceAbandoned =
2534 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2535 if (!isSurfaceAbandoned) {
2536 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2537 stream->getId(), strerror(-res), res);
2538 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002539 return res;
2540 }
Zhijun He5d677d12016-05-29 16:52:39 -07002541 }
2542
2543 return OK;
2544}
2545
Emilian Peev40ead602017-09-26 15:46:36 +01002546status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2547 const std::vector<OutputStreamInfo> &outputInfo,
2548 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2549 Mutex::Autolock il(mInterfaceLock);
2550 Mutex::Autolock l(mLock);
2551
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002552 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2553 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002554 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002555 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002556 }
2557
2558 for (const auto &it : removedSurfaceIds) {
2559 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2560 CLOGE("Shared surface still part of a pending request!");
2561 return -EBUSY;
2562 }
2563 }
2564
Emilian Peev40ead602017-09-26 15:46:36 +01002565 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2566 if (res != OK) {
2567 CLOGE("Stream %d failed to update stream (error %d %s) ",
2568 streamId, res, strerror(-res));
2569 if (res == UNKNOWN_ERROR) {
2570 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2571 __FUNCTION__);
2572 }
2573 return res;
2574 }
2575
2576 return res;
2577}
2578
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002579status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2580 Mutex::Autolock il(mInterfaceLock);
2581 Mutex::Autolock l(mLock);
2582
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002583 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2584 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002585 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2586 return BAD_VALUE;
2587 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002588 return stream->dropBuffers(dropping);
2589}
2590
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002591/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002592 * Camera3Device private methods
2593 */
2594
2595sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002596 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002597 ATRACE_CALL();
2598 status_t res;
2599
2600 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002601 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002602
2603 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002604 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002605 if (inputStreams.count > 0) {
2606 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002607 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002608 CLOGE("Request references unknown input stream %d",
2609 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002610 return NULL;
2611 }
2612 // Lazy completion of stream configuration (allocation/registration)
2613 // on first use
2614 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002615 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002616 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002617 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002618 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002619 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002620 return NULL;
2621 }
2622 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002623 // Check if stream prepare is blocking requests.
2624 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002625 CLOGE("Request references an input stream that's being prepared!");
2626 return NULL;
2627 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002628
2629 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002630 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002631 }
2632
2633 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002634 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002635 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002636 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002637 return NULL;
2638 }
2639
2640 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002641 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2642 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002643 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002644 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002645 return NULL;
2646 }
Zhijun He5d677d12016-05-29 16:52:39 -07002647 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002648 auto iter = surfaceMap.find(streams.data.i32[i]);
2649 if (iter != surfaceMap.end()) {
2650 const std::vector<size_t>& surfaces = iter->second;
2651 for (const auto& surface : surfaces) {
2652 if (stream->isConsumerConfigurationDeferred(surface)) {
2653 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2654 "due to deferred consumer", stream->getId(), surface);
2655 return NULL;
2656 }
2657 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002658 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002659 }
2660
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002661 // Lazy completion of stream configuration (allocation/registration)
2662 // on first use
2663 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002664 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002665 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002666 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2667 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002668 return NULL;
2669 }
2670 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002671 // Check if stream prepare is blocking requests.
2672 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002673 CLOGE("Request references an output stream that's being prepared!");
2674 return NULL;
2675 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002676
2677 newRequest->mOutputStreams.push(stream);
2678 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002679 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002680 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002681
2682 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002683}
2684
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002685bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2686 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2687 Size size = mSupportedOpaqueInputSizes[i];
2688 if (size.width == width && size.height == height) {
2689 return true;
2690 }
2691 }
2692
2693 return false;
2694}
2695
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002696void Camera3Device::cancelStreamsConfigurationLocked() {
2697 int res = OK;
2698 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2699 res = mInputStream->cancelConfiguration();
2700 if (res != OK) {
2701 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2702 mInputStream->getId(), strerror(-res), res);
2703 }
2704 }
2705
2706 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002707 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002708 if (outputStream->isConfiguring()) {
2709 res = outputStream->cancelConfiguration();
2710 if (res != OK) {
2711 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2712 outputStream->getId(), strerror(-res), res);
2713 }
2714 }
2715 }
2716
2717 // Return state to that at start of call, so that future configures
2718 // properly clean things up
2719 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2720 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002721
2722 res = mPreparerThread->resume();
2723 if (res != OK) {
2724 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2725 }
2726}
2727
2728bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2729 ATRACE_CALL();
2730 bool ret = false;
2731
2732 Mutex::Autolock il(mInterfaceLock);
2733 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2734
2735 Mutex::Autolock l(mLock);
2736 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2737 if (rc == NO_ERROR) {
2738 mNeedConfig = true;
2739 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2740 if (rc == NO_ERROR) {
2741 ret = true;
2742 mPauseStateNotify = false;
2743 //Moving to active state while holding 'mLock' is important.
2744 //There could be pending calls to 'create-/deleteStream' which
2745 //will trigger another stream configuration while the already
2746 //present streams end up with outstanding buffers that will
2747 //not get drained.
2748 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002749 } else if (rc == DEAD_OBJECT) {
2750 // DEAD_OBJECT can be returned if either the consumer surface is
2751 // abandoned, or the HAL has died.
2752 // - If the HAL has died, configureStreamsLocked call will set
2753 // device to error state,
2754 // - If surface is abandoned, we should not set device to error
2755 // state.
2756 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002757 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002758 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002759 }
2760 } else {
2761 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2762 }
2763
2764 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002765}
2766
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002767status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002768 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002769 ATRACE_CALL();
2770 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002771
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002772 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002773 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002774 return INVALID_OPERATION;
2775 }
2776
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002777 if (operatingMode < 0) {
2778 CLOGE("Invalid operating mode: %d", operatingMode);
2779 return BAD_VALUE;
2780 }
2781
2782 bool isConstrainedHighSpeed =
2783 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2784 operatingMode;
2785
2786 if (mOperatingMode != operatingMode) {
2787 mNeedConfig = true;
2788 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2789 mOperatingMode = operatingMode;
2790 }
2791
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002792 if (!mNeedConfig) {
2793 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2794 return OK;
2795 }
2796
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002797 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2798 // adding a dummy stream instead.
2799 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2800 if (mOutputStreams.size() == 0) {
2801 addDummyStreamLocked();
2802 } else {
2803 tryRemoveDummyStreamLocked();
2804 }
2805
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002806 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002807 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002808
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002809 mPreparerThread->pause();
2810
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002811 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002812 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002813 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2814
2815 Vector<camera3_stream_t*> streams;
2816 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002817 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002818
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002819
2820 if (mInputStream != NULL) {
2821 camera3_stream_t *inputStream;
2822 inputStream = mInputStream->startConfiguration();
2823 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002824 CLOGE("Can't start input stream configuration");
2825 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002826 return INVALID_OPERATION;
2827 }
2828 streams.add(inputStream);
2829 }
2830
2831 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002832
2833 // Don't configure bidi streams twice, nor add them twice to the list
2834 if (mOutputStreams[i].get() ==
2835 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2836
2837 config.num_streams--;
2838 continue;
2839 }
2840
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002841 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002842 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002843 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002844 CLOGE("Can't start output stream configuration");
2845 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002846 return INVALID_OPERATION;
2847 }
2848 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002849
2850 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2851 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002852 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2853 // always occupy the initial entry.
2854 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002855 getJpegBufferSize(outputStream->width, outputStream->height));
2856 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002857 }
2858
2859 config.streams = streams.editArray();
2860
2861 // Do the HAL configuration; will potentially touch stream
2862 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002863
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002864 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002865 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002866 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002867
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002868 if (res == BAD_VALUE) {
2869 // HAL rejected this set of streams as unsupported, clean up config
2870 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002871 CLOGE("Set of requested inputs/outputs not supported by HAL");
2872 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002873 return BAD_VALUE;
2874 } else if (res != OK) {
2875 // Some other kind of error from configure_streams - this is not
2876 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002877 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2878 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002879 return res;
2880 }
2881
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002882 // Finish all stream configuration immediately.
2883 // TODO: Try to relax this later back to lazy completion, which should be
2884 // faster
2885
Igor Murashkin073f8572013-05-02 14:59:28 -07002886 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002887 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002888 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002889 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002890 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002891 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002892 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2893 return DEAD_OBJECT;
2894 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002895 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002896 }
2897 }
2898
2899 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002900 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002901 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002902 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002903 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002904 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002905 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002906 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002907 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2908 return DEAD_OBJECT;
2909 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002910 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002911 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002912 }
2913 }
2914
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002915 // Request thread needs to know to avoid using repeat-last-settings protocol
2916 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002917 if (notifyRequestThread) {
2918 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2919 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002920
Zhijun He90f7c372016-08-16 16:19:43 -07002921 char value[PROPERTY_VALUE_MAX];
2922 property_get("camera.fifo.disable", value, "0");
2923 int32_t disableFifo = atoi(value);
2924 if (disableFifo != 1) {
2925 // Boost priority of request thread to SCHED_FIFO.
2926 pid_t requestThreadTid = mRequestThread->getTid();
2927 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002928 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002929 if (res != OK) {
2930 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2931 strerror(-res), res);
2932 } else {
2933 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2934 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002935 }
2936
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002937 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002938 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2939 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2940 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2941 sessionParams.unlock(newSessionParams);
2942 mSessionParams.unlock(currentSessionParams);
2943 if (updateSessionParams) {
2944 mSessionParams = sessionParams;
2945 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002946
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002947 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002948
Ruben Brunk183f0562015-08-12 12:55:02 -07002949 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2950 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002951
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002952 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002953
Zhijun He0a210512014-07-24 13:45:15 -07002954 // tear down the deleted streams after configure streams.
2955 mDeletedStreams.clear();
2956
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002957 auto rc = mPreparerThread->resume();
2958 if (rc != OK) {
2959 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2960 return rc;
2961 }
2962
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002963 if (mDummyStreamId == NO_STREAM) {
2964 mRequestBufferSM.onStreamsConfigured();
2965 }
2966
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002967 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002968}
2969
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002970status_t Camera3Device::addDummyStreamLocked() {
2971 ATRACE_CALL();
2972 status_t res;
2973
2974 if (mDummyStreamId != NO_STREAM) {
2975 // Should never be adding a second dummy stream when one is already
2976 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002977 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2978 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002979 return INVALID_OPERATION;
2980 }
2981
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002982 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002983
2984 sp<Camera3OutputStreamInterface> dummyStream =
2985 new Camera3DummyStream(mNextStreamId);
2986
2987 res = mOutputStreams.add(mNextStreamId, dummyStream);
2988 if (res < 0) {
2989 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2990 return res;
2991 }
2992
2993 mDummyStreamId = mNextStreamId;
2994 mNextStreamId++;
2995
2996 return OK;
2997}
2998
2999status_t Camera3Device::tryRemoveDummyStreamLocked() {
3000 ATRACE_CALL();
3001 status_t res;
3002
3003 if (mDummyStreamId == NO_STREAM) return OK;
3004 if (mOutputStreams.size() == 1) return OK;
3005
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003006 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003007
3008 // Ok, have a dummy stream and there's at least one other output stream,
3009 // so remove the dummy
3010
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003011 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
3012 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003013 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3014 return INVALID_OPERATION;
3015 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003016 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003017
3018 // Free up the stream endpoint so that it can be used by some other stream
3019 res = deletedStream->disconnect();
3020 if (res != OK) {
3021 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3022 // fall through since we want to still list the stream as deleted.
3023 }
3024 mDeletedStreams.add(deletedStream);
3025 mDummyStreamId = NO_STREAM;
3026
3027 return res;
3028}
3029
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003030void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003031 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003032 Mutex::Autolock l(mLock);
3033 va_list args;
3034 va_start(args, fmt);
3035
3036 setErrorStateLockedV(fmt, args);
3037
3038 va_end(args);
3039}
3040
3041void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003042 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003043 Mutex::Autolock l(mLock);
3044 setErrorStateLockedV(fmt, args);
3045}
3046
3047void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3048 va_list args;
3049 va_start(args, fmt);
3050
3051 setErrorStateLockedV(fmt, args);
3052
3053 va_end(args);
3054}
3055
3056void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003057 // Print out all error messages to log
3058 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003059 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003060
3061 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003062 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003063
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003064 mErrorCause = errorCause;
3065
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003066 if (mRequestThread != nullptr) {
3067 mRequestThread->setPaused(true);
3068 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003069 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003070
3071 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003072 sp<NotificationListener> listener = mListener.promote();
3073 if (listener != NULL) {
3074 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003075 CaptureResultExtras());
3076 }
3077
3078 // Save stack trace. View by dumping it later.
3079 CameraTraces::saveTrace();
3080 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003081}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003082
3083/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003084 * In-flight request management
3085 */
3086
Jianing Weicb0652e2014-03-12 18:29:36 -07003087status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003088 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003089 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003090 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003091 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003092 ATRACE_CALL();
3093 Mutex::Autolock l(mInFlightLock);
3094
3095 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003096 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003097 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3098 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003099 if (res < 0) return res;
3100
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003101 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003102 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3103 // avoid a deadlock during reprocess requests.
3104 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003105 if (mStatusTracker != nullptr) {
3106 mStatusTracker->markComponentActive(mInFlightStatusId);
3107 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003108 }
3109
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003110 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003111 return OK;
3112}
3113
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003114void Camera3Device::returnOutputBuffers(
3115 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003116 nsecs_t timestamp, bool timestampIncreasing,
3117 const SurfaceMap& outputSurfaces,
3118 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003119
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003120 for (size_t i = 0; i < numBuffers; i++)
3121 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003122 if (outputBuffers[i].buffer == nullptr) {
3123 if (!mUseHalBufManager) {
3124 // With HAL buffer management API, HAL sometimes will have to return buffers that
3125 // has not got a output buffer handle filled yet. This is though illegal if HAL
3126 // buffer management API is not being used.
3127 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3128 }
3129 continue;
3130 }
3131
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003132 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3133 int streamId = stream->getId();
3134 const auto& it = outputSurfaces.find(streamId);
3135 status_t res = OK;
3136 if (it != outputSurfaces.end()) {
3137 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003138 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3139 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003140 } else {
3141 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003142 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3143 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003144 }
3145
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003146 // Note: stream may be deallocated at this point, if this buffer was
3147 // the last reference to it.
3148 if (res != OK) {
3149 ALOGE("Can't return buffer to its stream: %s (%d)",
3150 strerror(-res), res);
3151 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003152
3153 // Long processing consumers can cause returnBuffer timeout for shared stream
3154 // If that happens, cancel the buffer and send a buffer error to client
3155 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3156 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3157 // cancel the buffer
3158 camera3_stream_buffer_t sb = outputBuffers[i];
3159 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003160 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3161 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003162
3163 // notify client buffer error
3164 sp<NotificationListener> listener;
3165 {
3166 Mutex::Autolock l(mOutputLock);
3167 listener = mListener.promote();
3168 }
3169
3170 if (listener != nullptr) {
3171 CaptureResultExtras extras = inResultExtras;
3172 extras.errorStreamId = streamId;
3173 listener->notifyError(
3174 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3175 extras);
3176 }
3177 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003178 }
3179}
3180
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003181void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003182 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003183 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003184 mInFlightMap.removeItemsAt(idx, 1);
3185
3186 // Indicate idle inFlightMap to the status tracker
3187 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003188 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003189 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3190 // avoid a deadlock during reprocess requests.
3191 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003192 if (mStatusTracker != nullptr) {
3193 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3194 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003195 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003196 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003197}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003198
3199void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3200
3201 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3202 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3203
3204 nsecs_t sensorTimestamp = request.sensorTimestamp;
3205 nsecs_t shutterTimestamp = request.shutterTimestamp;
3206
3207 // Check if it's okay to remove the request from InFlightMap:
3208 // In the case of a successful request:
3209 // all input and output buffers, all result metadata, shutter callback
3210 // arrived.
3211 // In the case of a unsuccessful request:
3212 // all input and output buffers arrived.
3213 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003214 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003215 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003216 if (request.stillCapture) {
3217 ATRACE_ASYNC_END("still capture", frameNumber);
3218 }
3219
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003220 ATRACE_ASYNC_END("frame capture", frameNumber);
3221
Shuzhen Wang403044a2017-02-26 23:29:04 -08003222 // Sanity check - if sensor timestamp matches shutter timestamp in the
3223 // case of request having callback.
3224 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003225 sensorTimestamp != shutterTimestamp) {
3226 SET_ERR("sensor timestamp (%" PRId64
3227 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3228 sensorTimestamp, frameNumber, shutterTimestamp);
3229 }
3230
3231 // for an unsuccessful request, it may have pending output buffers to
3232 // return.
3233 assert(request.requestStatus != OK ||
3234 request.pendingOutputBuffers.size() == 0);
3235 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003236 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3237 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003238
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003239 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003240 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3241 }
3242
3243 // Sanity check - if we have too many in-flight frames, something has
3244 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003245 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003246 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003247 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3248 kInFlightWarnLimitHighSpeed) {
3249 CLOGE("In-flight list too large for high speed configuration: %zu",
3250 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003251 }
3252}
3253
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003254void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003255 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003256 { // First return buffers cached in mInFlightMap
3257 Mutex::Autolock l(mInFlightLock);
3258 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3259 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3260 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003261 request.pendingOutputBuffers.size(), 0,
3262 /*timestampIncreasing*/true, request.outputSurfaces,
3263 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003264 }
3265 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003266 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003267 }
3268
3269 // Then return all inflight buffers not returned by HAL
3270 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3271 mInterface->getInflightBufferKeys(&inflightKeys);
3272
3273 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3274 for (auto& pair : inflightKeys) {
3275 int32_t frameNumber = pair.first;
3276 int32_t streamId = pair.second;
3277 buffer_handle_t* buffer;
3278 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3279 if (res != OK) {
3280 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3281 __FUNCTION__, frameNumber, streamId);
3282 continue;
3283 }
3284
3285 camera3_stream_buffer_t streamBuffer;
3286 streamBuffer.buffer = buffer;
3287 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3288 streamBuffer.acquire_fence = -1;
3289 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003290
3291 // First check if the buffer belongs to deleted stream
3292 bool streamDeleted = false;
3293 for (auto& stream : mDeletedStreams) {
3294 if (streamId == stream->getId()) {
3295 streamDeleted = true;
3296 // Return buffer to deleted stream
3297 camera3_stream* halStream = stream->asHalStream();
3298 streamBuffer.stream = halStream;
3299 switch (halStream->stream_type) {
3300 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003301 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3302 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003303 if (res != OK) {
3304 ALOGE("%s: Can't return output buffer for frame %d to"
3305 " stream %d: %s (%d)", __FUNCTION__,
3306 frameNumber, streamId, strerror(-res), res);
3307 }
3308 break;
3309 case CAMERA3_STREAM_INPUT:
3310 res = stream->returnInputBuffer(streamBuffer);
3311 if (res != OK) {
3312 ALOGE("%s: Can't return input buffer for frame %d to"
3313 " stream %d: %s (%d)", __FUNCTION__,
3314 frameNumber, streamId, strerror(-res), res);
3315 }
3316 break;
3317 default: // Bi-direcitonal stream is deprecated
3318 ALOGE("%s: stream %d has unknown stream type %d",
3319 __FUNCTION__, streamId, halStream->stream_type);
3320 break;
3321 }
3322 break;
3323 }
3324 }
3325 if (streamDeleted) {
3326 continue;
3327 }
3328
3329 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003330 if (streamId == inputStreamId) {
3331 streamBuffer.stream = mInputStream->asHalStream();
3332 res = mInputStream->returnInputBuffer(streamBuffer);
3333 if (res != OK) {
3334 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003335 " stream %d: %s (%d)", __FUNCTION__,
3336 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003337 }
3338 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003339 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3340 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003341 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3342 continue;
3343 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003344 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003345 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3346 }
3347 }
3348}
3349
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003350void Camera3Device::insertResultLocked(CaptureResult *result,
3351 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003352 if (result == nullptr) return;
3353
Emilian Peev71c73a22017-03-21 16:35:51 +00003354 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3355 result->mMetadata.getAndLock());
3356 set_camera_metadata_vendor_id(meta, mVendorTagId);
3357 result->mMetadata.unlock(meta);
3358
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003359 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3360 (int32_t*)&frameNumber, 1) != OK) {
3361 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3362 return;
3363 }
3364
3365 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3366 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3367 return;
3368 }
3369
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003370 // Valid result, insert into queue
3371 List<CaptureResult>::iterator queuedResult =
3372 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3373 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3374 ", burstId = %" PRId32, __FUNCTION__,
3375 queuedResult->mResultExtras.requestId,
3376 queuedResult->mResultExtras.frameNumber,
3377 queuedResult->mResultExtras.burstId);
3378
3379 mResultSignal.signal();
3380}
3381
3382
3383void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003384 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003385 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003386 Mutex::Autolock l(mOutputLock);
3387
3388 CaptureResult captureResult;
3389 captureResult.mResultExtras = resultExtras;
3390 captureResult.mMetadata = partialResult;
3391
Shuzhen Wang268a1362018-10-16 16:32:59 -07003392 // Fix up result metadata for monochrome camera.
3393 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3394 if (res != OK) {
3395 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3396 return;
3397 }
3398
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003399 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003400}
3401
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003402
3403void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3404 CaptureResultExtras &resultExtras,
3405 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003406 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003407 bool reprocess,
3408 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003409 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003410 if (pendingMetadata.isEmpty())
3411 return;
3412
3413 Mutex::Autolock l(mOutputLock);
3414
3415 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003416 if (reprocess) {
3417 if (frameNumber < mNextReprocessResultFrameNumber) {
3418 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003419 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003420 frameNumber, mNextReprocessResultFrameNumber);
3421 return;
3422 }
3423 mNextReprocessResultFrameNumber = frameNumber + 1;
3424 } else {
3425 if (frameNumber < mNextResultFrameNumber) {
3426 SET_ERR("Out-of-order capture result metadata submitted! "
3427 "(got frame number %d, expecting %d)",
3428 frameNumber, mNextResultFrameNumber);
3429 return;
3430 }
3431 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003432 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003433
3434 CaptureResult captureResult;
3435 captureResult.mResultExtras = resultExtras;
3436 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003437 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003438
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003439 // Append any previous partials to form a complete result
3440 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3441 captureResult.mMetadata.append(collectedPartialResult);
3442 }
3443
3444 captureResult.mMetadata.sort();
3445
3446 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003447 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3448 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003449 SET_ERR("No timestamp provided by HAL for frame %d!",
3450 frameNumber);
3451 return;
3452 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003453 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3454 camera_metadata_entry timestamp =
3455 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3456 if (timestamp.count == 0) {
3457 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3458 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3459 return;
3460 }
3461 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003462
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003463 // Fix up some result metadata to account for HAL-level distortion correction
3464 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3465 if (res != OK) {
3466 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3467 frameNumber, strerror(res), res);
3468 return;
3469 }
Shuzhen Wang268a1362018-10-16 16:32:59 -07003470 // Fix up result metadata for monochrome camera.
3471 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3472 if (res != OK) {
3473 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3474 return;
3475 }
3476 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3477 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3478 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3479 physicalMetadata.mPhysicalCameraMetadata);
3480 if (res != OK) {
3481 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3482 return;
3483 }
3484 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003485
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003486 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3487 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3488
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003489 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003490}
3491
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003492/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003493 * Camera HAL device callback methods
3494 */
3495
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003496void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003497 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003498
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003499 status_t res;
3500
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003501 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003502 if (result->result == NULL && result->num_output_buffers == 0 &&
3503 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003504 SET_ERR("No result data provided by HAL for frame %d",
3505 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003506 return;
3507 }
Zhijun He204e3292014-07-14 17:09:23 -07003508
Zhijun He204e3292014-07-14 17:09:23 -07003509 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003510 result->result != NULL &&
3511 result->partial_result != 1) {
3512 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3513 " if partial result is not supported",
3514 frameNumber, result->partial_result);
3515 return;
3516 }
3517
3518 bool isPartialResult = false;
3519 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003520 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003521
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003522 // Get shutter timestamp and resultExtras from list of in-flight requests,
3523 // where it was added by the shutter notification for this frame. If the
3524 // shutter timestamp isn't received yet, append the output buffers to the
3525 // in-flight request and they will be returned when the shutter timestamp
3526 // arrives. Update the in-flight status and remove the in-flight entry if
3527 // all result data and shutter timestamp have been received.
3528 nsecs_t shutterTimestamp = 0;
3529
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003530 {
3531 Mutex::Autolock l(mInFlightLock);
3532 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3533 if (idx == NAME_NOT_FOUND) {
3534 SET_ERR("Unknown frame number for capture result: %d",
3535 frameNumber);
3536 return;
3537 }
3538 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003539 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3540 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003541 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003542 __FUNCTION__, request.resultExtras.requestId,
3543 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003544 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003545 // Always update the partial count to the latest one if it's not 0
3546 // (buffers only). When framework aggregates adjacent partial results
3547 // into one, the latest partial count will be used.
3548 if (result->partial_result != 0)
3549 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003550
3551 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003552 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003553 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3554 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3555 " the range of [1, %d] when metadata is included in the result",
3556 frameNumber, result->partial_result, mNumPartialResults);
3557 return;
3558 }
3559 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003560 if (isPartialResult && result->num_physcam_metadata) {
3561 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3562 " physical camera result", frameNumber);
3563 return;
3564 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003565 if (isPartialResult) {
3566 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003567 }
3568
Shuzhen Wang4a472662017-02-26 23:29:04 -08003569 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003570 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003571 sendPartialCaptureResult(result->result, request.resultExtras,
3572 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003573 }
3574 }
3575
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003576 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003577 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003578
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003579 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003580 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003581 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3582 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3583 request.physicalCameraIds.size(), result->num_physcam_metadata);
3584 return;
3585 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003586 if (request.haveResultMetadata) {
3587 SET_ERR("Called multiple times with metadata for frame %d",
3588 frameNumber);
3589 return;
3590 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003591 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3592 String8 physicalId(result->physcam_ids[i]);
3593 std::set<String8>::iterator cameraIdIter =
3594 request.physicalCameraIds.find(physicalId);
3595 if (cameraIdIter != request.physicalCameraIds.end()) {
3596 request.physicalCameraIds.erase(cameraIdIter);
3597 } else {
3598 SET_ERR("Total result for frame %d has already returned for camera %s",
3599 frameNumber, physicalId.c_str());
3600 return;
3601 }
3602 }
Zhijun He204e3292014-07-14 17:09:23 -07003603 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003604 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003605 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003606 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003607 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003608 request.haveResultMetadata = true;
3609 }
3610
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003611 uint32_t numBuffersReturned = result->num_output_buffers;
3612 if (result->input_buffer != NULL) {
3613 if (hasInputBufferInRequest) {
3614 numBuffersReturned += 1;
3615 } else {
3616 ALOGW("%s: Input buffer should be NULL if there is no input"
3617 " buffer sent in the request",
3618 __FUNCTION__);
3619 }
3620 }
3621 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003622 if (request.numBuffersLeft < 0) {
3623 SET_ERR("Too many buffers returned for frame %d",
3624 frameNumber);
3625 return;
3626 }
3627
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003628 camera_metadata_ro_entry_t entry;
3629 res = find_camera_metadata_ro_entry(result->result,
3630 ANDROID_SENSOR_TIMESTAMP, &entry);
3631 if (res == OK && entry.count == 1) {
3632 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003633 }
3634
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003635 // If shutter event isn't received yet, append the output buffers to
3636 // the in-flight request. Otherwise, return the output buffers to
3637 // streams.
3638 if (shutterTimestamp == 0) {
3639 request.pendingOutputBuffers.appendArray(result->output_buffers,
3640 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003641 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003642 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003643 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003644 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3645 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003646 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003647
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003648 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003649 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3650 CameraMetadata physicalMetadata;
3651 physicalMetadata.append(result->physcam_metadata[i]);
3652 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3653 physicalMetadata});
3654 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003655 if (shutterTimestamp == 0) {
3656 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003657 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003658 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003659 CameraMetadata metadata;
3660 metadata = result->result;
3661 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003662 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003663 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003664 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003665 }
3666
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003667 removeInFlightRequestIfReadyLocked(idx);
3668 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003669
Zhijun Hef0d962a2014-06-30 10:24:11 -07003670 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003671 if (hasInputBufferInRequest) {
3672 Camera3Stream *stream =
3673 Camera3Stream::cast(result->input_buffer->stream);
3674 res = stream->returnInputBuffer(*(result->input_buffer));
3675 // Note: stream may be deallocated at this point, if this buffer was the
3676 // last reference to it.
3677 if (res != OK) {
3678 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3679 " its stream:%s (%d)", __FUNCTION__,
3680 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003681 }
3682 } else {
3683 ALOGW("%s: Input buffer should be NULL if there is no input"
3684 " buffer sent in the request, skipping input buffer return.",
3685 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003686 }
3687 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003688}
3689
3690void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003691 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003692 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003693 {
3694 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003695 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003696 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003697
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003698 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003699 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003700 return;
3701 }
3702
3703 switch (msg->type) {
3704 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003705 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003706 break;
3707 }
3708 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003709 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003710 break;
3711 }
3712 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003713 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003714 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003715 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003716}
3717
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003718void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003719 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003720 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003721 // Map camera HAL error codes to ICameraDeviceCallback error codes
3722 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003723 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003724 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003725 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003726 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003727 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003728 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003729 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003730 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003731 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003732 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003733 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003734 };
3735
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003736 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003737 ((msg.error_code >= 0) &&
3738 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3739 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003740 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003741
3742 int streamId = 0;
3743 if (msg.error_stream != NULL) {
3744 Camera3Stream *stream =
3745 Camera3Stream::cast(msg.error_stream);
3746 streamId = stream->getId();
3747 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003748 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3749 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003750 streamId, msg.error_code);
3751
3752 CaptureResultExtras resultExtras;
3753 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003754 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003755 // SET_ERR calls notifyError
3756 SET_ERR("Camera HAL reported serious device error");
3757 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003758 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3759 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3760 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003761 {
3762 Mutex::Autolock l(mInFlightLock);
3763 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3764 if (idx >= 0) {
3765 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3766 r.requestStatus = msg.error_code;
3767 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003768 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3769 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3770 errorCode) {
3771 r.skipResultMetadata = true;
3772 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003773 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3774 errorCode) {
3775 // In case of missing result check whether the buffers
3776 // returned. If they returned, then remove inflight
3777 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003778 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3779 // otherwise we are depending on HAL to send the buffers back after
3780 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003781 removeInFlightRequestIfReadyLocked(idx);
3782 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003783 } else {
3784 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003785 ALOGE("Camera %s: %s: cannot find in-flight request on "
3786 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003787 resultExtras.frameNumber);
3788 }
3789 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003790 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003791 if (listener != NULL) {
3792 listener->notifyError(errorCode, resultExtras);
3793 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003794 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003795 }
3796 break;
3797 default:
3798 // SET_ERR calls notifyError
3799 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3800 break;
3801 }
3802}
3803
3804void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003805 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003806 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003807 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003808
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003809 // Set timestamp for the request in the in-flight tracking
3810 // and get the request ID to send upstream
3811 {
3812 Mutex::Autolock l(mInFlightLock);
3813 idx = mInFlightMap.indexOfKey(msg.frame_number);
3814 if (idx >= 0) {
3815 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003816
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003817 // Verify ordering of shutter notifications
3818 {
3819 Mutex::Autolock l(mOutputLock);
3820 // TODO: need to track errors for tighter bounds on expected frame number.
3821 if (r.hasInputBuffer) {
3822 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3823 SET_ERR("Shutter notification out-of-order. Expected "
3824 "notification for frame %d, got frame %d",
3825 mNextReprocessShutterFrameNumber, msg.frame_number);
3826 return;
3827 }
3828 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3829 } else {
3830 if (msg.frame_number < mNextShutterFrameNumber) {
3831 SET_ERR("Shutter notification out-of-order. Expected "
3832 "notification for frame %d, got frame %d",
3833 mNextShutterFrameNumber, msg.frame_number);
3834 return;
3835 }
3836 mNextShutterFrameNumber = msg.frame_number + 1;
3837 }
3838 }
3839
Shuzhen Wang4a472662017-02-26 23:29:04 -08003840 r.shutterTimestamp = msg.timestamp;
3841 if (r.hasCallback) {
3842 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003843 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003844 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003845 // Call listener, if any
3846 if (listener != NULL) {
3847 listener->notifyShutter(r.resultExtras, msg.timestamp);
3848 }
3849 // send pending result and buffers
3850 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3851 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003852 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003853 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003854 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003855 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003856 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3857 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003858 r.pendingOutputBuffers.clear();
3859
3860 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003861 }
3862 }
3863 if (idx < 0) {
3864 SET_ERR("Shutter notification for non-existent frame number %d",
3865 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003866 }
3867}
3868
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003869CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003870 ALOGV("%s", __FUNCTION__);
3871
Igor Murashkin1e479c02013-09-06 16:55:14 -07003872 CameraMetadata retVal;
3873
3874 if (mRequestThread != NULL) {
3875 retVal = mRequestThread->getLatestRequest();
3876 }
3877
Igor Murashkin1e479c02013-09-06 16:55:14 -07003878 return retVal;
3879}
3880
Jianing Weicb0652e2014-03-12 18:29:36 -07003881
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003882void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3883 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3884 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3885}
3886
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003887/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003888 * HalInterface inner class methods
3889 */
3890
Yifan Hongf79b5542017-04-11 14:44:25 -07003891Camera3Device::HalInterface::HalInterface(
3892 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003893 std::shared_ptr<RequestMetadataQueue> queue,
3894 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003895 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003896 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003897 mUseHalBufManager(useHalBufManager),
3898 mIsReconfigurationQuerySupported(true) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003899 // Check with hardware service manager if we can downcast these interfaces
3900 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003901 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3902 if (castResult_3_5.isOk()) {
3903 mHidlSession_3_5 = castResult_3_5;
3904 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003905 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3906 if (castResult_3_4.isOk()) {
3907 mHidlSession_3_4 = castResult_3_4;
3908 }
3909 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3910 if (castResult_3_3.isOk()) {
3911 mHidlSession_3_3 = castResult_3_3;
3912 }
3913}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003914
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003915Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003916
3917Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003918 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003919 mRequestMetadataQueue(other.mRequestMetadataQueue),
3920 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003921
3922bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003923 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003924}
3925
3926void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00003927 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003928 mHidlSession_3_4.clear();
3929 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003930 mHidlSession.clear();
3931}
3932
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003933bool Camera3Device::HalInterface::supportBatchRequest() {
3934 return mHidlSession != nullptr;
3935}
3936
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003937status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3938 camera3_request_template_t templateId,
3939 /*out*/ camera_metadata_t **requestTemplate) {
3940 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3941 if (!valid()) return INVALID_OPERATION;
3942 status_t res = OK;
3943
Emilian Peev31abd0a2017-05-11 18:37:46 +01003944 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003945
3946 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003947 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003948 status = s;
3949 if (status == common::V1_0::Status::OK) {
3950 const camera_metadata *r =
3951 reinterpret_cast<const camera_metadata_t*>(request.data());
3952 size_t expectedSize = request.size();
3953 int ret = validate_camera_metadata_structure(r, &expectedSize);
3954 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3955 *requestTemplate = clone_camera_metadata(r);
3956 if (*requestTemplate == nullptr) {
3957 ALOGE("%s: Unable to clone camera metadata received from HAL",
3958 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003959 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003960 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003961 } else {
3962 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3963 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003964 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003965 }
3966 };
3967 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003968 RequestTemplate id;
3969 switch (templateId) {
3970 case CAMERA3_TEMPLATE_PREVIEW:
3971 id = RequestTemplate::PREVIEW;
3972 break;
3973 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3974 id = RequestTemplate::STILL_CAPTURE;
3975 break;
3976 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3977 id = RequestTemplate::VIDEO_RECORD;
3978 break;
3979 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3980 id = RequestTemplate::VIDEO_SNAPSHOT;
3981 break;
3982 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3983 id = RequestTemplate::ZERO_SHUTTER_LAG;
3984 break;
3985 case CAMERA3_TEMPLATE_MANUAL:
3986 id = RequestTemplate::MANUAL;
3987 break;
3988 default:
3989 // Unknown template ID, or this HAL is too old to support it
3990 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003991 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003992 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003993
Emilian Peev31abd0a2017-05-11 18:37:46 +01003994 if (!err.isOk()) {
3995 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3996 res = DEAD_OBJECT;
3997 } else {
3998 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003999 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004000
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004001 return res;
4002}
4003
Emilian Peev4ec17882019-01-24 17:16:58 -08004004bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4005 CameraMetadata& newSessionParams) {
4006 // We do reconfiguration by default;
4007 bool ret = true;
4008 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4009 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4010 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4011 oldSessionParams.getAndLock());
4012 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4013 newSessionParams.getAndLock());
4014 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4015 get_camera_metadata_size(oldSessioMeta));
4016 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4017 get_camera_metadata_size(newSessioMeta));
4018 hardware::camera::common::V1_0::Status callStatus;
4019 bool required;
4020 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4021 bool requiredFlag) {
4022 callStatus = s;
4023 required = requiredFlag;
4024 };
4025 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4026 oldSessionParams.unlock(oldSessioMeta);
4027 newSessionParams.unlock(newSessioMeta);
4028 if (err.isOk()) {
4029 switch (callStatus) {
4030 case hardware::camera::common::V1_0::Status::OK:
4031 ret = required;
4032 break;
4033 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4034 mIsReconfigurationQuerySupported = false;
4035 ret = true;
4036 break;
4037 default:
4038 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4039 ret = true;
4040 }
4041 } else {
4042 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4043 ret = true;
4044 }
4045 }
4046
4047 return ret;
4048}
4049
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004050status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004051 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004052 ATRACE_NAME("CameraHal::configureStreams");
4053 if (!valid()) return INVALID_OPERATION;
4054 status_t res = OK;
4055
Emilian Peev31abd0a2017-05-11 18:37:46 +01004056 // Convert stream config to HIDL
4057 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004058 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4059 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4060 requestedConfiguration3_2.streams.resize(config->num_streams);
4061 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004062 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004063 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4064 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004065 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004066
Emilian Peev31abd0a2017-05-11 18:37:46 +01004067 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4068 cam3stream->setBufferFreedListener(this);
4069 int streamId = cam3stream->getId();
4070 StreamType streamType;
4071 switch (src->stream_type) {
4072 case CAMERA3_STREAM_OUTPUT:
4073 streamType = StreamType::OUTPUT;
4074 break;
4075 case CAMERA3_STREAM_INPUT:
4076 streamType = StreamType::INPUT;
4077 break;
4078 default:
4079 ALOGE("%s: Stream %d: Unsupported stream type %d",
4080 __FUNCTION__, streamId, config->streams[i]->stream_type);
4081 return BAD_VALUE;
4082 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004083 dst3_2.id = streamId;
4084 dst3_2.streamType = streamType;
4085 dst3_2.width = src->width;
4086 dst3_2.height = src->height;
4087 dst3_2.format = mapToPixelFormat(src->format);
4088 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
4089 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4090 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
4091 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004092 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004093 if (src->physical_camera_id != nullptr) {
4094 dst3_4.physicalCameraId = src->physical_camera_id;
4095 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004096
4097 activeStreams.insert(streamId);
4098 // Create Buffer ID map if necessary
4099 if (mBufferIdMaps.count(streamId) == 0) {
4100 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4101 }
4102 }
4103 // remove BufferIdMap for deleted streams
4104 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4105 int streamId = it->first;
4106 bool active = activeStreams.count(streamId) > 0;
4107 if (!active) {
4108 it = mBufferIdMaps.erase(it);
4109 } else {
4110 ++it;
4111 }
4112 }
4113
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004114 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004115 res = mapToStreamConfigurationMode(
4116 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004117 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004118 if (res != OK) {
4119 return res;
4120 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004121 requestedConfiguration3_2.operationMode = operationMode;
4122 requestedConfiguration3_4.operationMode = operationMode;
4123 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004124 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4125 get_camera_metadata_size(sessionParams));
4126
Emilian Peev31abd0a2017-05-11 18:37:46 +01004127 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004128 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004129 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004130 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004131
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004132 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004133 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4134 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004135 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004136 };
4137
4138 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4139 (hardware::Return<void>& err) -> status_t {
4140 if (!err.isOk()) {
4141 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4142 return DEAD_OBJECT;
4143 }
4144 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4145 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4146 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4147 }
4148 return OK;
4149 };
4150
4151 // See if we have v3.4 or v3.3 HAL
4152 if (mHidlSession_3_5 != nullptr) {
4153 ALOGV("%s: v3.5 device found", __FUNCTION__);
4154 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4155 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4156 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4157 auto err = mHidlSession_3_5->configureStreams_3_5(
4158 requestedConfiguration3_5, configStream34Cb);
4159 res = postprocConfigStream34(err);
4160 if (res != OK) {
4161 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004162 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004163 } else if (mHidlSession_3_4 != nullptr) {
4164 // We do; use v3.4 for the call
4165 ALOGV("%s: v3.4 device found", __FUNCTION__);
4166 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
4167 auto err = mHidlSession_3_4->configureStreams_3_4(
4168 requestedConfiguration3_4, configStream34Cb);
4169 res = postprocConfigStream34(err);
4170 if (res != OK) {
4171 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004172 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004173 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004174 // We do; use v3.3 for the call
4175 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004176 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004177 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004178 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004179 finalConfiguration = halConfiguration;
4180 status = s;
4181 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004182 if (!err.isOk()) {
4183 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4184 return DEAD_OBJECT;
4185 }
4186 } else {
4187 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4188 ALOGV("%s: v3.2 device found", __FUNCTION__);
4189 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004190 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004191 [&status, &finalConfiguration_3_2]
4192 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4193 finalConfiguration_3_2 = halConfiguration;
4194 status = s;
4195 });
4196 if (!err.isOk()) {
4197 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4198 return DEAD_OBJECT;
4199 }
4200 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4201 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4202 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4203 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004204 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004205 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004206 }
4207
4208 if (status != common::V1_0::Status::OK ) {
4209 return CameraProviderManager::mapToStatusT(status);
4210 }
4211
4212 // And convert output stream configuration from HIDL
4213
4214 for (size_t i = 0; i < config->num_streams; i++) {
4215 camera3_stream_t *dst = config->streams[i];
4216 int streamId = Camera3Stream::cast(dst)->getId();
4217
4218 // Start scan at i, with the assumption that the stream order matches
4219 size_t realIdx = i;
4220 bool found = false;
4221 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004222 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004223 found = true;
4224 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004225 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004226 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4227 }
4228 if (!found) {
4229 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4230 __FUNCTION__, streamId);
4231 return INVALID_OPERATION;
4232 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004233 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004234
Emilian Peev710c1422017-08-30 11:19:38 +01004235 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4236 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004237 dstStream->setDataSpaceOverride(false);
4238 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4239 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4240
Emilian Peev31abd0a2017-05-11 18:37:46 +01004241 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4242 if (dst->format != overrideFormat) {
4243 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4244 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004245 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004246 if (dst->data_space != overrideDataSpace) {
4247 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4248 streamId, dst->format);
4249 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004250 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004251 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004252 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4253
Emilian Peev31abd0a2017-05-11 18:37:46 +01004254 // Override allowed with IMPLEMENTATION_DEFINED
4255 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004256 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004257 }
4258
Emilian Peev31abd0a2017-05-11 18:37:46 +01004259 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004260 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004261 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004262 __FUNCTION__, streamId);
4263 return INVALID_OPERATION;
4264 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004265 dstStream->setUsage(
4266 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004267 } else {
4268 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004269 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004270 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4271 __FUNCTION__, streamId);
4272 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004273 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004274 dstStream->setUsage(
4275 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004276 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004277 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004278 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004279
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004280 return res;
4281}
4282
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004283status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004284 /*out*/device::V3_2::CaptureRequest* captureRequest,
4285 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004286 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004287 if (captureRequest == nullptr || handlesCreated == nullptr) {
4288 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4289 __FUNCTION__, captureRequest, handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004290 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004291 }
4292
4293 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004294
4295 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004296
4297 {
4298 std::lock_guard<std::mutex> lock(mInflightLock);
4299 if (request->input_buffer != nullptr) {
4300 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4301 buffer_handle_t buf = *(request->input_buffer->buffer);
4302 auto pair = getBufferId(buf, streamId);
4303 bool isNewBuffer = pair.first;
4304 uint64_t bufferId = pair.second;
4305 captureRequest->inputBuffer.streamId = streamId;
4306 captureRequest->inputBuffer.bufferId = bufferId;
4307 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4308 captureRequest->inputBuffer.status = BufferStatus::OK;
4309 native_handle_t *acquireFence = nullptr;
4310 if (request->input_buffer->acquire_fence != -1) {
4311 acquireFence = native_handle_create(1,0);
4312 acquireFence->data[0] = request->input_buffer->acquire_fence;
4313 handlesCreated->push_back(acquireFence);
4314 }
4315 captureRequest->inputBuffer.acquireFence = acquireFence;
4316 captureRequest->inputBuffer.releaseFence = nullptr;
4317
4318 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4319 request->input_buffer->buffer,
4320 request->input_buffer->acquire_fence);
4321 } else {
4322 captureRequest->inputBuffer.streamId = -1;
4323 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4324 }
4325
4326 captureRequest->outputBuffers.resize(request->num_output_buffers);
4327 for (size_t i = 0; i < request->num_output_buffers; i++) {
4328 const camera3_stream_buffer_t *src = request->output_buffers + i;
4329 StreamBuffer &dst = captureRequest->outputBuffers[i];
4330 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004331 if (src->buffer != nullptr) {
4332 buffer_handle_t buf = *(src->buffer);
4333 auto pair = getBufferId(buf, streamId);
4334 bool isNewBuffer = pair.first;
4335 dst.bufferId = pair.second;
4336 dst.buffer = isNewBuffer ? buf : nullptr;
4337 native_handle_t *acquireFence = nullptr;
4338 if (src->acquire_fence != -1) {
4339 acquireFence = native_handle_create(1,0);
4340 acquireFence->data[0] = src->acquire_fence;
4341 handlesCreated->push_back(acquireFence);
4342 }
4343 dst.acquireFence = acquireFence;
4344 } else if (mUseHalBufManager) {
4345 // HAL buffer management path
4346 dst.bufferId = BUFFER_ID_NO_BUFFER;
4347 dst.buffer = nullptr;
4348 dst.acquireFence = nullptr;
4349 } else {
4350 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4351 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004352 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004353 dst.streamId = streamId;
4354 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004355 dst.releaseFence = nullptr;
4356
4357 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4358 src->buffer, src->acquire_fence);
4359 }
4360 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004361 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004362}
4363
4364status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4365 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4366 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4367 if (!valid()) return INVALID_OPERATION;
4368
Emilian Peevaebbe412018-01-15 13:53:24 +00004369 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4370 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4371 if (castResult_3_4.isOk()) {
4372 hidlSession_3_4 = castResult_3_4;
4373 }
4374
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004375 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004376 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004377 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004378 if (hidlSession_3_4 != nullptr) {
4379 captureRequests_3_4.resize(batchSize);
4380 } else {
4381 captureRequests.resize(batchSize);
4382 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004383 std::vector<native_handle_t*> handlesCreated;
4384
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004385 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004386 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004387 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004388 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Emilian Peevaebbe412018-01-15 13:53:24 +00004389 /*out*/&handlesCreated);
4390 } else {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004391 res = wrapAsHidlRequest(requests[i],
4392 /*out*/&captureRequests[i], /*out*/&handlesCreated);
4393 }
4394 if (res != OK) {
4395 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004396 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004397 }
4398
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004399 std::vector<device::V3_2::BufferCache> cachesToRemove;
4400 {
4401 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4402 for (auto& pair : mFreedBuffers) {
4403 // The stream might have been removed since onBufferFreed
4404 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4405 cachesToRemove.push_back({pair.first, pair.second});
4406 }
4407 }
4408 mFreedBuffers.clear();
4409 }
4410
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004411 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4412 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004413
4414 // Write metadata to FMQ.
4415 for (size_t i = 0; i < batchSize; i++) {
4416 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004417 device::V3_2::CaptureRequest* captureRequest;
4418 if (hidlSession_3_4 != nullptr) {
4419 captureRequest = &captureRequests_3_4[i].v3_2;
4420 } else {
4421 captureRequest = &captureRequests[i];
4422 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004423
4424 if (request->settings != nullptr) {
4425 size_t settingsSize = get_camera_metadata_size(request->settings);
4426 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4427 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4428 captureRequest->settings.resize(0);
4429 captureRequest->fmqSettingsSize = settingsSize;
4430 } else {
4431 if (mRequestMetadataQueue != nullptr) {
4432 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4433 }
4434 captureRequest->settings.setToExternal(
4435 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4436 get_camera_metadata_size(request->settings));
4437 captureRequest->fmqSettingsSize = 0u;
4438 }
4439 } else {
4440 // A null request settings maps to a size-0 CameraMetadata
4441 captureRequest->settings.resize(0);
4442 captureRequest->fmqSettingsSize = 0u;
4443 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004444
4445 if (hidlSession_3_4 != nullptr) {
4446 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4447 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004448 if (request->physcam_settings != nullptr) {
4449 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4450 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4451 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4452 settingsSize)) {
4453 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4454 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4455 settingsSize;
4456 } else {
4457 if (mRequestMetadataQueue != nullptr) {
4458 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4459 }
4460 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4461 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4462 request->physcam_settings[j])),
4463 get_camera_metadata_size(request->physcam_settings[j]));
4464 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004465 }
Emilian Peev00420d22018-02-05 21:33:13 +00004466 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004467 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004468 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004469 }
4470 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4471 request->physcam_id[j];
4472 }
4473 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004474 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004475
4476 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004477 auto resultCallback =
4478 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4479 status = s;
4480 *numRequestProcessed = n;
4481 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004482 if (hidlSession_3_4 != nullptr) {
4483 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004484 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004485 } else {
4486 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004487 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004488 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004489 if (!err.isOk()) {
4490 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4491 return DEAD_OBJECT;
4492 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004493 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4494 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4495 __FUNCTION__, *numRequestProcessed, batchSize);
4496 status = common::V1_0::Status::INTERNAL_ERROR;
4497 }
4498
4499 for (auto& handle : handlesCreated) {
4500 native_handle_delete(handle);
4501 }
4502 return CameraProviderManager::mapToStatusT(status);
4503}
4504
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004505status_t Camera3Device::HalInterface::processCaptureRequest(
4506 camera3_capture_request_t *request) {
4507 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004508 if (!valid()) return INVALID_OPERATION;
4509 status_t res = OK;
4510
Emilian Peev31abd0a2017-05-11 18:37:46 +01004511 uint32_t numRequestProcessed = 0;
4512 std::vector<camera3_capture_request_t*> requests(1);
4513 requests[0] = request;
4514 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4515
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004516 return res;
4517}
4518
4519status_t Camera3Device::HalInterface::flush() {
4520 ATRACE_NAME("CameraHal::flush");
4521 if (!valid()) return INVALID_OPERATION;
4522 status_t res = OK;
4523
Emilian Peev31abd0a2017-05-11 18:37:46 +01004524 auto err = mHidlSession->flush();
4525 if (!err.isOk()) {
4526 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4527 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004528 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004529 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004530 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004531
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004532 return res;
4533}
4534
Emilian Peev31abd0a2017-05-11 18:37:46 +01004535status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004536 ATRACE_NAME("CameraHal::dump");
4537 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004538
Emilian Peev31abd0a2017-05-11 18:37:46 +01004539 // Handled by CameraProviderManager::dump
4540
4541 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004542}
4543
4544status_t Camera3Device::HalInterface::close() {
4545 ATRACE_NAME("CameraHal::close()");
4546 if (!valid()) return INVALID_OPERATION;
4547 status_t res = OK;
4548
Emilian Peev31abd0a2017-05-11 18:37:46 +01004549 auto err = mHidlSession->close();
4550 // Interface will be dead shortly anyway, so don't log errors
4551 if (!err.isOk()) {
4552 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004553 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004554
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004555 return res;
4556}
4557
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004558void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4559 ATRACE_NAME("CameraHal::signalPipelineDrain");
4560 if (!valid() || mHidlSession_3_5 == nullptr) {
4561 ALOGE("%s called on invalid camera!", __FUNCTION__);
4562 return;
4563 }
4564
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004565 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004566 if (!err.isOk()) {
4567 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4568 return;
4569 }
4570}
4571
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004572void Camera3Device::HalInterface::getInflightBufferKeys(
4573 std::vector<std::pair<int32_t, int32_t>>* out) {
4574 std::lock_guard<std::mutex> lock(mInflightLock);
4575 out->clear();
4576 out->reserve(mInflightBufferMap.size());
4577 for (auto& pair : mInflightBufferMap) {
4578 uint64_t key = pair.first;
4579 int32_t streamId = key & 0xFFFFFFFF;
4580 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4581 out->push_back(std::make_pair(frameNumber, streamId));
4582 }
4583 return;
4584}
4585
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004586status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004587 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004588 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004589 auto pair = std::make_pair(buffer, acquireFence);
4590 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004591 return OK;
4592}
4593
4594status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004595 int32_t frameNumber, int32_t streamId,
4596 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004597 std::lock_guard<std::mutex> lock(mInflightLock);
4598
4599 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4600 auto it = mInflightBufferMap.find(key);
4601 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004602 auto pair = it->second;
4603 *buffer = pair.first;
4604 int acquireFence = pair.second;
4605 if (acquireFence > 0) {
4606 ::close(acquireFence);
4607 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004608 mInflightBufferMap.erase(it);
4609 return OK;
4610}
4611
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004612status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4613 uint64_t bufferId, buffer_handle_t* buf) {
4614 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4615 auto pair = mRequestedBuffers.insert({bufferId, buf});
4616 if (!pair.second) {
4617 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4618 __FUNCTION__, bufferId);
4619 return BAD_VALUE;
4620 }
4621 return OK;
4622}
4623
4624// Find and pop a buffer_handle_t based on bufferId
4625status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4626 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4627 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4628 auto it = mRequestedBuffers.find(bufferId);
4629 if (it == mRequestedBuffers.end()) {
4630 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4631 __FUNCTION__, bufferId);
4632 return BAD_VALUE;
4633 }
4634 *buffer = it->second;
4635 mRequestedBuffers.erase(it);
4636 return OK;
4637}
4638
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004639std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4640 const buffer_handle_t& buf, int streamId) {
4641 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4642
4643 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4644 auto it = bIdMap.find(buf);
4645 if (it == bIdMap.end()) {
4646 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004647 ALOGV("stream %d now have %zu buffer caches, buf %p",
4648 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004649 return std::make_pair(true, mNextBufferId - 1);
4650 } else {
4651 return std::make_pair(false, it->second);
4652 }
4653}
4654
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004655void Camera3Device::HalInterface::onBufferFreed(
4656 int streamId, const native_handle_t* handle) {
4657 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4658 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4659 auto mapIt = mBufferIdMaps.find(streamId);
4660 if (mapIt == mBufferIdMaps.end()) {
4661 // streamId might be from a deleted stream here
4662 ALOGI("%s: stream %d has been removed",
4663 __FUNCTION__, streamId);
4664 return;
4665 }
4666 BufferIdMap& bIdMap = mapIt->second;
4667 auto it = bIdMap.find(handle);
4668 if (it == bIdMap.end()) {
4669 ALOGW("%s: cannot find buffer %p in stream %d",
4670 __FUNCTION__, handle, streamId);
4671 return;
4672 } else {
4673 bufferId = it->second;
4674 bIdMap.erase(it);
4675 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4676 __FUNCTION__, streamId, bIdMap.size(), handle);
4677 }
4678 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4679}
4680
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004681/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004682 * RequestThread inner class methods
4683 */
4684
4685Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004686 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004687 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4688 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004689 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004690 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004691 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004692 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004693 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004694 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004695 mReconfigured(false),
4696 mDoPause(false),
4697 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004698 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004699 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004700 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004701 mCurrentAfTriggerId(0),
4702 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004703 mRepeatingLastFrameNumber(
4704 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004705 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004706 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004707 mRequestLatency(kRequestLatencyBinSize),
4708 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004709 mLatestSessionParams(sessionParamKeys.size()),
4710 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004711 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004712}
4713
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004714Camera3Device::RequestThread::~RequestThread() {}
4715
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004716void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004717 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004718 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004719 Mutex::Autolock l(mRequestLock);
4720 mListener = listener;
4721}
4722
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004723void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4724 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004725 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004726 Mutex::Autolock l(mRequestLock);
4727 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004728 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004729 // Prepare video stream for high speed recording.
4730 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004731 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004732}
4733
Jianing Wei90e59c92014-03-12 18:29:36 -07004734status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004735 List<sp<CaptureRequest> > &requests,
4736 /*out*/
4737 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004738 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004739 Mutex::Autolock l(mRequestLock);
4740 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4741 ++it) {
4742 mRequestQueue.push_back(*it);
4743 }
4744
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004745 if (lastFrameNumber != NULL) {
4746 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4747 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4748 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4749 *lastFrameNumber);
4750 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004751
Jianing Wei90e59c92014-03-12 18:29:36 -07004752 unpauseForNewRequests();
4753
4754 return OK;
4755}
4756
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004757
4758status_t Camera3Device::RequestThread::queueTrigger(
4759 RequestTrigger trigger[],
4760 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004761 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004762 Mutex::Autolock l(mTriggerMutex);
4763 status_t ret;
4764
4765 for (size_t i = 0; i < count; ++i) {
4766 ret = queueTriggerLocked(trigger[i]);
4767
4768 if (ret != OK) {
4769 return ret;
4770 }
4771 }
4772
4773 return OK;
4774}
4775
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004776const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4777 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004778 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004779 if (d != nullptr) return d->mId;
4780 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004781}
4782
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004783status_t Camera3Device::RequestThread::queueTriggerLocked(
4784 RequestTrigger trigger) {
4785
4786 uint32_t tag = trigger.metadataTag;
4787 ssize_t index = mTriggerMap.indexOfKey(tag);
4788
4789 switch (trigger.getTagType()) {
4790 case TYPE_BYTE:
4791 // fall-through
4792 case TYPE_INT32:
4793 break;
4794 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004795 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4796 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004797 return INVALID_OPERATION;
4798 }
4799
4800 /**
4801 * Collect only the latest trigger, since we only have 1 field
4802 * in the request settings per trigger tag, and can't send more than 1
4803 * trigger per request.
4804 */
4805 if (index != NAME_NOT_FOUND) {
4806 mTriggerMap.editValueAt(index) = trigger;
4807 } else {
4808 mTriggerMap.add(tag, trigger);
4809 }
4810
4811 return OK;
4812}
4813
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004814status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004815 const RequestList &requests,
4816 /*out*/
4817 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004818 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004819 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004820 if (lastFrameNumber != NULL) {
4821 *lastFrameNumber = mRepeatingLastFrameNumber;
4822 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004823 mRepeatingRequests.clear();
4824 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4825 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004826
4827 unpauseForNewRequests();
4828
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004829 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004830 return OK;
4831}
4832
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004833bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004834 if (mRepeatingRequests.empty()) {
4835 return false;
4836 }
4837 int32_t requestId = requestIn->mResultExtras.requestId;
4838 const RequestList &repeatRequests = mRepeatingRequests;
4839 // All repeating requests are guaranteed to have same id so only check first quest
4840 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4841 return (firstRequest->mResultExtras.requestId == requestId);
4842}
4843
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004844status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004845 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004846 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004847 return clearRepeatingRequestsLocked(lastFrameNumber);
4848
4849}
4850
4851status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004852 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004853 if (lastFrameNumber != NULL) {
4854 *lastFrameNumber = mRepeatingLastFrameNumber;
4855 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004856 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004857 return OK;
4858}
4859
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004860status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004861 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004862 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004863 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004864 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004865
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004866 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004867
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004868 // Send errors for all requests pending in the request queue, including
4869 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004870 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004871 if (listener != NULL) {
4872 for (RequestList::iterator it = mRequestQueue.begin();
4873 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004874 // Abort the input buffers for reprocess requests.
4875 if ((*it)->mInputStream != NULL) {
4876 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004877 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4878 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004879 if (res != OK) {
4880 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4881 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4882 } else {
4883 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4884 if (res != OK) {
4885 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4886 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4887 }
4888 }
4889 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004890 // Set the frame number this request would have had, if it
4891 // had been submitted; this frame number will not be reused.
4892 // The requestId and burstId fields were set when the request was
4893 // submitted originally (in convertMetadataListToRequestListLocked)
4894 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004895 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004896 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004897 }
4898 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004899 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004900
4901 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004902 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004903 if (lastFrameNumber != NULL) {
4904 *lastFrameNumber = mRepeatingLastFrameNumber;
4905 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004906 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004907 return OK;
4908}
4909
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004910status_t Camera3Device::RequestThread::flush() {
4911 ATRACE_CALL();
4912 Mutex::Autolock l(mFlushLock);
4913
Emilian Peev08dd2452017-04-06 16:55:14 +01004914 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004915}
4916
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004917void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004918 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004919 Mutex::Autolock l(mPauseLock);
4920 mDoPause = paused;
4921 mDoPauseSignal.signal();
4922}
4923
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004924status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4925 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004926 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004927 Mutex::Autolock l(mLatestRequestMutex);
4928 status_t res;
4929 while (mLatestRequestId != requestId) {
4930 nsecs_t startTime = systemTime();
4931
4932 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4933 if (res != OK) return res;
4934
4935 timeout -= (systemTime() - startTime);
4936 }
4937
4938 return OK;
4939}
4940
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004941void Camera3Device::RequestThread::requestExit() {
4942 // Call parent to set up shutdown
4943 Thread::requestExit();
4944 // The exit from any possible waits
4945 mDoPauseSignal.signal();
4946 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004947
4948 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4949 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004950}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004951
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004952void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004953 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004954 bool surfaceAbandoned = false;
4955 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004956 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004957 {
4958 Mutex::Autolock l(mRequestLock);
4959 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4960 // repeating requests.
4961 for (const auto& request : mRepeatingRequests) {
4962 for (const auto& s : request->mOutputStreams) {
4963 if (s->isAbandoned()) {
4964 surfaceAbandoned = true;
4965 clearRepeatingRequestsLocked(&lastFrameNumber);
4966 break;
4967 }
4968 }
4969 if (surfaceAbandoned) {
4970 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004971 }
4972 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004973 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004974 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004975
4976 if (listener != NULL && surfaceAbandoned) {
4977 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004978 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004979}
4980
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004981bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004982 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004983 status_t res;
4984 size_t batchSize = mNextRequests.size();
4985 std::vector<camera3_capture_request_t*> requests(batchSize);
4986 uint32_t numRequestProcessed = 0;
4987 for (size_t i = 0; i < batchSize; i++) {
4988 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004989 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004990 }
4991
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004992 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4993
4994 bool triggerRemoveFailed = false;
4995 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4996 for (size_t i = 0; i < numRequestProcessed; i++) {
4997 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4998 nextRequest.submitted = true;
4999
5000
5001 // Update the latest request sent to HAL
5002 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5003 Mutex::Autolock al(mLatestRequestMutex);
5004
5005 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5006 mLatestRequest.acquire(cloned);
5007
5008 sp<Camera3Device> parent = mParent.promote();
5009 if (parent != NULL) {
5010 parent->monitorMetadata(TagMonitor::REQUEST,
5011 nextRequest.halRequest.frame_number,
5012 0, mLatestRequest);
5013 }
5014 }
5015
5016 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005017 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5018 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005019 }
5020
Emilian Peevaebbe412018-01-15 13:53:24 +00005021 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5022
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005023 if (!triggerRemoveFailed) {
5024 // Remove any previously queued triggers (after unlock)
5025 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5026 if (removeTriggerRes != OK) {
5027 triggerRemoveFailed = true;
5028 triggerFailedRequest = nextRequest;
5029 }
5030 }
5031 }
5032
5033 if (triggerRemoveFailed) {
5034 SET_ERR("RequestThread: Unable to remove triggers "
5035 "(capture request %d, HAL device: %s (%d)",
5036 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5037 cleanUpFailedRequests(/*sendRequestError*/ false);
5038 return false;
5039 }
5040
5041 if (res != OK) {
5042 // Should only get a failure here for malformed requests or device-level
5043 // errors, so consider all errors fatal. Bad metadata failures should
5044 // come through notify.
5045 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5046 mNextRequests[numRequestProcessed].halRequest.frame_number,
5047 strerror(-res), res);
5048 cleanUpFailedRequests(/*sendRequestError*/ false);
5049 return false;
5050 }
5051 return true;
5052}
5053
5054bool Camera3Device::RequestThread::sendRequestsOneByOne() {
5055 status_t res;
5056
5057 for (auto& nextRequest : mNextRequests) {
5058 // Submit request and block until ready for next one
5059 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
5060 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
5061
5062 if (res != OK) {
5063 // Should only get a failure here for malformed requests or device-level
5064 // errors, so consider all errors fatal. Bad metadata failures should
5065 // come through notify.
5066 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
5067 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
5068 res);
5069 cleanUpFailedRequests(/*sendRequestError*/ false);
5070 return false;
5071 }
5072
5073 // Mark that the request has be submitted successfully.
5074 nextRequest.submitted = true;
5075
5076 // Update the latest request sent to HAL
5077 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5078 Mutex::Autolock al(mLatestRequestMutex);
5079
5080 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5081 mLatestRequest.acquire(cloned);
5082
5083 sp<Camera3Device> parent = mParent.promote();
5084 if (parent != NULL) {
5085 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
5086 0, mLatestRequest);
5087 }
5088 }
5089
5090 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005091 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5092 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005093 }
5094
Emilian Peevaebbe412018-01-15 13:53:24 +00005095 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5096
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005097 // Remove any previously queued triggers (after unlock)
5098 res = removeTriggers(mPrevRequest);
5099 if (res != OK) {
5100 SET_ERR("RequestThread: Unable to remove triggers "
5101 "(capture request %d, HAL device: %s (%d)",
5102 nextRequest.halRequest.frame_number, strerror(-res), res);
5103 cleanUpFailedRequests(/*sendRequestError*/ false);
5104 return false;
5105 }
5106 }
5107 return true;
5108}
5109
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005110nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5111 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5112 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5113 find_camera_metadata_ro_entry(request,
5114 ANDROID_CONTROL_AE_MODE,
5115 &e);
5116 if (e.count == 0) return maxExpectedDuration;
5117
5118 switch (e.data.u8[0]) {
5119 case ANDROID_CONTROL_AE_MODE_OFF:
5120 find_camera_metadata_ro_entry(request,
5121 ANDROID_SENSOR_EXPOSURE_TIME,
5122 &e);
5123 if (e.count > 0) {
5124 maxExpectedDuration = e.data.i64[0];
5125 }
5126 find_camera_metadata_ro_entry(request,
5127 ANDROID_SENSOR_FRAME_DURATION,
5128 &e);
5129 if (e.count > 0) {
5130 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5131 }
5132 break;
5133 default:
5134 find_camera_metadata_ro_entry(request,
5135 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5136 &e);
5137 if (e.count > 1) {
5138 maxExpectedDuration = 1e9 / e.data.u8[0];
5139 }
5140 break;
5141 }
5142
5143 return maxExpectedDuration;
5144}
5145
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005146bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5147 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5148 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5149 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5150 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5151 return true;
5152 }
5153
5154 return false;
5155}
5156
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005157bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5158 ATRACE_CALL();
5159 bool updatesDetected = false;
5160
Emilian Peev4ec17882019-01-24 17:16:58 -08005161 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005162 for (auto tag : mSessionParamKeys) {
5163 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005164 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005165
5166 if (entry.count > 0) {
5167 bool isDifferent = false;
5168 if (lastEntry.count > 0) {
5169 // Have a last value, compare to see if changed
5170 if (lastEntry.type == entry.type &&
5171 lastEntry.count == entry.count) {
5172 // Same type and count, compare values
5173 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5174 size_t entryBytes = bytesPerValue * lastEntry.count;
5175 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5176 if (cmp != 0) {
5177 isDifferent = true;
5178 }
5179 } else {
5180 // Count or type has changed
5181 isDifferent = true;
5182 }
5183 } else {
5184 // No last entry, so always consider to be different
5185 isDifferent = true;
5186 }
5187
5188 if (isDifferent) {
5189 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005190 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5191 updatesDetected = true;
5192 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005193 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005194 }
5195 } else if (lastEntry.count > 0) {
5196 // Value has been removed
5197 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005198 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005199 updatesDetected = true;
5200 }
5201 }
5202
Emilian Peev4ec17882019-01-24 17:16:58 -08005203 bool reconfigureRequired;
5204 if (updatesDetected) {
5205 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5206 updatedParams);
5207 mLatestSessionParams = updatedParams;
5208 } else {
5209 reconfigureRequired = false;
5210 }
5211
5212 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005213}
5214
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005215bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005216 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005217 status_t res;
5218
5219 // Handle paused state.
5220 if (waitIfPaused()) {
5221 return true;
5222 }
5223
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005224 // Wait for the next batch of requests.
5225 waitForNextRequestBatch();
5226 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005227 return true;
5228 }
5229
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005230 // Get the latest request ID, if any
5231 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005232 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005233 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005234 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005235 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005236 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005237 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5238 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005239 }
5240
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005241 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5242 // or a single request from streaming or burst. In either case the first element
5243 // should contain the latest camera settings that we need to check for any session
5244 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005245 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005246 res = OK;
5247
5248 //Input stream buffers are already acquired at this point so an input stream
5249 //will not be able to move to idle state unless we force it.
5250 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5251 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5252 if (res != OK) {
5253 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5254 cleanUpFailedRequests(/*sendRequestError*/ false);
5255 return false;
5256 }
5257 }
5258
5259 if (res == OK) {
5260 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5261 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005262 sp<Camera3Device> parent = mParent.promote();
5263 if (parent != nullptr) {
5264 parent->pauseStateNotify(true);
5265 }
5266
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005267 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5268
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005269 if (parent != nullptr) {
5270 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5271 }
5272
5273 statusTracker->markComponentActive(mStatusId);
5274 setPaused(false);
5275 }
5276
5277 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5278 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5279 if (res != OK) {
5280 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5281 cleanUpFailedRequests(/*sendRequestError*/ false);
5282 return false;
5283 }
5284 }
5285 }
5286 }
5287
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005288 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005289 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005290 if (res == TIMED_OUT) {
5291 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005292 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005293 // Check if any stream is abandoned.
5294 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005295 return true;
5296 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005297 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005298 return false;
5299 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005300
Zhijun Hecc27e112013-10-03 16:12:43 -07005301 // Inform waitUntilRequestProcessed thread of a new request ID
5302 {
5303 Mutex::Autolock al(mLatestRequestMutex);
5304
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005305 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005306 mLatestRequestSignal.signal();
5307 }
5308
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005309 // Submit a batch of requests to HAL.
5310 // Use flush lock only when submitting multilple requests in a batch.
5311 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5312 // which may take a long time to finish so synchronizing flush() and
5313 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5314 // For now, only synchronize for high speed recording and we should figure something out for
5315 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005316 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005317
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005318 if (useFlushLock) {
5319 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005320 }
5321
Zhijun Hef0645c12016-08-02 00:58:11 -07005322 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005323 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005324
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005325 sp<Camera3Device> parent = mParent.promote();
5326 if (parent != nullptr) {
5327 parent->mRequestBufferSM.onSubmittingRequest();
5328 }
5329
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005330 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005331 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005332 if (mInterface->supportBatchRequest()) {
5333 submitRequestSuccess = sendRequestsBatch();
5334 } else {
5335 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005336 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005337 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5338 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005339
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005340 if (useFlushLock) {
5341 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005342 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005343
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005344 // Unset as current request
5345 {
5346 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005347 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005348 }
5349
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005350 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005351}
5352
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005353status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005354 ATRACE_CALL();
5355
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005356 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005357 for (size_t i = 0; i < mNextRequests.size(); i++) {
5358 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005359 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5360 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5361 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5362
5363 // Prepare a request to HAL
5364 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5365
5366 // Insert any queued triggers (before metadata is locked)
5367 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005368 if (res < 0) {
5369 SET_ERR("RequestThread: Unable to insert triggers "
5370 "(capture request %d, HAL device: %s (%d)",
5371 halRequest->frame_number, strerror(-res), res);
5372 return INVALID_OPERATION;
5373 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005374
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005375 int triggerCount = res;
5376 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5377 mPrevTriggers = triggerCount;
5378
5379 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005380 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5381 // Request settings are all the same within one batch, so only treat the first
5382 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005383 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005384 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005385 /**
5386 * HAL workaround:
5387 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5388 */
5389 res = addDummyTriggerIds(captureRequest);
5390 if (res != OK) {
5391 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5392 "(capture request %d, HAL device: %s (%d)",
5393 halRequest->frame_number, strerror(-res), res);
5394 return INVALID_OPERATION;
5395 }
5396
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005397 {
5398 // Correct metadata regions for distortion correction if enabled
5399 sp<Camera3Device> parent = mParent.promote();
5400 if (parent != nullptr) {
5401 res = parent->mDistortionMapper.correctCaptureRequest(
5402 &(captureRequest->mSettingsList.begin()->metadata));
5403 if (res != OK) {
5404 SET_ERR("RequestThread: Unable to correct capture requests "
5405 "for lens distortion for request %d: %s (%d)",
5406 halRequest->frame_number, strerror(-res), res);
5407 return INVALID_OPERATION;
5408 }
5409 }
5410 }
5411
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005412 /**
5413 * The request should be presorted so accesses in HAL
5414 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5415 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005416 captureRequest->mSettingsList.begin()->metadata.sort();
5417 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005418 mPrevRequest = captureRequest;
5419 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5420
5421 IF_ALOGV() {
5422 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5423 find_camera_metadata_ro_entry(
5424 halRequest->settings,
5425 ANDROID_CONTROL_AF_TRIGGER,
5426 &e
5427 );
5428 if (e.count > 0) {
5429 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5430 __FUNCTION__,
5431 halRequest->frame_number,
5432 e.data.u8[0]);
5433 }
5434 }
5435 } else {
5436 // leave request.settings NULL to indicate 'reuse latest given'
5437 ALOGVV("%s: Request settings are REUSED",
5438 __FUNCTION__);
5439 }
5440
Emilian Peevaebbe412018-01-15 13:53:24 +00005441 if (captureRequest->mSettingsList.size() > 1) {
5442 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5443 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005444 if (newRequest) {
5445 halRequest->physcam_settings =
5446 new const camera_metadata* [halRequest->num_physcam_settings];
5447 } else {
5448 halRequest->physcam_settings = nullptr;
5449 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005450 auto it = ++captureRequest->mSettingsList.begin();
5451 size_t i = 0;
5452 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5453 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005454 if (newRequest) {
5455 it->metadata.sort();
5456 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5457 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005458 }
5459 }
5460
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005461 uint32_t totalNumBuffers = 0;
5462
5463 // Fill in buffers
5464 if (captureRequest->mInputStream != NULL) {
5465 halRequest->input_buffer = &captureRequest->mInputBuffer;
5466 totalNumBuffers += 1;
5467 } else {
5468 halRequest->input_buffer = NULL;
5469 }
5470
5471 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5472 captureRequest->mOutputStreams.size());
5473 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005474 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005475
5476 sp<Camera3Device> parent = mParent.promote();
5477 if (parent == NULL) {
5478 // Should not happen, and nowhere to send errors to, so just log it
5479 CLOGE("RequestThread: Parent is gone");
5480 return INVALID_OPERATION;
5481 }
5482 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5483
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005484 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005485 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005486 sp<Camera3OutputStreamInterface> outputStream =
5487 captureRequest->mOutputStreams.editItemAt(j);
5488 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005489
5490 // Prepare video buffers for high speed recording on the first video request.
5491 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5492 // Only try to prepare video stream on the first video request.
5493 mPrepareVideoStream = false;
5494
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005495 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5496 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005497 while (res == NOT_ENOUGH_DATA) {
5498 res = outputStream->prepareNextBuffer();
5499 }
5500 if (res != OK) {
5501 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5502 __FUNCTION__, strerror(-res), res);
5503 outputStream->cancelPrepare();
5504 }
5505 }
5506
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005507 std::vector<size_t> uniqueSurfaceIds;
5508 res = outputStream->getUniqueSurfaceIds(
5509 captureRequest->mOutputSurfaces[streamId],
5510 &uniqueSurfaceIds);
5511 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5512 if (res != OK && res != INVALID_OPERATION) {
5513 ALOGE("%s: failed to query stream %d unique surface IDs",
5514 __FUNCTION__, streamId);
5515 return res;
5516 }
5517 if (res == OK) {
5518 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5519 }
5520
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005521 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005522 if (outputStream->isAbandoned()) {
5523 ALOGE("%s: stream %d is abandoned.", __FUNCTION__, streamId);
5524 return TIMED_OUT;
5525 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005526 // HAL will request buffer through requestStreamBuffer API
5527 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5528 buffer.stream = outputStream->asHalStream();
5529 buffer.buffer = nullptr;
5530 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5531 buffer.acquire_fence = -1;
5532 buffer.release_fence = -1;
5533 } else {
5534 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5535 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005536 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005537 if (res != OK) {
5538 // Can't get output buffer from gralloc queue - this could be due to
5539 // abandoned queue or other consumer misbehavior, so not a fatal
5540 // error
5541 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5542 " %s (%d)", strerror(-res), res);
5543
5544 return TIMED_OUT;
5545 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005546 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005547
5548 {
5549 sp<Camera3Device> parent = mParent.promote();
5550 if (parent != nullptr) {
5551 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5552 for (const auto& settings : captureRequest->mSettingsList) {
5553 if ((streamCameraId.isEmpty() &&
5554 parent->getId() == settings.cameraId.c_str()) ||
5555 streamCameraId == settings.cameraId.c_str()) {
5556 outputStream->fireBufferRequestForFrameNumber(
5557 captureRequest->mResultExtras.frameNumber,
5558 settings.metadata);
5559 }
5560 }
5561 }
5562 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005563
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005564 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5565
5566 if (!physicalCameraId.isEmpty()) {
5567 // Physical stream isn't supported for input request.
5568 if (halRequest->input_buffer) {
5569 CLOGE("Physical stream is not supported for input request");
5570 return INVALID_OPERATION;
5571 }
5572 requestedPhysicalCameras.insert(physicalCameraId);
5573 }
5574 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005575 }
5576 totalNumBuffers += halRequest->num_output_buffers;
5577
5578 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005579 // If this request list is for constrained high speed recording (not
5580 // preview), and the current request is not the last one in the batch,
5581 // do not send callback to the app.
5582 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005583 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005584 hasCallback = false;
5585 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005586 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005587 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005588 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5589 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5590 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5591 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5592 isStillCapture = true;
5593 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5594 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005595
5596 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5597 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5598 isZslCapture = true;
5599 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005600 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005601 res = parent->registerInFlight(halRequest->frame_number,
5602 totalNumBuffers, captureRequest->mResultExtras,
5603 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005604 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005605 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005606 requestedPhysicalCameras, isStillCapture, isZslCapture,
5607 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5608 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005609 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5610 ", burstId = %" PRId32 ".",
5611 __FUNCTION__,
5612 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5613 captureRequest->mResultExtras.burstId);
5614 if (res != OK) {
5615 SET_ERR("RequestThread: Unable to register new in-flight request:"
5616 " %s (%d)", strerror(-res), res);
5617 return INVALID_OPERATION;
5618 }
5619 }
5620
5621 return OK;
5622}
5623
Igor Murashkin1e479c02013-09-06 16:55:14 -07005624CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005625 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005626 Mutex::Autolock al(mLatestRequestMutex);
5627
5628 ALOGV("RequestThread::%s", __FUNCTION__);
5629
5630 return mLatestRequest;
5631}
5632
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005633bool Camera3Device::RequestThread::isStreamPending(
5634 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005635 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005636 Mutex::Autolock l(mRequestLock);
5637
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005638 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005639 if (!nextRequest.submitted) {
5640 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5641 if (stream == s) return true;
5642 }
5643 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005644 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005645 }
5646
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005647 for (const auto& request : mRequestQueue) {
5648 for (const auto& s : request->mOutputStreams) {
5649 if (stream == s) return true;
5650 }
5651 if (stream == request->mInputStream) return true;
5652 }
5653
5654 for (const auto& request : mRepeatingRequests) {
5655 for (const auto& s : request->mOutputStreams) {
5656 if (stream == s) return true;
5657 }
5658 if (stream == request->mInputStream) return true;
5659 }
5660
5661 return false;
5662}
Jianing Weicb0652e2014-03-12 18:29:36 -07005663
Emilian Peev40ead602017-09-26 15:46:36 +01005664bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5665 ATRACE_CALL();
5666 Mutex::Autolock l(mRequestLock);
5667
5668 for (const auto& nextRequest : mNextRequests) {
5669 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5670 if (s.first == streamId) {
5671 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5672 if (it != s.second.end()) {
5673 return true;
5674 }
5675 }
5676 }
5677 }
5678
5679 for (const auto& request : mRequestQueue) {
5680 for (const auto& s : request->mOutputSurfaces) {
5681 if (s.first == streamId) {
5682 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5683 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005684 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005685 }
5686 }
5687 }
5688 }
5689
5690 for (const auto& request : mRepeatingRequests) {
5691 for (const auto& s : request->mOutputSurfaces) {
5692 if (s.first == streamId) {
5693 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5694 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005695 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005696 }
5697 }
5698 }
5699 }
5700
5701 return false;
5702}
5703
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005704void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5705 if (!mUseHalBufManager) {
5706 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5707 return;
5708 }
5709
5710 Mutex::Autolock pl(mPauseLock);
5711 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005712 mInterface->signalPipelineDrain(streamIds);
5713 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005714 }
5715 // If request thread is still busy, wait until paused then notify HAL
5716 mNotifyPipelineDrain = true;
5717 mStreamIdsToBeDrained = streamIds;
5718}
5719
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005720nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005721 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005722 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005723 return mExpectedInflightDuration > kMinInflightDuration ?
5724 mExpectedInflightDuration : kMinInflightDuration;
5725}
5726
Emilian Peevaebbe412018-01-15 13:53:24 +00005727void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5728 camera3_capture_request_t *halRequest) {
5729 if ((request == nullptr) || (halRequest == nullptr)) {
5730 ALOGE("%s: Invalid request!", __FUNCTION__);
5731 return;
5732 }
5733
5734 if (halRequest->num_physcam_settings > 0) {
5735 if (halRequest->physcam_id != nullptr) {
5736 delete [] halRequest->physcam_id;
5737 halRequest->physcam_id = nullptr;
5738 }
5739 if (halRequest->physcam_settings != nullptr) {
5740 auto it = ++(request->mSettingsList.begin());
5741 size_t i = 0;
5742 for (; it != request->mSettingsList.end(); it++, i++) {
5743 it->metadata.unlock(halRequest->physcam_settings[i]);
5744 }
5745 delete [] halRequest->physcam_settings;
5746 halRequest->physcam_settings = nullptr;
5747 }
5748 }
5749}
5750
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005751void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5752 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005753 return;
5754 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005755
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005756 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005757 // Skip the ones that have been submitted successfully.
5758 if (nextRequest.submitted) {
5759 continue;
5760 }
5761
5762 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5763 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5764 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5765
5766 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005767 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005768 }
5769
Emilian Peevaebbe412018-01-15 13:53:24 +00005770 cleanupPhysicalSettings(captureRequest, halRequest);
5771
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005772 if (captureRequest->mInputStream != NULL) {
5773 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5774 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5775 }
5776
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005777 // No output buffer can be returned when using HAL buffer manager
5778 if (!mUseHalBufManager) {
5779 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5780 //Buffers that failed processing could still have
5781 //valid acquire fence.
5782 int acquireFence = (*outputBuffers)[i].acquire_fence;
5783 if (0 <= acquireFence) {
5784 close(acquireFence);
5785 outputBuffers->editItemAt(i).acquire_fence = -1;
5786 }
5787 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5788 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5789 /*timestampIncreasing*/true, std::vector<size_t> (),
5790 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005791 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005792 }
5793
5794 if (sendRequestError) {
5795 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005796 sp<NotificationListener> listener = mListener.promote();
5797 if (listener != NULL) {
5798 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005799 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005800 captureRequest->mResultExtras);
5801 }
5802 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005803
5804 // Remove yet-to-be submitted inflight request from inflightMap
5805 {
5806 sp<Camera3Device> parent = mParent.promote();
5807 if (parent != NULL) {
5808 Mutex::Autolock l(parent->mInFlightLock);
5809 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5810 if (idx >= 0) {
5811 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5812 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5813 parent->removeInFlightMapEntryLocked(idx);
5814 }
5815 }
5816 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005817 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005818
5819 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005820 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005821}
5822
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005823void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005824 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005825 // Optimized a bit for the simple steady-state case (single repeating
5826 // request), to avoid putting that request in the queue temporarily.
5827 Mutex::Autolock l(mRequestLock);
5828
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005829 assert(mNextRequests.empty());
5830
5831 NextRequest nextRequest;
5832 nextRequest.captureRequest = waitForNextRequestLocked();
5833 if (nextRequest.captureRequest == nullptr) {
5834 return;
5835 }
5836
5837 nextRequest.halRequest = camera3_capture_request_t();
5838 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005839 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005840
5841 // Wait for additional requests
5842 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5843
5844 for (size_t i = 1; i < batchSize; i++) {
5845 NextRequest additionalRequest;
5846 additionalRequest.captureRequest = waitForNextRequestLocked();
5847 if (additionalRequest.captureRequest == nullptr) {
5848 break;
5849 }
5850
5851 additionalRequest.halRequest = camera3_capture_request_t();
5852 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005853 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005854 }
5855
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005856 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005857 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005858 mNextRequests.size(), batchSize);
5859 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005860 }
5861
5862 return;
5863}
5864
5865sp<Camera3Device::CaptureRequest>
5866 Camera3Device::RequestThread::waitForNextRequestLocked() {
5867 status_t res;
5868 sp<CaptureRequest> nextRequest;
5869
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005870 while (mRequestQueue.empty()) {
5871 if (!mRepeatingRequests.empty()) {
5872 // Always atomically enqueue all requests in a repeating request
5873 // list. Guarantees a complete in-sequence set of captures to
5874 // application.
5875 const RequestList &requests = mRepeatingRequests;
5876 RequestList::const_iterator firstRequest =
5877 requests.begin();
5878 nextRequest = *firstRequest;
5879 mRequestQueue.insert(mRequestQueue.end(),
5880 ++firstRequest,
5881 requests.end());
5882 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005883
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005884 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005885
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005886 break;
5887 }
5888
5889 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5890
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005891 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5892 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005893 Mutex::Autolock pl(mPauseLock);
5894 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005895 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005896 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005897 if (mNotifyPipelineDrain) {
5898 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5899 mNotifyPipelineDrain = false;
5900 mStreamIdsToBeDrained.clear();
5901 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005902 // Let the tracker know
5903 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5904 if (statusTracker != 0) {
5905 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5906 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005907 sp<Camera3Device> parent = mParent.promote();
5908 if (parent != nullptr) {
5909 parent->mRequestBufferSM.onRequestThreadPaused();
5910 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005911 }
5912 // Stop waiting for now and let thread management happen
5913 return NULL;
5914 }
5915 }
5916
5917 if (nextRequest == NULL) {
5918 // Don't have a repeating request already in hand, so queue
5919 // must have an entry now.
5920 RequestList::iterator firstRequest =
5921 mRequestQueue.begin();
5922 nextRequest = *firstRequest;
5923 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005924 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5925 sp<NotificationListener> listener = mListener.promote();
5926 if (listener != NULL) {
5927 listener->notifyRequestQueueEmpty();
5928 }
5929 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005930 }
5931
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005932 // In case we've been unpaused by setPaused clearing mDoPause, need to
5933 // update internal pause state (capture/setRepeatingRequest unpause
5934 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005935 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005936 if (mPaused) {
5937 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5938 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5939 if (statusTracker != 0) {
5940 statusTracker->markComponentActive(mStatusId);
5941 }
5942 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005943 mPaused = false;
5944
5945 // Check if we've reconfigured since last time, and reset the preview
5946 // request if so. Can't use 'NULL request == repeat' across configure calls.
5947 if (mReconfigured) {
5948 mPrevRequest.clear();
5949 mReconfigured = false;
5950 }
5951
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005952 if (nextRequest != NULL) {
5953 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005954 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5955 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005956
5957 // Since RequestThread::clear() removes buffers from the input stream,
5958 // get the right buffer here before unlocking mRequestLock
5959 if (nextRequest->mInputStream != NULL) {
5960 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5961 if (res != OK) {
5962 // Can't get input buffer from gralloc queue - this could be due to
5963 // disconnected queue or other producer misbehavior, so not a fatal
5964 // error
5965 ALOGE("%s: Can't get input buffer, skipping request:"
5966 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005967
5968 sp<NotificationListener> listener = mListener.promote();
5969 if (listener != NULL) {
5970 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005971 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005972 nextRequest->mResultExtras);
5973 }
5974 return NULL;
5975 }
5976 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005977 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005978
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005979 return nextRequest;
5980}
5981
5982bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005983 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005984 status_t res;
5985 Mutex::Autolock l(mPauseLock);
5986 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005987 if (mPaused == false) {
5988 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005989 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005990 if (mNotifyPipelineDrain) {
5991 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5992 mNotifyPipelineDrain = false;
5993 mStreamIdsToBeDrained.clear();
5994 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005995 // Let the tracker know
5996 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5997 if (statusTracker != 0) {
5998 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5999 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006000 sp<Camera3Device> parent = mParent.promote();
6001 if (parent != nullptr) {
6002 parent->mRequestBufferSM.onRequestThreadPaused();
6003 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006004 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006005
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006006 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006007 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006008 return true;
6009 }
6010 }
6011 // We don't set mPaused to false here, because waitForNextRequest needs
6012 // to further manage the paused state in case of starvation.
6013 return false;
6014}
6015
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006016void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006017 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006018 // With work to do, mark thread as unpaused.
6019 // If paused by request (setPaused), don't resume, to avoid
6020 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006021 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006022 Mutex::Autolock p(mPauseLock);
6023 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006024 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6025 if (mPaused) {
6026 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6027 if (statusTracker != 0) {
6028 statusTracker->markComponentActive(mStatusId);
6029 }
6030 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006031 mPaused = false;
6032 }
6033}
6034
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006035void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6036 sp<Camera3Device> parent = mParent.promote();
6037 if (parent != NULL) {
6038 va_list args;
6039 va_start(args, fmt);
6040
6041 parent->setErrorStateV(fmt, args);
6042
6043 va_end(args);
6044 }
6045}
6046
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006047status_t Camera3Device::RequestThread::insertTriggers(
6048 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006049 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006050 Mutex::Autolock al(mTriggerMutex);
6051
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006052 sp<Camera3Device> parent = mParent.promote();
6053 if (parent == NULL) {
6054 CLOGE("RequestThread: Parent is gone");
6055 return DEAD_OBJECT;
6056 }
6057
Emilian Peevaebbe412018-01-15 13:53:24 +00006058 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006059 size_t count = mTriggerMap.size();
6060
6061 for (size_t i = 0; i < count; ++i) {
6062 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006063 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006064
6065 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6066 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6067 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006068 if (isAeTrigger) {
6069 request->mResultExtras.precaptureTriggerId = triggerId;
6070 mCurrentPreCaptureTriggerId = triggerId;
6071 } else {
6072 request->mResultExtras.afTriggerId = triggerId;
6073 mCurrentAfTriggerId = triggerId;
6074 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006075 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006076 }
6077
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006078 camera_metadata_entry entry = metadata.find(tag);
6079
6080 if (entry.count > 0) {
6081 /**
6082 * Already has an entry for this trigger in the request.
6083 * Rewrite it with our requested trigger value.
6084 */
6085 RequestTrigger oldTrigger = trigger;
6086
6087 oldTrigger.entryValue = entry.data.u8[0];
6088
6089 mTriggerReplacedMap.add(tag, oldTrigger);
6090 } else {
6091 /**
6092 * More typical, no trigger entry, so we just add it
6093 */
6094 mTriggerRemovedMap.add(tag, trigger);
6095 }
6096
6097 status_t res;
6098
6099 switch (trigger.getTagType()) {
6100 case TYPE_BYTE: {
6101 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6102 res = metadata.update(tag,
6103 &entryValue,
6104 /*count*/1);
6105 break;
6106 }
6107 case TYPE_INT32:
6108 res = metadata.update(tag,
6109 &trigger.entryValue,
6110 /*count*/1);
6111 break;
6112 default:
6113 ALOGE("%s: Type not supported: 0x%x",
6114 __FUNCTION__,
6115 trigger.getTagType());
6116 return INVALID_OPERATION;
6117 }
6118
6119 if (res != OK) {
6120 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6121 ", value %d", __FUNCTION__, trigger.getTagName(),
6122 trigger.entryValue);
6123 return res;
6124 }
6125
6126 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6127 trigger.getTagName(),
6128 trigger.entryValue);
6129 }
6130
6131 mTriggerMap.clear();
6132
6133 return count;
6134}
6135
6136status_t Camera3Device::RequestThread::removeTriggers(
6137 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006138 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006139 Mutex::Autolock al(mTriggerMutex);
6140
Emilian Peevaebbe412018-01-15 13:53:24 +00006141 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006142
6143 /**
6144 * Replace all old entries with their old values.
6145 */
6146 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6147 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6148
6149 status_t res;
6150
6151 uint32_t tag = trigger.metadataTag;
6152 switch (trigger.getTagType()) {
6153 case TYPE_BYTE: {
6154 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6155 res = metadata.update(tag,
6156 &entryValue,
6157 /*count*/1);
6158 break;
6159 }
6160 case TYPE_INT32:
6161 res = metadata.update(tag,
6162 &trigger.entryValue,
6163 /*count*/1);
6164 break;
6165 default:
6166 ALOGE("%s: Type not supported: 0x%x",
6167 __FUNCTION__,
6168 trigger.getTagType());
6169 return INVALID_OPERATION;
6170 }
6171
6172 if (res != OK) {
6173 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6174 ", trigger value %d", __FUNCTION__,
6175 trigger.getTagName(), trigger.entryValue);
6176 return res;
6177 }
6178 }
6179 mTriggerReplacedMap.clear();
6180
6181 /**
6182 * Remove all new entries.
6183 */
6184 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6185 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6186 status_t res = metadata.erase(trigger.metadataTag);
6187
6188 if (res != OK) {
6189 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6190 ", trigger value %d", __FUNCTION__,
6191 trigger.getTagName(), trigger.entryValue);
6192 return res;
6193 }
6194 }
6195 mTriggerRemovedMap.clear();
6196
6197 return OK;
6198}
6199
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006200status_t Camera3Device::RequestThread::addDummyTriggerIds(
6201 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006202 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006203 static const int32_t dummyTriggerId = 1;
6204 status_t res;
6205
Emilian Peevaebbe412018-01-15 13:53:24 +00006206 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006207
6208 // If AF trigger is active, insert a dummy AF trigger ID if none already
6209 // exists
6210 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6211 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6212 if (afTrigger.count > 0 &&
6213 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6214 afId.count == 0) {
6215 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6216 if (res != OK) return res;
6217 }
6218
6219 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6220 // if none already exists
6221 camera_metadata_entry pcTrigger =
6222 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6223 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6224 if (pcTrigger.count > 0 &&
6225 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6226 pcId.count == 0) {
6227 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6228 &dummyTriggerId, 1);
6229 if (res != OK) return res;
6230 }
6231
6232 return OK;
6233}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006234
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006235/**
6236 * PreparerThread inner class methods
6237 */
6238
6239Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006240 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006241 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006242}
6243
6244Camera3Device::PreparerThread::~PreparerThread() {
6245 Thread::requestExitAndWait();
6246 if (mCurrentStream != nullptr) {
6247 mCurrentStream->cancelPrepare();
6248 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6249 mCurrentStream.clear();
6250 }
6251 clear();
6252}
6253
Ruben Brunkc78ac262015-08-13 17:58:46 -07006254status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006255 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006256 status_t res;
6257
6258 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006259 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006260
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006261 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006262 if (res == OK) {
6263 // No preparation needed, fire listener right off
6264 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006265 if (listener != NULL) {
6266 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006267 }
6268 return OK;
6269 } else if (res != NOT_ENOUGH_DATA) {
6270 return res;
6271 }
6272
6273 // Need to prepare, start up thread if necessary
6274 if (!mActive) {
6275 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6276 // isn't running
6277 Thread::requestExitAndWait();
6278 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6279 if (res != OK) {
6280 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006281 if (listener != NULL) {
6282 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006283 }
6284 return res;
6285 }
6286 mCancelNow = false;
6287 mActive = true;
6288 ALOGV("%s: Preparer stream started", __FUNCTION__);
6289 }
6290
6291 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006292 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006293 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6294
6295 return OK;
6296}
6297
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006298void Camera3Device::PreparerThread::pause() {
6299 ATRACE_CALL();
6300
6301 Mutex::Autolock l(mLock);
6302
6303 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6304 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6305 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6306 int currentMaxCount = mCurrentMaxCount;
6307 mPendingStreams.clear();
6308 mCancelNow = true;
6309 while (mActive) {
6310 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6311 if (res == TIMED_OUT) {
6312 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6313 return;
6314 } else if (res != OK) {
6315 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6316 return;
6317 }
6318 }
6319
6320 //Check whether the prepare thread was able to complete the current
6321 //stream. In case work is still pending emplace it along with the rest
6322 //of the streams in the pending list.
6323 if (currentStream != nullptr) {
6324 if (!mCurrentPrepareComplete) {
6325 pendingStreams.emplace(currentMaxCount, currentStream);
6326 }
6327 }
6328
6329 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6330 for (const auto& it : mPendingStreams) {
6331 it.second->cancelPrepare();
6332 }
6333}
6334
6335status_t Camera3Device::PreparerThread::resume() {
6336 ATRACE_CALL();
6337 status_t res;
6338
6339 Mutex::Autolock l(mLock);
6340 sp<NotificationListener> listener = mListener.promote();
6341
6342 if (mActive) {
6343 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6344 return NO_INIT;
6345 }
6346
6347 auto it = mPendingStreams.begin();
6348 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006349 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006350 if (res == OK) {
6351 if (listener != NULL) {
6352 listener->notifyPrepared(it->second->getId());
6353 }
6354 it = mPendingStreams.erase(it);
6355 } else if (res != NOT_ENOUGH_DATA) {
6356 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6357 res, strerror(-res));
6358 it = mPendingStreams.erase(it);
6359 } else {
6360 it++;
6361 }
6362 }
6363
6364 if (mPendingStreams.empty()) {
6365 return OK;
6366 }
6367
6368 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6369 if (res != OK) {
6370 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6371 __FUNCTION__, res, strerror(-res));
6372 return res;
6373 }
6374 mCancelNow = false;
6375 mActive = true;
6376 ALOGV("%s: Preparer stream started", __FUNCTION__);
6377
6378 return OK;
6379}
6380
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006381status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006382 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006383 Mutex::Autolock l(mLock);
6384
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006385 for (const auto& it : mPendingStreams) {
6386 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006387 }
6388 mPendingStreams.clear();
6389 mCancelNow = true;
6390
6391 return OK;
6392}
6393
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006394void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006395 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006396 Mutex::Autolock l(mLock);
6397 mListener = listener;
6398}
6399
6400bool Camera3Device::PreparerThread::threadLoop() {
6401 status_t res;
6402 {
6403 Mutex::Autolock l(mLock);
6404 if (mCurrentStream == nullptr) {
6405 // End thread if done with work
6406 if (mPendingStreams.empty()) {
6407 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6408 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6409 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6410 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006411 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006412 return false;
6413 }
6414
6415 // Get next stream to prepare
6416 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006417 mCurrentStream = it->second;
6418 mCurrentMaxCount = it->first;
6419 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006420 mPendingStreams.erase(it);
6421 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6422 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6423 } else if (mCancelNow) {
6424 mCurrentStream->cancelPrepare();
6425 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6426 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6427 mCurrentStream.clear();
6428 mCancelNow = false;
6429 return true;
6430 }
6431 }
6432
6433 res = mCurrentStream->prepareNextBuffer();
6434 if (res == NOT_ENOUGH_DATA) return true;
6435 if (res != OK) {
6436 // Something bad happened; try to recover by cancelling prepare and
6437 // signalling listener anyway
6438 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6439 mCurrentStream->getId(), res, strerror(-res));
6440 mCurrentStream->cancelPrepare();
6441 }
6442
6443 // This stream has finished, notify listener
6444 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006445 sp<NotificationListener> listener = mListener.promote();
6446 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006447 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6448 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006449 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006450 }
6451
6452 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6453 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006454 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006455
6456 return true;
6457}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006458
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006459status_t Camera3Device::RequestBufferStateMachine::initialize(
6460 sp<camera3::StatusTracker> statusTracker) {
6461 if (statusTracker == nullptr) {
6462 ALOGE("%s: statusTracker is null", __FUNCTION__);
6463 return BAD_VALUE;
6464 }
6465
6466 std::lock_guard<std::mutex> lock(mLock);
6467 mStatusTracker = statusTracker;
6468 mRequestBufferStatusId = statusTracker->addComponent();
6469 return OK;
6470}
6471
6472bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6473 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006474 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006475 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006476 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006477 return true;
6478 }
6479 return false;
6480}
6481
6482void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6483 std::lock_guard<std::mutex> lock(mLock);
6484 if (!mRequestBufferOngoing) {
6485 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6486 return;
6487 }
6488 mRequestBufferOngoing = false;
6489 if (mStatus == RB_STATUS_PENDING_STOP) {
6490 checkSwitchToStopLocked();
6491 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006492 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006493}
6494
6495void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6496 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006497 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006498 return;
6499}
6500
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006501void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006502 std::lock_guard<std::mutex> lock(mLock);
6503 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006504 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6505 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006506 mInflightMapEmpty = false;
6507 if (mStatus == RB_STATUS_STOPPED) {
6508 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006509 }
6510 return;
6511}
6512
6513void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6514 std::lock_guard<std::mutex> lock(mLock);
6515 mRequestThreadPaused = true;
6516 if (mStatus == RB_STATUS_PENDING_STOP) {
6517 checkSwitchToStopLocked();
6518 }
6519 return;
6520}
6521
6522void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6523 std::lock_guard<std::mutex> lock(mLock);
6524 mInflightMapEmpty = true;
6525 if (mStatus == RB_STATUS_PENDING_STOP) {
6526 checkSwitchToStopLocked();
6527 }
6528 return;
6529}
6530
6531void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6532 std::lock_guard<std::mutex> lock(mLock);
6533 if (!checkSwitchToStopLocked()) {
6534 mStatus = RB_STATUS_PENDING_STOP;
6535 }
6536 return;
6537}
6538
6539void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6540 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6541 if (statusTracker != nullptr) {
6542 if (active) {
6543 statusTracker->markComponentActive(mRequestBufferStatusId);
6544 } else {
6545 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6546 }
6547 }
6548}
6549
6550bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6551 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6552 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006553 return true;
6554 }
6555 return false;
6556}
6557
Shuzhen Wang268a1362018-10-16 16:32:59 -07006558status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6559 CameraMetadata& resultMetadata) {
6560 status_t res = OK;
6561 if (!mNeedFixupMonochromeTags) {
6562 return res;
6563 }
6564
6565 // Remove tags that are not applicable to monochrome camera.
6566 int32_t tagsToRemove[] = {
6567 ANDROID_SENSOR_GREEN_SPLIT,
6568 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6569 ANDROID_COLOR_CORRECTION_MODE,
6570 ANDROID_COLOR_CORRECTION_TRANSFORM,
6571 ANDROID_COLOR_CORRECTION_GAINS,
6572 };
6573 for (auto tag : tagsToRemove) {
6574 res = resultMetadata.erase(tag);
6575 if (res != OK) {
6576 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6577 return res;
6578 }
6579 }
6580
6581 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6582 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6583 for (size_t i = 1; i < blEntry.count; i++) {
6584 blEntry.data.f[i] = blEntry.data.f[0];
6585 }
6586
6587 // ANDROID_SENSOR_NOISE_PROFILE
6588 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6589 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6590 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6591 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6592 if (res != OK) {
6593 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6594 __FUNCTION__, strerror(-res), res);
6595 return res;
6596 }
6597 }
6598
6599 // ANDROID_STATISTICS_LENS_SHADING_MAP
6600 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6601 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6602 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6603 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6604 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6605 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6606 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6607 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6608 }
6609 }
6610
6611 // ANDROID_TONEMAP_CURVE_BLUE
6612 // ANDROID_TONEMAP_CURVE_GREEN
6613 // ANDROID_TONEMAP_CURVE_RED
6614 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6615 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6616 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6617 if (tcbEntry.count > 0
6618 && tcbEntry.count == tcgEntry.count
6619 && tcbEntry.count == tcrEntry.count) {
6620 for (size_t i = 0; i < tcbEntry.count; i++) {
6621 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6622 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6623 }
6624 }
6625
6626 return res;
6627}
6628
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006629}; // namespace android