blob: dfbff1803d7c6fe234a11b38725c6f79c6a31bbf [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
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002850 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002851 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2852 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002853 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2854 bufferSizes[k] = static_cast<uint32_t>(
2855 getJpegBufferSize(outputStream->width, outputStream->height));
2856 } else if (outputStream->data_space ==
2857 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2858 bufferSizes[k] = outputStream->width * outputStream->height;
2859 } else {
2860 ALOGW("%s: Blob dataSpace %d not supported",
2861 __FUNCTION__, outputStream->data_space);
2862 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002863 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002864 }
2865
2866 config.streams = streams.editArray();
2867
2868 // Do the HAL configuration; will potentially touch stream
2869 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002870
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002871 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002872 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002873 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002874
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002875 if (res == BAD_VALUE) {
2876 // HAL rejected this set of streams as unsupported, clean up config
2877 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002878 CLOGE("Set of requested inputs/outputs not supported by HAL");
2879 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002880 return BAD_VALUE;
2881 } else if (res != OK) {
2882 // Some other kind of error from configure_streams - this is not
2883 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002884 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2885 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002886 return res;
2887 }
2888
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002889 // Finish all stream configuration immediately.
2890 // TODO: Try to relax this later back to lazy completion, which should be
2891 // faster
2892
Igor Murashkin073f8572013-05-02 14:59:28 -07002893 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002894 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002895 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002896 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002897 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002898 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002899 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2900 return DEAD_OBJECT;
2901 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002902 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002903 }
2904 }
2905
2906 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002907 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002908 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002909 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002910 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002911 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002912 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002913 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002914 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2915 return DEAD_OBJECT;
2916 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002917 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002918 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002919 }
2920 }
2921
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002922 // Request thread needs to know to avoid using repeat-last-settings protocol
2923 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002924 if (notifyRequestThread) {
2925 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2926 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002927
Zhijun He90f7c372016-08-16 16:19:43 -07002928 char value[PROPERTY_VALUE_MAX];
2929 property_get("camera.fifo.disable", value, "0");
2930 int32_t disableFifo = atoi(value);
2931 if (disableFifo != 1) {
2932 // Boost priority of request thread to SCHED_FIFO.
2933 pid_t requestThreadTid = mRequestThread->getTid();
2934 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002935 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002936 if (res != OK) {
2937 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2938 strerror(-res), res);
2939 } else {
2940 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2941 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002942 }
2943
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002944 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002945 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2946 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2947 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2948 sessionParams.unlock(newSessionParams);
2949 mSessionParams.unlock(currentSessionParams);
2950 if (updateSessionParams) {
2951 mSessionParams = sessionParams;
2952 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002953
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002954 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002955
Ruben Brunk183f0562015-08-12 12:55:02 -07002956 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2957 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002958
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002959 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002960
Zhijun He0a210512014-07-24 13:45:15 -07002961 // tear down the deleted streams after configure streams.
2962 mDeletedStreams.clear();
2963
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002964 auto rc = mPreparerThread->resume();
2965 if (rc != OK) {
2966 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2967 return rc;
2968 }
2969
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002970 if (mDummyStreamId == NO_STREAM) {
2971 mRequestBufferSM.onStreamsConfigured();
2972 }
2973
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002974 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002975}
2976
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002977status_t Camera3Device::addDummyStreamLocked() {
2978 ATRACE_CALL();
2979 status_t res;
2980
2981 if (mDummyStreamId != NO_STREAM) {
2982 // Should never be adding a second dummy stream when one is already
2983 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002984 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2985 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002986 return INVALID_OPERATION;
2987 }
2988
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002989 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002990
2991 sp<Camera3OutputStreamInterface> dummyStream =
2992 new Camera3DummyStream(mNextStreamId);
2993
2994 res = mOutputStreams.add(mNextStreamId, dummyStream);
2995 if (res < 0) {
2996 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2997 return res;
2998 }
2999
3000 mDummyStreamId = mNextStreamId;
3001 mNextStreamId++;
3002
3003 return OK;
3004}
3005
3006status_t Camera3Device::tryRemoveDummyStreamLocked() {
3007 ATRACE_CALL();
3008 status_t res;
3009
3010 if (mDummyStreamId == NO_STREAM) return OK;
3011 if (mOutputStreams.size() == 1) return OK;
3012
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003013 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003014
3015 // Ok, have a dummy stream and there's at least one other output stream,
3016 // so remove the dummy
3017
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003018 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
3019 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003020 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3021 return INVALID_OPERATION;
3022 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003023 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003024
3025 // Free up the stream endpoint so that it can be used by some other stream
3026 res = deletedStream->disconnect();
3027 if (res != OK) {
3028 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3029 // fall through since we want to still list the stream as deleted.
3030 }
3031 mDeletedStreams.add(deletedStream);
3032 mDummyStreamId = NO_STREAM;
3033
3034 return res;
3035}
3036
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003037void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003038 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003039 Mutex::Autolock l(mLock);
3040 va_list args;
3041 va_start(args, fmt);
3042
3043 setErrorStateLockedV(fmt, args);
3044
3045 va_end(args);
3046}
3047
3048void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003049 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003050 Mutex::Autolock l(mLock);
3051 setErrorStateLockedV(fmt, args);
3052}
3053
3054void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3055 va_list args;
3056 va_start(args, fmt);
3057
3058 setErrorStateLockedV(fmt, args);
3059
3060 va_end(args);
3061}
3062
3063void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003064 // Print out all error messages to log
3065 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003066 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003067
3068 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003069 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003070
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003071 mErrorCause = errorCause;
3072
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003073 if (mRequestThread != nullptr) {
3074 mRequestThread->setPaused(true);
3075 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003076 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003077
3078 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003079 sp<NotificationListener> listener = mListener.promote();
3080 if (listener != NULL) {
3081 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003082 CaptureResultExtras());
3083 }
3084
3085 // Save stack trace. View by dumping it later.
3086 CameraTraces::saveTrace();
3087 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003088}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003089
3090/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003091 * In-flight request management
3092 */
3093
Jianing Weicb0652e2014-03-12 18:29:36 -07003094status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003095 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003096 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003097 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003098 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003099 ATRACE_CALL();
3100 Mutex::Autolock l(mInFlightLock);
3101
3102 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003103 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003104 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3105 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003106 if (res < 0) return res;
3107
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003108 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003109 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3110 // avoid a deadlock during reprocess requests.
3111 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003112 if (mStatusTracker != nullptr) {
3113 mStatusTracker->markComponentActive(mInFlightStatusId);
3114 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003115 }
3116
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003117 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003118 return OK;
3119}
3120
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003121void Camera3Device::returnOutputBuffers(
3122 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003123 nsecs_t timestamp, bool timestampIncreasing,
3124 const SurfaceMap& outputSurfaces,
3125 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003126
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003127 for (size_t i = 0; i < numBuffers; i++)
3128 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003129 if (outputBuffers[i].buffer == nullptr) {
3130 if (!mUseHalBufManager) {
3131 // With HAL buffer management API, HAL sometimes will have to return buffers that
3132 // has not got a output buffer handle filled yet. This is though illegal if HAL
3133 // buffer management API is not being used.
3134 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3135 }
3136 continue;
3137 }
3138
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003139 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3140 int streamId = stream->getId();
3141 const auto& it = outputSurfaces.find(streamId);
3142 status_t res = OK;
3143 if (it != outputSurfaces.end()) {
3144 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003145 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3146 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003147 } else {
3148 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003149 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3150 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003151 }
3152
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003153 // Note: stream may be deallocated at this point, if this buffer was
3154 // the last reference to it.
3155 if (res != OK) {
3156 ALOGE("Can't return buffer to its stream: %s (%d)",
3157 strerror(-res), res);
3158 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003159
3160 // Long processing consumers can cause returnBuffer timeout for shared stream
3161 // If that happens, cancel the buffer and send a buffer error to client
3162 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3163 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3164 // cancel the buffer
3165 camera3_stream_buffer_t sb = outputBuffers[i];
3166 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003167 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3168 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003169
3170 // notify client buffer error
3171 sp<NotificationListener> listener;
3172 {
3173 Mutex::Autolock l(mOutputLock);
3174 listener = mListener.promote();
3175 }
3176
3177 if (listener != nullptr) {
3178 CaptureResultExtras extras = inResultExtras;
3179 extras.errorStreamId = streamId;
3180 listener->notifyError(
3181 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3182 extras);
3183 }
3184 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003185 }
3186}
3187
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003188void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003189 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003190 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003191 mInFlightMap.removeItemsAt(idx, 1);
3192
3193 // Indicate idle inFlightMap to the status tracker
3194 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003195 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003196 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3197 // avoid a deadlock during reprocess requests.
3198 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003199 if (mStatusTracker != nullptr) {
3200 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3201 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003202 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003203 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003204}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003205
3206void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3207
3208 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3209 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3210
3211 nsecs_t sensorTimestamp = request.sensorTimestamp;
3212 nsecs_t shutterTimestamp = request.shutterTimestamp;
3213
3214 // Check if it's okay to remove the request from InFlightMap:
3215 // In the case of a successful request:
3216 // all input and output buffers, all result metadata, shutter callback
3217 // arrived.
3218 // In the case of a unsuccessful request:
3219 // all input and output buffers arrived.
3220 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003221 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003222 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003223 if (request.stillCapture) {
3224 ATRACE_ASYNC_END("still capture", frameNumber);
3225 }
3226
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003227 ATRACE_ASYNC_END("frame capture", frameNumber);
3228
Shuzhen Wang403044a2017-02-26 23:29:04 -08003229 // Sanity check - if sensor timestamp matches shutter timestamp in the
3230 // case of request having callback.
3231 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003232 sensorTimestamp != shutterTimestamp) {
3233 SET_ERR("sensor timestamp (%" PRId64
3234 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3235 sensorTimestamp, frameNumber, shutterTimestamp);
3236 }
3237
3238 // for an unsuccessful request, it may have pending output buffers to
3239 // return.
3240 assert(request.requestStatus != OK ||
3241 request.pendingOutputBuffers.size() == 0);
3242 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003243 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3244 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003245
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003246 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003247 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3248 }
3249
3250 // Sanity check - if we have too many in-flight frames, something has
3251 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003252 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003253 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003254 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3255 kInFlightWarnLimitHighSpeed) {
3256 CLOGE("In-flight list too large for high speed configuration: %zu",
3257 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003258 }
3259}
3260
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003261void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003262 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003263 { // First return buffers cached in mInFlightMap
3264 Mutex::Autolock l(mInFlightLock);
3265 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3266 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3267 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003268 request.pendingOutputBuffers.size(), 0,
3269 /*timestampIncreasing*/true, request.outputSurfaces,
3270 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003271 }
3272 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003273 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003274 }
3275
3276 // Then return all inflight buffers not returned by HAL
3277 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3278 mInterface->getInflightBufferKeys(&inflightKeys);
3279
3280 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3281 for (auto& pair : inflightKeys) {
3282 int32_t frameNumber = pair.first;
3283 int32_t streamId = pair.second;
3284 buffer_handle_t* buffer;
3285 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3286 if (res != OK) {
3287 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3288 __FUNCTION__, frameNumber, streamId);
3289 continue;
3290 }
3291
3292 camera3_stream_buffer_t streamBuffer;
3293 streamBuffer.buffer = buffer;
3294 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3295 streamBuffer.acquire_fence = -1;
3296 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003297
3298 // First check if the buffer belongs to deleted stream
3299 bool streamDeleted = false;
3300 for (auto& stream : mDeletedStreams) {
3301 if (streamId == stream->getId()) {
3302 streamDeleted = true;
3303 // Return buffer to deleted stream
3304 camera3_stream* halStream = stream->asHalStream();
3305 streamBuffer.stream = halStream;
3306 switch (halStream->stream_type) {
3307 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003308 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3309 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003310 if (res != OK) {
3311 ALOGE("%s: Can't return output buffer for frame %d to"
3312 " stream %d: %s (%d)", __FUNCTION__,
3313 frameNumber, streamId, strerror(-res), res);
3314 }
3315 break;
3316 case CAMERA3_STREAM_INPUT:
3317 res = stream->returnInputBuffer(streamBuffer);
3318 if (res != OK) {
3319 ALOGE("%s: Can't return input buffer for frame %d to"
3320 " stream %d: %s (%d)", __FUNCTION__,
3321 frameNumber, streamId, strerror(-res), res);
3322 }
3323 break;
3324 default: // Bi-direcitonal stream is deprecated
3325 ALOGE("%s: stream %d has unknown stream type %d",
3326 __FUNCTION__, streamId, halStream->stream_type);
3327 break;
3328 }
3329 break;
3330 }
3331 }
3332 if (streamDeleted) {
3333 continue;
3334 }
3335
3336 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003337 if (streamId == inputStreamId) {
3338 streamBuffer.stream = mInputStream->asHalStream();
3339 res = mInputStream->returnInputBuffer(streamBuffer);
3340 if (res != OK) {
3341 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003342 " stream %d: %s (%d)", __FUNCTION__,
3343 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003344 }
3345 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003346 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3347 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003348 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3349 continue;
3350 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003351 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003352 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3353 }
3354 }
3355}
3356
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003357void Camera3Device::insertResultLocked(CaptureResult *result,
3358 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003359 if (result == nullptr) return;
3360
Emilian Peev71c73a22017-03-21 16:35:51 +00003361 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3362 result->mMetadata.getAndLock());
3363 set_camera_metadata_vendor_id(meta, mVendorTagId);
3364 result->mMetadata.unlock(meta);
3365
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003366 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3367 (int32_t*)&frameNumber, 1) != OK) {
3368 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3369 return;
3370 }
3371
3372 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3373 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3374 return;
3375 }
3376
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003377 // Valid result, insert into queue
3378 List<CaptureResult>::iterator queuedResult =
3379 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3380 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3381 ", burstId = %" PRId32, __FUNCTION__,
3382 queuedResult->mResultExtras.requestId,
3383 queuedResult->mResultExtras.frameNumber,
3384 queuedResult->mResultExtras.burstId);
3385
3386 mResultSignal.signal();
3387}
3388
3389
3390void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003391 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003392 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003393 Mutex::Autolock l(mOutputLock);
3394
3395 CaptureResult captureResult;
3396 captureResult.mResultExtras = resultExtras;
3397 captureResult.mMetadata = partialResult;
3398
Shuzhen Wang268a1362018-10-16 16:32:59 -07003399 // Fix up result metadata for monochrome camera.
3400 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3401 if (res != OK) {
3402 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3403 return;
3404 }
3405
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003406 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003407}
3408
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003409
3410void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3411 CaptureResultExtras &resultExtras,
3412 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003413 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003414 bool reprocess,
3415 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003416 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003417 if (pendingMetadata.isEmpty())
3418 return;
3419
3420 Mutex::Autolock l(mOutputLock);
3421
3422 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003423 if (reprocess) {
3424 if (frameNumber < mNextReprocessResultFrameNumber) {
3425 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003426 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003427 frameNumber, mNextReprocessResultFrameNumber);
3428 return;
3429 }
3430 mNextReprocessResultFrameNumber = frameNumber + 1;
3431 } else {
3432 if (frameNumber < mNextResultFrameNumber) {
3433 SET_ERR("Out-of-order capture result metadata submitted! "
3434 "(got frame number %d, expecting %d)",
3435 frameNumber, mNextResultFrameNumber);
3436 return;
3437 }
3438 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003439 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003440
3441 CaptureResult captureResult;
3442 captureResult.mResultExtras = resultExtras;
3443 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003444 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003445
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003446 // Append any previous partials to form a complete result
3447 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3448 captureResult.mMetadata.append(collectedPartialResult);
3449 }
3450
3451 captureResult.mMetadata.sort();
3452
3453 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003454 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3455 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003456 SET_ERR("No timestamp provided by HAL for frame %d!",
3457 frameNumber);
3458 return;
3459 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003460 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3461 camera_metadata_entry timestamp =
3462 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3463 if (timestamp.count == 0) {
3464 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3465 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3466 return;
3467 }
3468 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003469
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003470 // Fix up some result metadata to account for HAL-level distortion correction
3471 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3472 if (res != OK) {
3473 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3474 frameNumber, strerror(res), res);
3475 return;
3476 }
Shuzhen Wang268a1362018-10-16 16:32:59 -07003477 // Fix up result metadata for monochrome camera.
3478 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3479 if (res != OK) {
3480 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3481 return;
3482 }
3483 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3484 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3485 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3486 physicalMetadata.mPhysicalCameraMetadata);
3487 if (res != OK) {
3488 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3489 return;
3490 }
3491 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003492
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003493 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3494 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3495
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003496 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003497}
3498
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003499/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003500 * Camera HAL device callback methods
3501 */
3502
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003503void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003504 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003505
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003506 status_t res;
3507
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003508 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003509 if (result->result == NULL && result->num_output_buffers == 0 &&
3510 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003511 SET_ERR("No result data provided by HAL for frame %d",
3512 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003513 return;
3514 }
Zhijun He204e3292014-07-14 17:09:23 -07003515
Zhijun He204e3292014-07-14 17:09:23 -07003516 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003517 result->result != NULL &&
3518 result->partial_result != 1) {
3519 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3520 " if partial result is not supported",
3521 frameNumber, result->partial_result);
3522 return;
3523 }
3524
3525 bool isPartialResult = false;
3526 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003527 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003528
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003529 // Get shutter timestamp and resultExtras from list of in-flight requests,
3530 // where it was added by the shutter notification for this frame. If the
3531 // shutter timestamp isn't received yet, append the output buffers to the
3532 // in-flight request and they will be returned when the shutter timestamp
3533 // arrives. Update the in-flight status and remove the in-flight entry if
3534 // all result data and shutter timestamp have been received.
3535 nsecs_t shutterTimestamp = 0;
3536
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003537 {
3538 Mutex::Autolock l(mInFlightLock);
3539 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3540 if (idx == NAME_NOT_FOUND) {
3541 SET_ERR("Unknown frame number for capture result: %d",
3542 frameNumber);
3543 return;
3544 }
3545 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003546 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3547 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003548 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003549 __FUNCTION__, request.resultExtras.requestId,
3550 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003551 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003552 // Always update the partial count to the latest one if it's not 0
3553 // (buffers only). When framework aggregates adjacent partial results
3554 // into one, the latest partial count will be used.
3555 if (result->partial_result != 0)
3556 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003557
3558 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003559 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003560 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3561 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3562 " the range of [1, %d] when metadata is included in the result",
3563 frameNumber, result->partial_result, mNumPartialResults);
3564 return;
3565 }
3566 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003567 if (isPartialResult && result->num_physcam_metadata) {
3568 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3569 " physical camera result", frameNumber);
3570 return;
3571 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003572 if (isPartialResult) {
3573 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003574 }
3575
Shuzhen Wang4a472662017-02-26 23:29:04 -08003576 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003577 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003578 sendPartialCaptureResult(result->result, request.resultExtras,
3579 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003580 }
3581 }
3582
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003583 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003584 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003585
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003586 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003587 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003588 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3589 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3590 request.physicalCameraIds.size(), result->num_physcam_metadata);
3591 return;
3592 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003593 if (request.haveResultMetadata) {
3594 SET_ERR("Called multiple times with metadata for frame %d",
3595 frameNumber);
3596 return;
3597 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003598 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3599 String8 physicalId(result->physcam_ids[i]);
3600 std::set<String8>::iterator cameraIdIter =
3601 request.physicalCameraIds.find(physicalId);
3602 if (cameraIdIter != request.physicalCameraIds.end()) {
3603 request.physicalCameraIds.erase(cameraIdIter);
3604 } else {
3605 SET_ERR("Total result for frame %d has already returned for camera %s",
3606 frameNumber, physicalId.c_str());
3607 return;
3608 }
3609 }
Zhijun He204e3292014-07-14 17:09:23 -07003610 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003611 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003612 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003613 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003614 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003615 request.haveResultMetadata = true;
3616 }
3617
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003618 uint32_t numBuffersReturned = result->num_output_buffers;
3619 if (result->input_buffer != NULL) {
3620 if (hasInputBufferInRequest) {
3621 numBuffersReturned += 1;
3622 } else {
3623 ALOGW("%s: Input buffer should be NULL if there is no input"
3624 " buffer sent in the request",
3625 __FUNCTION__);
3626 }
3627 }
3628 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003629 if (request.numBuffersLeft < 0) {
3630 SET_ERR("Too many buffers returned for frame %d",
3631 frameNumber);
3632 return;
3633 }
3634
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003635 camera_metadata_ro_entry_t entry;
3636 res = find_camera_metadata_ro_entry(result->result,
3637 ANDROID_SENSOR_TIMESTAMP, &entry);
3638 if (res == OK && entry.count == 1) {
3639 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003640 }
3641
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003642 // If shutter event isn't received yet, append the output buffers to
3643 // the in-flight request. Otherwise, return the output buffers to
3644 // streams.
3645 if (shutterTimestamp == 0) {
3646 request.pendingOutputBuffers.appendArray(result->output_buffers,
3647 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003648 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003649 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003650 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003651 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3652 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003653 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003654
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003655 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003656 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3657 CameraMetadata physicalMetadata;
3658 physicalMetadata.append(result->physcam_metadata[i]);
3659 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3660 physicalMetadata});
3661 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003662 if (shutterTimestamp == 0) {
3663 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003664 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003665 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003666 CameraMetadata metadata;
3667 metadata = result->result;
3668 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003669 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003670 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003671 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003672 }
3673
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003674 removeInFlightRequestIfReadyLocked(idx);
3675 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003676
Zhijun Hef0d962a2014-06-30 10:24:11 -07003677 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003678 if (hasInputBufferInRequest) {
3679 Camera3Stream *stream =
3680 Camera3Stream::cast(result->input_buffer->stream);
3681 res = stream->returnInputBuffer(*(result->input_buffer));
3682 // Note: stream may be deallocated at this point, if this buffer was the
3683 // last reference to it.
3684 if (res != OK) {
3685 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3686 " its stream:%s (%d)", __FUNCTION__,
3687 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003688 }
3689 } else {
3690 ALOGW("%s: Input buffer should be NULL if there is no input"
3691 " buffer sent in the request, skipping input buffer return.",
3692 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003693 }
3694 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003695}
3696
3697void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003698 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003699 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003700 {
3701 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003702 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003703 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003704
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003705 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003706 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003707 return;
3708 }
3709
3710 switch (msg->type) {
3711 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003712 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003713 break;
3714 }
3715 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003716 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003717 break;
3718 }
3719 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003720 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003721 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003722 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003723}
3724
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003725void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003726 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003727 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003728 // Map camera HAL error codes to ICameraDeviceCallback error codes
3729 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003730 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003731 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003732 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003733 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003734 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003735 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003736 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003737 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003738 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003739 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003740 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003741 };
3742
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003743 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003744 ((msg.error_code >= 0) &&
3745 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3746 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003747 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003748
3749 int streamId = 0;
3750 if (msg.error_stream != NULL) {
3751 Camera3Stream *stream =
3752 Camera3Stream::cast(msg.error_stream);
3753 streamId = stream->getId();
3754 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003755 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3756 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003757 streamId, msg.error_code);
3758
3759 CaptureResultExtras resultExtras;
3760 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003761 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003762 // SET_ERR calls notifyError
3763 SET_ERR("Camera HAL reported serious device error");
3764 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003765 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3766 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3767 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003768 {
3769 Mutex::Autolock l(mInFlightLock);
3770 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3771 if (idx >= 0) {
3772 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3773 r.requestStatus = msg.error_code;
3774 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003775 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3776 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3777 errorCode) {
3778 r.skipResultMetadata = true;
3779 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003780 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3781 errorCode) {
3782 // In case of missing result check whether the buffers
3783 // returned. If they returned, then remove inflight
3784 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003785 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3786 // otherwise we are depending on HAL to send the buffers back after
3787 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003788 removeInFlightRequestIfReadyLocked(idx);
3789 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003790 } else {
3791 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003792 ALOGE("Camera %s: %s: cannot find in-flight request on "
3793 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003794 resultExtras.frameNumber);
3795 }
3796 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003797 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003798 if (listener != NULL) {
3799 listener->notifyError(errorCode, resultExtras);
3800 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003801 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003802 }
3803 break;
3804 default:
3805 // SET_ERR calls notifyError
3806 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3807 break;
3808 }
3809}
3810
3811void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003812 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003813 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003814 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003815
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003816 // Set timestamp for the request in the in-flight tracking
3817 // and get the request ID to send upstream
3818 {
3819 Mutex::Autolock l(mInFlightLock);
3820 idx = mInFlightMap.indexOfKey(msg.frame_number);
3821 if (idx >= 0) {
3822 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003823
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003824 // Verify ordering of shutter notifications
3825 {
3826 Mutex::Autolock l(mOutputLock);
3827 // TODO: need to track errors for tighter bounds on expected frame number.
3828 if (r.hasInputBuffer) {
3829 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3830 SET_ERR("Shutter notification out-of-order. Expected "
3831 "notification for frame %d, got frame %d",
3832 mNextReprocessShutterFrameNumber, msg.frame_number);
3833 return;
3834 }
3835 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3836 } else {
3837 if (msg.frame_number < mNextShutterFrameNumber) {
3838 SET_ERR("Shutter notification out-of-order. Expected "
3839 "notification for frame %d, got frame %d",
3840 mNextShutterFrameNumber, msg.frame_number);
3841 return;
3842 }
3843 mNextShutterFrameNumber = msg.frame_number + 1;
3844 }
3845 }
3846
Shuzhen Wang4a472662017-02-26 23:29:04 -08003847 r.shutterTimestamp = msg.timestamp;
3848 if (r.hasCallback) {
3849 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003850 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003851 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003852 // Call listener, if any
3853 if (listener != NULL) {
3854 listener->notifyShutter(r.resultExtras, msg.timestamp);
3855 }
3856 // send pending result and buffers
3857 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3858 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003859 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003860 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003861 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003862 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003863 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3864 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003865 r.pendingOutputBuffers.clear();
3866
3867 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003868 }
3869 }
3870 if (idx < 0) {
3871 SET_ERR("Shutter notification for non-existent frame number %d",
3872 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003873 }
3874}
3875
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003876CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003877 ALOGV("%s", __FUNCTION__);
3878
Igor Murashkin1e479c02013-09-06 16:55:14 -07003879 CameraMetadata retVal;
3880
3881 if (mRequestThread != NULL) {
3882 retVal = mRequestThread->getLatestRequest();
3883 }
3884
Igor Murashkin1e479c02013-09-06 16:55:14 -07003885 return retVal;
3886}
3887
Jianing Weicb0652e2014-03-12 18:29:36 -07003888
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003889void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3890 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3891 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3892}
3893
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003894/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003895 * HalInterface inner class methods
3896 */
3897
Yifan Hongf79b5542017-04-11 14:44:25 -07003898Camera3Device::HalInterface::HalInterface(
3899 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003900 std::shared_ptr<RequestMetadataQueue> queue,
3901 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003902 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003903 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003904 mUseHalBufManager(useHalBufManager),
3905 mIsReconfigurationQuerySupported(true) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003906 // Check with hardware service manager if we can downcast these interfaces
3907 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003908 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3909 if (castResult_3_5.isOk()) {
3910 mHidlSession_3_5 = castResult_3_5;
3911 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003912 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3913 if (castResult_3_4.isOk()) {
3914 mHidlSession_3_4 = castResult_3_4;
3915 }
3916 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3917 if (castResult_3_3.isOk()) {
3918 mHidlSession_3_3 = castResult_3_3;
3919 }
3920}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003921
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003922Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003923
3924Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003925 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003926 mRequestMetadataQueue(other.mRequestMetadataQueue),
3927 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003928
3929bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003930 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003931}
3932
3933void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00003934 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003935 mHidlSession_3_4.clear();
3936 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003937 mHidlSession.clear();
3938}
3939
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003940bool Camera3Device::HalInterface::supportBatchRequest() {
3941 return mHidlSession != nullptr;
3942}
3943
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003944status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3945 camera3_request_template_t templateId,
3946 /*out*/ camera_metadata_t **requestTemplate) {
3947 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3948 if (!valid()) return INVALID_OPERATION;
3949 status_t res = OK;
3950
Emilian Peev31abd0a2017-05-11 18:37:46 +01003951 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003952
3953 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003954 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003955 status = s;
3956 if (status == common::V1_0::Status::OK) {
3957 const camera_metadata *r =
3958 reinterpret_cast<const camera_metadata_t*>(request.data());
3959 size_t expectedSize = request.size();
3960 int ret = validate_camera_metadata_structure(r, &expectedSize);
3961 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3962 *requestTemplate = clone_camera_metadata(r);
3963 if (*requestTemplate == nullptr) {
3964 ALOGE("%s: Unable to clone camera metadata received from HAL",
3965 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003966 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003967 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003968 } else {
3969 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3970 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003971 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003972 }
3973 };
3974 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003975 RequestTemplate id;
3976 switch (templateId) {
3977 case CAMERA3_TEMPLATE_PREVIEW:
3978 id = RequestTemplate::PREVIEW;
3979 break;
3980 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3981 id = RequestTemplate::STILL_CAPTURE;
3982 break;
3983 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3984 id = RequestTemplate::VIDEO_RECORD;
3985 break;
3986 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3987 id = RequestTemplate::VIDEO_SNAPSHOT;
3988 break;
3989 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3990 id = RequestTemplate::ZERO_SHUTTER_LAG;
3991 break;
3992 case CAMERA3_TEMPLATE_MANUAL:
3993 id = RequestTemplate::MANUAL;
3994 break;
3995 default:
3996 // Unknown template ID, or this HAL is too old to support it
3997 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003998 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003999 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004000
Emilian Peev31abd0a2017-05-11 18:37:46 +01004001 if (!err.isOk()) {
4002 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4003 res = DEAD_OBJECT;
4004 } else {
4005 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004006 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004007
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004008 return res;
4009}
4010
Emilian Peev4ec17882019-01-24 17:16:58 -08004011bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4012 CameraMetadata& newSessionParams) {
4013 // We do reconfiguration by default;
4014 bool ret = true;
4015 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4016 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4017 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4018 oldSessionParams.getAndLock());
4019 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4020 newSessionParams.getAndLock());
4021 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4022 get_camera_metadata_size(oldSessioMeta));
4023 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4024 get_camera_metadata_size(newSessioMeta));
4025 hardware::camera::common::V1_0::Status callStatus;
4026 bool required;
4027 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4028 bool requiredFlag) {
4029 callStatus = s;
4030 required = requiredFlag;
4031 };
4032 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4033 oldSessionParams.unlock(oldSessioMeta);
4034 newSessionParams.unlock(newSessioMeta);
4035 if (err.isOk()) {
4036 switch (callStatus) {
4037 case hardware::camera::common::V1_0::Status::OK:
4038 ret = required;
4039 break;
4040 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4041 mIsReconfigurationQuerySupported = false;
4042 ret = true;
4043 break;
4044 default:
4045 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4046 ret = true;
4047 }
4048 } else {
4049 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4050 ret = true;
4051 }
4052 }
4053
4054 return ret;
4055}
4056
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004057status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004058 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004059 ATRACE_NAME("CameraHal::configureStreams");
4060 if (!valid()) return INVALID_OPERATION;
4061 status_t res = OK;
4062
Emilian Peev31abd0a2017-05-11 18:37:46 +01004063 // Convert stream config to HIDL
4064 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004065 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4066 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4067 requestedConfiguration3_2.streams.resize(config->num_streams);
4068 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004069 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004070 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4071 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004072 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004073
Emilian Peev31abd0a2017-05-11 18:37:46 +01004074 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4075 cam3stream->setBufferFreedListener(this);
4076 int streamId = cam3stream->getId();
4077 StreamType streamType;
4078 switch (src->stream_type) {
4079 case CAMERA3_STREAM_OUTPUT:
4080 streamType = StreamType::OUTPUT;
4081 break;
4082 case CAMERA3_STREAM_INPUT:
4083 streamType = StreamType::INPUT;
4084 break;
4085 default:
4086 ALOGE("%s: Stream %d: Unsupported stream type %d",
4087 __FUNCTION__, streamId, config->streams[i]->stream_type);
4088 return BAD_VALUE;
4089 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004090 dst3_2.id = streamId;
4091 dst3_2.streamType = streamType;
4092 dst3_2.width = src->width;
4093 dst3_2.height = src->height;
4094 dst3_2.format = mapToPixelFormat(src->format);
4095 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
4096 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4097 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
4098 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004099 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004100 if (src->physical_camera_id != nullptr) {
4101 dst3_4.physicalCameraId = src->physical_camera_id;
4102 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004103
4104 activeStreams.insert(streamId);
4105 // Create Buffer ID map if necessary
4106 if (mBufferIdMaps.count(streamId) == 0) {
4107 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4108 }
4109 }
4110 // remove BufferIdMap for deleted streams
4111 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4112 int streamId = it->first;
4113 bool active = activeStreams.count(streamId) > 0;
4114 if (!active) {
4115 it = mBufferIdMaps.erase(it);
4116 } else {
4117 ++it;
4118 }
4119 }
4120
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004121 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004122 res = mapToStreamConfigurationMode(
4123 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004124 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004125 if (res != OK) {
4126 return res;
4127 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004128 requestedConfiguration3_2.operationMode = operationMode;
4129 requestedConfiguration3_4.operationMode = operationMode;
4130 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004131 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4132 get_camera_metadata_size(sessionParams));
4133
Emilian Peev31abd0a2017-05-11 18:37:46 +01004134 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004135 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004136 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004137 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004138
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004139 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004140 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4141 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004142 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004143 };
4144
4145 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4146 (hardware::Return<void>& err) -> status_t {
4147 if (!err.isOk()) {
4148 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4149 return DEAD_OBJECT;
4150 }
4151 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4152 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4153 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4154 }
4155 return OK;
4156 };
4157
4158 // See if we have v3.4 or v3.3 HAL
4159 if (mHidlSession_3_5 != nullptr) {
4160 ALOGV("%s: v3.5 device found", __FUNCTION__);
4161 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4162 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4163 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4164 auto err = mHidlSession_3_5->configureStreams_3_5(
4165 requestedConfiguration3_5, configStream34Cb);
4166 res = postprocConfigStream34(err);
4167 if (res != OK) {
4168 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004169 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004170 } else if (mHidlSession_3_4 != nullptr) {
4171 // We do; use v3.4 for the call
4172 ALOGV("%s: v3.4 device found", __FUNCTION__);
4173 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
4174 auto err = mHidlSession_3_4->configureStreams_3_4(
4175 requestedConfiguration3_4, configStream34Cb);
4176 res = postprocConfigStream34(err);
4177 if (res != OK) {
4178 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004179 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004180 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004181 // We do; use v3.3 for the call
4182 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004183 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004184 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004185 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004186 finalConfiguration = halConfiguration;
4187 status = s;
4188 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004189 if (!err.isOk()) {
4190 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4191 return DEAD_OBJECT;
4192 }
4193 } else {
4194 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4195 ALOGV("%s: v3.2 device found", __FUNCTION__);
4196 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004197 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004198 [&status, &finalConfiguration_3_2]
4199 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4200 finalConfiguration_3_2 = halConfiguration;
4201 status = s;
4202 });
4203 if (!err.isOk()) {
4204 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4205 return DEAD_OBJECT;
4206 }
4207 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4208 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4209 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4210 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004211 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004212 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004213 }
4214
4215 if (status != common::V1_0::Status::OK ) {
4216 return CameraProviderManager::mapToStatusT(status);
4217 }
4218
4219 // And convert output stream configuration from HIDL
4220
4221 for (size_t i = 0; i < config->num_streams; i++) {
4222 camera3_stream_t *dst = config->streams[i];
4223 int streamId = Camera3Stream::cast(dst)->getId();
4224
4225 // Start scan at i, with the assumption that the stream order matches
4226 size_t realIdx = i;
4227 bool found = false;
4228 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004229 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004230 found = true;
4231 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004232 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004233 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4234 }
4235 if (!found) {
4236 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4237 __FUNCTION__, streamId);
4238 return INVALID_OPERATION;
4239 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004240 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004241
Emilian Peev710c1422017-08-30 11:19:38 +01004242 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4243 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004244 dstStream->setDataSpaceOverride(false);
4245 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4246 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4247
Emilian Peev31abd0a2017-05-11 18:37:46 +01004248 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4249 if (dst->format != overrideFormat) {
4250 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4251 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004252 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004253 if (dst->data_space != overrideDataSpace) {
4254 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4255 streamId, dst->format);
4256 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004257 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004258 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004259 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4260
Emilian Peev31abd0a2017-05-11 18:37:46 +01004261 // Override allowed with IMPLEMENTATION_DEFINED
4262 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004263 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004264 }
4265
Emilian Peev31abd0a2017-05-11 18:37:46 +01004266 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004267 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004268 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004269 __FUNCTION__, streamId);
4270 return INVALID_OPERATION;
4271 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004272 dstStream->setUsage(
4273 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004274 } else {
4275 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004276 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004277 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4278 __FUNCTION__, streamId);
4279 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004280 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004281 dstStream->setUsage(
4282 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004283 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004284 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004285 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004286
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004287 return res;
4288}
4289
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004290status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004291 /*out*/device::V3_2::CaptureRequest* captureRequest,
4292 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004293 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004294 if (captureRequest == nullptr || handlesCreated == nullptr) {
4295 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4296 __FUNCTION__, captureRequest, handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004297 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004298 }
4299
4300 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004301
4302 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004303
4304 {
4305 std::lock_guard<std::mutex> lock(mInflightLock);
4306 if (request->input_buffer != nullptr) {
4307 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4308 buffer_handle_t buf = *(request->input_buffer->buffer);
4309 auto pair = getBufferId(buf, streamId);
4310 bool isNewBuffer = pair.first;
4311 uint64_t bufferId = pair.second;
4312 captureRequest->inputBuffer.streamId = streamId;
4313 captureRequest->inputBuffer.bufferId = bufferId;
4314 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4315 captureRequest->inputBuffer.status = BufferStatus::OK;
4316 native_handle_t *acquireFence = nullptr;
4317 if (request->input_buffer->acquire_fence != -1) {
4318 acquireFence = native_handle_create(1,0);
4319 acquireFence->data[0] = request->input_buffer->acquire_fence;
4320 handlesCreated->push_back(acquireFence);
4321 }
4322 captureRequest->inputBuffer.acquireFence = acquireFence;
4323 captureRequest->inputBuffer.releaseFence = nullptr;
4324
4325 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4326 request->input_buffer->buffer,
4327 request->input_buffer->acquire_fence);
4328 } else {
4329 captureRequest->inputBuffer.streamId = -1;
4330 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4331 }
4332
4333 captureRequest->outputBuffers.resize(request->num_output_buffers);
4334 for (size_t i = 0; i < request->num_output_buffers; i++) {
4335 const camera3_stream_buffer_t *src = request->output_buffers + i;
4336 StreamBuffer &dst = captureRequest->outputBuffers[i];
4337 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004338 if (src->buffer != nullptr) {
4339 buffer_handle_t buf = *(src->buffer);
4340 auto pair = getBufferId(buf, streamId);
4341 bool isNewBuffer = pair.first;
4342 dst.bufferId = pair.second;
4343 dst.buffer = isNewBuffer ? buf : nullptr;
4344 native_handle_t *acquireFence = nullptr;
4345 if (src->acquire_fence != -1) {
4346 acquireFence = native_handle_create(1,0);
4347 acquireFence->data[0] = src->acquire_fence;
4348 handlesCreated->push_back(acquireFence);
4349 }
4350 dst.acquireFence = acquireFence;
4351 } else if (mUseHalBufManager) {
4352 // HAL buffer management path
4353 dst.bufferId = BUFFER_ID_NO_BUFFER;
4354 dst.buffer = nullptr;
4355 dst.acquireFence = nullptr;
4356 } else {
4357 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4358 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004359 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004360 dst.streamId = streamId;
4361 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004362 dst.releaseFence = nullptr;
4363
4364 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4365 src->buffer, src->acquire_fence);
4366 }
4367 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004368 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004369}
4370
4371status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4372 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4373 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4374 if (!valid()) return INVALID_OPERATION;
4375
Emilian Peevaebbe412018-01-15 13:53:24 +00004376 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4377 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4378 if (castResult_3_4.isOk()) {
4379 hidlSession_3_4 = castResult_3_4;
4380 }
4381
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004382 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004383 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004384 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004385 if (hidlSession_3_4 != nullptr) {
4386 captureRequests_3_4.resize(batchSize);
4387 } else {
4388 captureRequests.resize(batchSize);
4389 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004390 std::vector<native_handle_t*> handlesCreated;
4391
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004392 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004393 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004394 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004395 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Emilian Peevaebbe412018-01-15 13:53:24 +00004396 /*out*/&handlesCreated);
4397 } else {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004398 res = wrapAsHidlRequest(requests[i],
4399 /*out*/&captureRequests[i], /*out*/&handlesCreated);
4400 }
4401 if (res != OK) {
4402 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004403 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004404 }
4405
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004406 std::vector<device::V3_2::BufferCache> cachesToRemove;
4407 {
4408 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4409 for (auto& pair : mFreedBuffers) {
4410 // The stream might have been removed since onBufferFreed
4411 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4412 cachesToRemove.push_back({pair.first, pair.second});
4413 }
4414 }
4415 mFreedBuffers.clear();
4416 }
4417
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004418 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4419 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004420
4421 // Write metadata to FMQ.
4422 for (size_t i = 0; i < batchSize; i++) {
4423 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004424 device::V3_2::CaptureRequest* captureRequest;
4425 if (hidlSession_3_4 != nullptr) {
4426 captureRequest = &captureRequests_3_4[i].v3_2;
4427 } else {
4428 captureRequest = &captureRequests[i];
4429 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004430
4431 if (request->settings != nullptr) {
4432 size_t settingsSize = get_camera_metadata_size(request->settings);
4433 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4434 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4435 captureRequest->settings.resize(0);
4436 captureRequest->fmqSettingsSize = settingsSize;
4437 } else {
4438 if (mRequestMetadataQueue != nullptr) {
4439 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4440 }
4441 captureRequest->settings.setToExternal(
4442 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4443 get_camera_metadata_size(request->settings));
4444 captureRequest->fmqSettingsSize = 0u;
4445 }
4446 } else {
4447 // A null request settings maps to a size-0 CameraMetadata
4448 captureRequest->settings.resize(0);
4449 captureRequest->fmqSettingsSize = 0u;
4450 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004451
4452 if (hidlSession_3_4 != nullptr) {
4453 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4454 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004455 if (request->physcam_settings != nullptr) {
4456 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4457 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4458 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4459 settingsSize)) {
4460 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4461 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4462 settingsSize;
4463 } else {
4464 if (mRequestMetadataQueue != nullptr) {
4465 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4466 }
4467 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4468 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4469 request->physcam_settings[j])),
4470 get_camera_metadata_size(request->physcam_settings[j]));
4471 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004472 }
Emilian Peev00420d22018-02-05 21:33:13 +00004473 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004474 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004475 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004476 }
4477 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4478 request->physcam_id[j];
4479 }
4480 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004481 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004482
4483 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004484 auto resultCallback =
4485 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4486 status = s;
4487 *numRequestProcessed = n;
4488 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004489 if (hidlSession_3_4 != nullptr) {
4490 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004491 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004492 } else {
4493 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004494 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004495 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004496 if (!err.isOk()) {
4497 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4498 return DEAD_OBJECT;
4499 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004500 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4501 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4502 __FUNCTION__, *numRequestProcessed, batchSize);
4503 status = common::V1_0::Status::INTERNAL_ERROR;
4504 }
4505
4506 for (auto& handle : handlesCreated) {
4507 native_handle_delete(handle);
4508 }
4509 return CameraProviderManager::mapToStatusT(status);
4510}
4511
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004512status_t Camera3Device::HalInterface::processCaptureRequest(
4513 camera3_capture_request_t *request) {
4514 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004515 if (!valid()) return INVALID_OPERATION;
4516 status_t res = OK;
4517
Emilian Peev31abd0a2017-05-11 18:37:46 +01004518 uint32_t numRequestProcessed = 0;
4519 std::vector<camera3_capture_request_t*> requests(1);
4520 requests[0] = request;
4521 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4522
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004523 return res;
4524}
4525
4526status_t Camera3Device::HalInterface::flush() {
4527 ATRACE_NAME("CameraHal::flush");
4528 if (!valid()) return INVALID_OPERATION;
4529 status_t res = OK;
4530
Emilian Peev31abd0a2017-05-11 18:37:46 +01004531 auto err = mHidlSession->flush();
4532 if (!err.isOk()) {
4533 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4534 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004535 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004536 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004537 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004538
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004539 return res;
4540}
4541
Emilian Peev31abd0a2017-05-11 18:37:46 +01004542status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004543 ATRACE_NAME("CameraHal::dump");
4544 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004545
Emilian Peev31abd0a2017-05-11 18:37:46 +01004546 // Handled by CameraProviderManager::dump
4547
4548 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004549}
4550
4551status_t Camera3Device::HalInterface::close() {
4552 ATRACE_NAME("CameraHal::close()");
4553 if (!valid()) return INVALID_OPERATION;
4554 status_t res = OK;
4555
Emilian Peev31abd0a2017-05-11 18:37:46 +01004556 auto err = mHidlSession->close();
4557 // Interface will be dead shortly anyway, so don't log errors
4558 if (!err.isOk()) {
4559 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004560 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004561
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004562 return res;
4563}
4564
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004565void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4566 ATRACE_NAME("CameraHal::signalPipelineDrain");
4567 if (!valid() || mHidlSession_3_5 == nullptr) {
4568 ALOGE("%s called on invalid camera!", __FUNCTION__);
4569 return;
4570 }
4571
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004572 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004573 if (!err.isOk()) {
4574 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4575 return;
4576 }
4577}
4578
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004579void Camera3Device::HalInterface::getInflightBufferKeys(
4580 std::vector<std::pair<int32_t, int32_t>>* out) {
4581 std::lock_guard<std::mutex> lock(mInflightLock);
4582 out->clear();
4583 out->reserve(mInflightBufferMap.size());
4584 for (auto& pair : mInflightBufferMap) {
4585 uint64_t key = pair.first;
4586 int32_t streamId = key & 0xFFFFFFFF;
4587 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4588 out->push_back(std::make_pair(frameNumber, streamId));
4589 }
4590 return;
4591}
4592
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004593status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004594 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004595 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004596 auto pair = std::make_pair(buffer, acquireFence);
4597 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004598 return OK;
4599}
4600
4601status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004602 int32_t frameNumber, int32_t streamId,
4603 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004604 std::lock_guard<std::mutex> lock(mInflightLock);
4605
4606 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4607 auto it = mInflightBufferMap.find(key);
4608 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004609 auto pair = it->second;
4610 *buffer = pair.first;
4611 int acquireFence = pair.second;
4612 if (acquireFence > 0) {
4613 ::close(acquireFence);
4614 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004615 mInflightBufferMap.erase(it);
4616 return OK;
4617}
4618
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004619status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4620 uint64_t bufferId, buffer_handle_t* buf) {
4621 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4622 auto pair = mRequestedBuffers.insert({bufferId, buf});
4623 if (!pair.second) {
4624 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4625 __FUNCTION__, bufferId);
4626 return BAD_VALUE;
4627 }
4628 return OK;
4629}
4630
4631// Find and pop a buffer_handle_t based on bufferId
4632status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4633 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4634 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4635 auto it = mRequestedBuffers.find(bufferId);
4636 if (it == mRequestedBuffers.end()) {
4637 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4638 __FUNCTION__, bufferId);
4639 return BAD_VALUE;
4640 }
4641 *buffer = it->second;
4642 mRequestedBuffers.erase(it);
4643 return OK;
4644}
4645
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004646std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4647 const buffer_handle_t& buf, int streamId) {
4648 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4649
4650 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4651 auto it = bIdMap.find(buf);
4652 if (it == bIdMap.end()) {
4653 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004654 ALOGV("stream %d now have %zu buffer caches, buf %p",
4655 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004656 return std::make_pair(true, mNextBufferId - 1);
4657 } else {
4658 return std::make_pair(false, it->second);
4659 }
4660}
4661
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004662void Camera3Device::HalInterface::onBufferFreed(
4663 int streamId, const native_handle_t* handle) {
4664 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4665 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4666 auto mapIt = mBufferIdMaps.find(streamId);
4667 if (mapIt == mBufferIdMaps.end()) {
4668 // streamId might be from a deleted stream here
4669 ALOGI("%s: stream %d has been removed",
4670 __FUNCTION__, streamId);
4671 return;
4672 }
4673 BufferIdMap& bIdMap = mapIt->second;
4674 auto it = bIdMap.find(handle);
4675 if (it == bIdMap.end()) {
4676 ALOGW("%s: cannot find buffer %p in stream %d",
4677 __FUNCTION__, handle, streamId);
4678 return;
4679 } else {
4680 bufferId = it->second;
4681 bIdMap.erase(it);
4682 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4683 __FUNCTION__, streamId, bIdMap.size(), handle);
4684 }
4685 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4686}
4687
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004688/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004689 * RequestThread inner class methods
4690 */
4691
4692Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004693 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004694 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4695 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004696 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004697 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004698 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004699 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004700 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004701 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004702 mReconfigured(false),
4703 mDoPause(false),
4704 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004705 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004706 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004707 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004708 mCurrentAfTriggerId(0),
4709 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004710 mRepeatingLastFrameNumber(
4711 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004712 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004713 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004714 mRequestLatency(kRequestLatencyBinSize),
4715 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004716 mLatestSessionParams(sessionParamKeys.size()),
4717 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004718 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004719}
4720
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004721Camera3Device::RequestThread::~RequestThread() {}
4722
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004723void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004724 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004725 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004726 Mutex::Autolock l(mRequestLock);
4727 mListener = listener;
4728}
4729
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004730void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4731 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004732 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004733 Mutex::Autolock l(mRequestLock);
4734 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004735 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004736 // Prepare video stream for high speed recording.
4737 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004738 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004739}
4740
Jianing Wei90e59c92014-03-12 18:29:36 -07004741status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004742 List<sp<CaptureRequest> > &requests,
4743 /*out*/
4744 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004745 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004746 Mutex::Autolock l(mRequestLock);
4747 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4748 ++it) {
4749 mRequestQueue.push_back(*it);
4750 }
4751
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004752 if (lastFrameNumber != NULL) {
4753 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4754 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4755 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4756 *lastFrameNumber);
4757 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004758
Jianing Wei90e59c92014-03-12 18:29:36 -07004759 unpauseForNewRequests();
4760
4761 return OK;
4762}
4763
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004764
4765status_t Camera3Device::RequestThread::queueTrigger(
4766 RequestTrigger trigger[],
4767 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004768 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004769 Mutex::Autolock l(mTriggerMutex);
4770 status_t ret;
4771
4772 for (size_t i = 0; i < count; ++i) {
4773 ret = queueTriggerLocked(trigger[i]);
4774
4775 if (ret != OK) {
4776 return ret;
4777 }
4778 }
4779
4780 return OK;
4781}
4782
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004783const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4784 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004785 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004786 if (d != nullptr) return d->mId;
4787 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004788}
4789
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004790status_t Camera3Device::RequestThread::queueTriggerLocked(
4791 RequestTrigger trigger) {
4792
4793 uint32_t tag = trigger.metadataTag;
4794 ssize_t index = mTriggerMap.indexOfKey(tag);
4795
4796 switch (trigger.getTagType()) {
4797 case TYPE_BYTE:
4798 // fall-through
4799 case TYPE_INT32:
4800 break;
4801 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004802 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4803 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004804 return INVALID_OPERATION;
4805 }
4806
4807 /**
4808 * Collect only the latest trigger, since we only have 1 field
4809 * in the request settings per trigger tag, and can't send more than 1
4810 * trigger per request.
4811 */
4812 if (index != NAME_NOT_FOUND) {
4813 mTriggerMap.editValueAt(index) = trigger;
4814 } else {
4815 mTriggerMap.add(tag, trigger);
4816 }
4817
4818 return OK;
4819}
4820
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004821status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004822 const RequestList &requests,
4823 /*out*/
4824 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004825 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004826 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004827 if (lastFrameNumber != NULL) {
4828 *lastFrameNumber = mRepeatingLastFrameNumber;
4829 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004830 mRepeatingRequests.clear();
4831 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4832 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004833
4834 unpauseForNewRequests();
4835
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004836 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004837 return OK;
4838}
4839
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004840bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004841 if (mRepeatingRequests.empty()) {
4842 return false;
4843 }
4844 int32_t requestId = requestIn->mResultExtras.requestId;
4845 const RequestList &repeatRequests = mRepeatingRequests;
4846 // All repeating requests are guaranteed to have same id so only check first quest
4847 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4848 return (firstRequest->mResultExtras.requestId == requestId);
4849}
4850
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004851status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004852 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004853 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004854 return clearRepeatingRequestsLocked(lastFrameNumber);
4855
4856}
4857
4858status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004859 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004860 if (lastFrameNumber != NULL) {
4861 *lastFrameNumber = mRepeatingLastFrameNumber;
4862 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004863 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004864 return OK;
4865}
4866
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004867status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004868 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004869 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004870 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004871 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004872
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004873 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004874
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004875 // Send errors for all requests pending in the request queue, including
4876 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004877 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004878 if (listener != NULL) {
4879 for (RequestList::iterator it = mRequestQueue.begin();
4880 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004881 // Abort the input buffers for reprocess requests.
4882 if ((*it)->mInputStream != NULL) {
4883 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004884 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4885 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004886 if (res != OK) {
4887 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4888 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4889 } else {
4890 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4891 if (res != OK) {
4892 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4893 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4894 }
4895 }
4896 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004897 // Set the frame number this request would have had, if it
4898 // had been submitted; this frame number will not be reused.
4899 // The requestId and burstId fields were set when the request was
4900 // submitted originally (in convertMetadataListToRequestListLocked)
4901 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004902 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004903 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004904 }
4905 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004906 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004907
4908 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004909 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004910 if (lastFrameNumber != NULL) {
4911 *lastFrameNumber = mRepeatingLastFrameNumber;
4912 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004913 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004914 return OK;
4915}
4916
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004917status_t Camera3Device::RequestThread::flush() {
4918 ATRACE_CALL();
4919 Mutex::Autolock l(mFlushLock);
4920
Emilian Peev08dd2452017-04-06 16:55:14 +01004921 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004922}
4923
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004924void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004925 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004926 Mutex::Autolock l(mPauseLock);
4927 mDoPause = paused;
4928 mDoPauseSignal.signal();
4929}
4930
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004931status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4932 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004933 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004934 Mutex::Autolock l(mLatestRequestMutex);
4935 status_t res;
4936 while (mLatestRequestId != requestId) {
4937 nsecs_t startTime = systemTime();
4938
4939 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4940 if (res != OK) return res;
4941
4942 timeout -= (systemTime() - startTime);
4943 }
4944
4945 return OK;
4946}
4947
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004948void Camera3Device::RequestThread::requestExit() {
4949 // Call parent to set up shutdown
4950 Thread::requestExit();
4951 // The exit from any possible waits
4952 mDoPauseSignal.signal();
4953 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004954
4955 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4956 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004957}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004958
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004959void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004960 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004961 bool surfaceAbandoned = false;
4962 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004963 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004964 {
4965 Mutex::Autolock l(mRequestLock);
4966 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4967 // repeating requests.
4968 for (const auto& request : mRepeatingRequests) {
4969 for (const auto& s : request->mOutputStreams) {
4970 if (s->isAbandoned()) {
4971 surfaceAbandoned = true;
4972 clearRepeatingRequestsLocked(&lastFrameNumber);
4973 break;
4974 }
4975 }
4976 if (surfaceAbandoned) {
4977 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004978 }
4979 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004980 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004981 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004982
4983 if (listener != NULL && surfaceAbandoned) {
4984 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004985 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004986}
4987
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004988bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004989 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004990 status_t res;
4991 size_t batchSize = mNextRequests.size();
4992 std::vector<camera3_capture_request_t*> requests(batchSize);
4993 uint32_t numRequestProcessed = 0;
4994 for (size_t i = 0; i < batchSize; i++) {
4995 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004996 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004997 }
4998
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004999 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
5000
5001 bool triggerRemoveFailed = false;
5002 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
5003 for (size_t i = 0; i < numRequestProcessed; i++) {
5004 NextRequest& nextRequest = mNextRequests.editItemAt(i);
5005 nextRequest.submitted = true;
5006
5007
5008 // Update the latest request sent to HAL
5009 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5010 Mutex::Autolock al(mLatestRequestMutex);
5011
5012 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5013 mLatestRequest.acquire(cloned);
5014
5015 sp<Camera3Device> parent = mParent.promote();
5016 if (parent != NULL) {
5017 parent->monitorMetadata(TagMonitor::REQUEST,
5018 nextRequest.halRequest.frame_number,
5019 0, mLatestRequest);
5020 }
5021 }
5022
5023 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005024 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5025 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005026 }
5027
Emilian Peevaebbe412018-01-15 13:53:24 +00005028 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5029
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005030 if (!triggerRemoveFailed) {
5031 // Remove any previously queued triggers (after unlock)
5032 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5033 if (removeTriggerRes != OK) {
5034 triggerRemoveFailed = true;
5035 triggerFailedRequest = nextRequest;
5036 }
5037 }
5038 }
5039
5040 if (triggerRemoveFailed) {
5041 SET_ERR("RequestThread: Unable to remove triggers "
5042 "(capture request %d, HAL device: %s (%d)",
5043 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5044 cleanUpFailedRequests(/*sendRequestError*/ false);
5045 return false;
5046 }
5047
5048 if (res != OK) {
5049 // Should only get a failure here for malformed requests or device-level
5050 // errors, so consider all errors fatal. Bad metadata failures should
5051 // come through notify.
5052 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5053 mNextRequests[numRequestProcessed].halRequest.frame_number,
5054 strerror(-res), res);
5055 cleanUpFailedRequests(/*sendRequestError*/ false);
5056 return false;
5057 }
5058 return true;
5059}
5060
5061bool Camera3Device::RequestThread::sendRequestsOneByOne() {
5062 status_t res;
5063
5064 for (auto& nextRequest : mNextRequests) {
5065 // Submit request and block until ready for next one
5066 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
5067 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
5068
5069 if (res != OK) {
5070 // Should only get a failure here for malformed requests or device-level
5071 // errors, so consider all errors fatal. Bad metadata failures should
5072 // come through notify.
5073 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
5074 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
5075 res);
5076 cleanUpFailedRequests(/*sendRequestError*/ false);
5077 return false;
5078 }
5079
5080 // Mark that the request has be submitted successfully.
5081 nextRequest.submitted = true;
5082
5083 // Update the latest request sent to HAL
5084 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5085 Mutex::Autolock al(mLatestRequestMutex);
5086
5087 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5088 mLatestRequest.acquire(cloned);
5089
5090 sp<Camera3Device> parent = mParent.promote();
5091 if (parent != NULL) {
5092 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
5093 0, mLatestRequest);
5094 }
5095 }
5096
5097 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005098 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5099 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005100 }
5101
Emilian Peevaebbe412018-01-15 13:53:24 +00005102 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5103
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005104 // Remove any previously queued triggers (after unlock)
5105 res = removeTriggers(mPrevRequest);
5106 if (res != OK) {
5107 SET_ERR("RequestThread: Unable to remove triggers "
5108 "(capture request %d, HAL device: %s (%d)",
5109 nextRequest.halRequest.frame_number, strerror(-res), res);
5110 cleanUpFailedRequests(/*sendRequestError*/ false);
5111 return false;
5112 }
5113 }
5114 return true;
5115}
5116
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005117nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5118 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5119 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5120 find_camera_metadata_ro_entry(request,
5121 ANDROID_CONTROL_AE_MODE,
5122 &e);
5123 if (e.count == 0) return maxExpectedDuration;
5124
5125 switch (e.data.u8[0]) {
5126 case ANDROID_CONTROL_AE_MODE_OFF:
5127 find_camera_metadata_ro_entry(request,
5128 ANDROID_SENSOR_EXPOSURE_TIME,
5129 &e);
5130 if (e.count > 0) {
5131 maxExpectedDuration = e.data.i64[0];
5132 }
5133 find_camera_metadata_ro_entry(request,
5134 ANDROID_SENSOR_FRAME_DURATION,
5135 &e);
5136 if (e.count > 0) {
5137 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5138 }
5139 break;
5140 default:
5141 find_camera_metadata_ro_entry(request,
5142 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5143 &e);
5144 if (e.count > 1) {
5145 maxExpectedDuration = 1e9 / e.data.u8[0];
5146 }
5147 break;
5148 }
5149
5150 return maxExpectedDuration;
5151}
5152
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005153bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5154 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5155 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5156 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5157 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5158 return true;
5159 }
5160
5161 return false;
5162}
5163
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005164bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5165 ATRACE_CALL();
5166 bool updatesDetected = false;
5167
Emilian Peev4ec17882019-01-24 17:16:58 -08005168 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005169 for (auto tag : mSessionParamKeys) {
5170 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005171 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005172
5173 if (entry.count > 0) {
5174 bool isDifferent = false;
5175 if (lastEntry.count > 0) {
5176 // Have a last value, compare to see if changed
5177 if (lastEntry.type == entry.type &&
5178 lastEntry.count == entry.count) {
5179 // Same type and count, compare values
5180 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5181 size_t entryBytes = bytesPerValue * lastEntry.count;
5182 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5183 if (cmp != 0) {
5184 isDifferent = true;
5185 }
5186 } else {
5187 // Count or type has changed
5188 isDifferent = true;
5189 }
5190 } else {
5191 // No last entry, so always consider to be different
5192 isDifferent = true;
5193 }
5194
5195 if (isDifferent) {
5196 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005197 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5198 updatesDetected = true;
5199 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005200 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005201 }
5202 } else if (lastEntry.count > 0) {
5203 // Value has been removed
5204 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005205 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005206 updatesDetected = true;
5207 }
5208 }
5209
Emilian Peev4ec17882019-01-24 17:16:58 -08005210 bool reconfigureRequired;
5211 if (updatesDetected) {
5212 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5213 updatedParams);
5214 mLatestSessionParams = updatedParams;
5215 } else {
5216 reconfigureRequired = false;
5217 }
5218
5219 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005220}
5221
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005222bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005223 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005224 status_t res;
5225
5226 // Handle paused state.
5227 if (waitIfPaused()) {
5228 return true;
5229 }
5230
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005231 // Wait for the next batch of requests.
5232 waitForNextRequestBatch();
5233 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005234 return true;
5235 }
5236
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005237 // Get the latest request ID, if any
5238 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005239 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005240 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005241 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005242 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005243 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005244 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5245 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005246 }
5247
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005248 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5249 // or a single request from streaming or burst. In either case the first element
5250 // should contain the latest camera settings that we need to check for any session
5251 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005252 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005253 res = OK;
5254
5255 //Input stream buffers are already acquired at this point so an input stream
5256 //will not be able to move to idle state unless we force it.
5257 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5258 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5259 if (res != OK) {
5260 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5261 cleanUpFailedRequests(/*sendRequestError*/ false);
5262 return false;
5263 }
5264 }
5265
5266 if (res == OK) {
5267 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5268 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005269 sp<Camera3Device> parent = mParent.promote();
5270 if (parent != nullptr) {
5271 parent->pauseStateNotify(true);
5272 }
5273
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005274 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5275
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005276 if (parent != nullptr) {
5277 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5278 }
5279
5280 statusTracker->markComponentActive(mStatusId);
5281 setPaused(false);
5282 }
5283
5284 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5285 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5286 if (res != OK) {
5287 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5288 cleanUpFailedRequests(/*sendRequestError*/ false);
5289 return false;
5290 }
5291 }
5292 }
5293 }
5294
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005295 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005296 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005297 if (res == TIMED_OUT) {
5298 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005299 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005300 // Check if any stream is abandoned.
5301 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005302 return true;
5303 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005304 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005305 return false;
5306 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005307
Zhijun Hecc27e112013-10-03 16:12:43 -07005308 // Inform waitUntilRequestProcessed thread of a new request ID
5309 {
5310 Mutex::Autolock al(mLatestRequestMutex);
5311
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005312 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005313 mLatestRequestSignal.signal();
5314 }
5315
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005316 // Submit a batch of requests to HAL.
5317 // Use flush lock only when submitting multilple requests in a batch.
5318 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5319 // which may take a long time to finish so synchronizing flush() and
5320 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5321 // For now, only synchronize for high speed recording and we should figure something out for
5322 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005323 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005324
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005325 if (useFlushLock) {
5326 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005327 }
5328
Zhijun Hef0645c12016-08-02 00:58:11 -07005329 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005330 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005331
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005332 sp<Camera3Device> parent = mParent.promote();
5333 if (parent != nullptr) {
5334 parent->mRequestBufferSM.onSubmittingRequest();
5335 }
5336
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005337 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005338 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005339 if (mInterface->supportBatchRequest()) {
5340 submitRequestSuccess = sendRequestsBatch();
5341 } else {
5342 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005343 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005344 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5345 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005346
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005347 if (useFlushLock) {
5348 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005349 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005350
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005351 // Unset as current request
5352 {
5353 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005354 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005355 }
5356
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005357 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005358}
5359
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005360status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005361 ATRACE_CALL();
5362
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005363 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005364 for (size_t i = 0; i < mNextRequests.size(); i++) {
5365 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005366 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5367 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5368 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5369
5370 // Prepare a request to HAL
5371 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5372
5373 // Insert any queued triggers (before metadata is locked)
5374 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005375 if (res < 0) {
5376 SET_ERR("RequestThread: Unable to insert triggers "
5377 "(capture request %d, HAL device: %s (%d)",
5378 halRequest->frame_number, strerror(-res), res);
5379 return INVALID_OPERATION;
5380 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005381
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005382 int triggerCount = res;
5383 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5384 mPrevTriggers = triggerCount;
5385
5386 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005387 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5388 // Request settings are all the same within one batch, so only treat the first
5389 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005390 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005391 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005392 /**
5393 * HAL workaround:
5394 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5395 */
5396 res = addDummyTriggerIds(captureRequest);
5397 if (res != OK) {
5398 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5399 "(capture request %d, HAL device: %s (%d)",
5400 halRequest->frame_number, strerror(-res), res);
5401 return INVALID_OPERATION;
5402 }
5403
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005404 {
5405 // Correct metadata regions for distortion correction if enabled
5406 sp<Camera3Device> parent = mParent.promote();
5407 if (parent != nullptr) {
5408 res = parent->mDistortionMapper.correctCaptureRequest(
5409 &(captureRequest->mSettingsList.begin()->metadata));
5410 if (res != OK) {
5411 SET_ERR("RequestThread: Unable to correct capture requests "
5412 "for lens distortion for request %d: %s (%d)",
5413 halRequest->frame_number, strerror(-res), res);
5414 return INVALID_OPERATION;
5415 }
5416 }
5417 }
5418
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005419 /**
5420 * The request should be presorted so accesses in HAL
5421 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5422 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005423 captureRequest->mSettingsList.begin()->metadata.sort();
5424 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005425 mPrevRequest = captureRequest;
5426 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5427
5428 IF_ALOGV() {
5429 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5430 find_camera_metadata_ro_entry(
5431 halRequest->settings,
5432 ANDROID_CONTROL_AF_TRIGGER,
5433 &e
5434 );
5435 if (e.count > 0) {
5436 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5437 __FUNCTION__,
5438 halRequest->frame_number,
5439 e.data.u8[0]);
5440 }
5441 }
5442 } else {
5443 // leave request.settings NULL to indicate 'reuse latest given'
5444 ALOGVV("%s: Request settings are REUSED",
5445 __FUNCTION__);
5446 }
5447
Emilian Peevaebbe412018-01-15 13:53:24 +00005448 if (captureRequest->mSettingsList.size() > 1) {
5449 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5450 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005451 if (newRequest) {
5452 halRequest->physcam_settings =
5453 new const camera_metadata* [halRequest->num_physcam_settings];
5454 } else {
5455 halRequest->physcam_settings = nullptr;
5456 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005457 auto it = ++captureRequest->mSettingsList.begin();
5458 size_t i = 0;
5459 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5460 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005461 if (newRequest) {
5462 it->metadata.sort();
5463 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5464 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005465 }
5466 }
5467
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005468 uint32_t totalNumBuffers = 0;
5469
5470 // Fill in buffers
5471 if (captureRequest->mInputStream != NULL) {
5472 halRequest->input_buffer = &captureRequest->mInputBuffer;
5473 totalNumBuffers += 1;
5474 } else {
5475 halRequest->input_buffer = NULL;
5476 }
5477
5478 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5479 captureRequest->mOutputStreams.size());
5480 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005481 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005482
5483 sp<Camera3Device> parent = mParent.promote();
5484 if (parent == NULL) {
5485 // Should not happen, and nowhere to send errors to, so just log it
5486 CLOGE("RequestThread: Parent is gone");
5487 return INVALID_OPERATION;
5488 }
5489 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5490
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005491 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005492 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005493 sp<Camera3OutputStreamInterface> outputStream =
5494 captureRequest->mOutputStreams.editItemAt(j);
5495 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005496
5497 // Prepare video buffers for high speed recording on the first video request.
5498 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5499 // Only try to prepare video stream on the first video request.
5500 mPrepareVideoStream = false;
5501
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005502 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5503 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005504 while (res == NOT_ENOUGH_DATA) {
5505 res = outputStream->prepareNextBuffer();
5506 }
5507 if (res != OK) {
5508 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5509 __FUNCTION__, strerror(-res), res);
5510 outputStream->cancelPrepare();
5511 }
5512 }
5513
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005514 std::vector<size_t> uniqueSurfaceIds;
5515 res = outputStream->getUniqueSurfaceIds(
5516 captureRequest->mOutputSurfaces[streamId],
5517 &uniqueSurfaceIds);
5518 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5519 if (res != OK && res != INVALID_OPERATION) {
5520 ALOGE("%s: failed to query stream %d unique surface IDs",
5521 __FUNCTION__, streamId);
5522 return res;
5523 }
5524 if (res == OK) {
5525 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5526 }
5527
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005528 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005529 if (outputStream->isAbandoned()) {
5530 ALOGE("%s: stream %d is abandoned.", __FUNCTION__, streamId);
5531 return TIMED_OUT;
5532 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005533 // HAL will request buffer through requestStreamBuffer API
5534 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5535 buffer.stream = outputStream->asHalStream();
5536 buffer.buffer = nullptr;
5537 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5538 buffer.acquire_fence = -1;
5539 buffer.release_fence = -1;
5540 } else {
5541 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5542 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005543 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005544 if (res != OK) {
5545 // Can't get output buffer from gralloc queue - this could be due to
5546 // abandoned queue or other consumer misbehavior, so not a fatal
5547 // error
5548 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5549 " %s (%d)", strerror(-res), res);
5550
5551 return TIMED_OUT;
5552 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005553 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005554
5555 {
5556 sp<Camera3Device> parent = mParent.promote();
5557 if (parent != nullptr) {
5558 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5559 for (const auto& settings : captureRequest->mSettingsList) {
5560 if ((streamCameraId.isEmpty() &&
5561 parent->getId() == settings.cameraId.c_str()) ||
5562 streamCameraId == settings.cameraId.c_str()) {
5563 outputStream->fireBufferRequestForFrameNumber(
5564 captureRequest->mResultExtras.frameNumber,
5565 settings.metadata);
5566 }
5567 }
5568 }
5569 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005570
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005571 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5572
5573 if (!physicalCameraId.isEmpty()) {
5574 // Physical stream isn't supported for input request.
5575 if (halRequest->input_buffer) {
5576 CLOGE("Physical stream is not supported for input request");
5577 return INVALID_OPERATION;
5578 }
5579 requestedPhysicalCameras.insert(physicalCameraId);
5580 }
5581 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005582 }
5583 totalNumBuffers += halRequest->num_output_buffers;
5584
5585 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005586 // If this request list is for constrained high speed recording (not
5587 // preview), and the current request is not the last one in the batch,
5588 // do not send callback to the app.
5589 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005590 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005591 hasCallback = false;
5592 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005593 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005594 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005595 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5596 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5597 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5598 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5599 isStillCapture = true;
5600 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5601 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005602
5603 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5604 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5605 isZslCapture = true;
5606 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005607 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005608 res = parent->registerInFlight(halRequest->frame_number,
5609 totalNumBuffers, captureRequest->mResultExtras,
5610 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005611 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005612 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005613 requestedPhysicalCameras, isStillCapture, isZslCapture,
5614 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5615 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005616 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5617 ", burstId = %" PRId32 ".",
5618 __FUNCTION__,
5619 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5620 captureRequest->mResultExtras.burstId);
5621 if (res != OK) {
5622 SET_ERR("RequestThread: Unable to register new in-flight request:"
5623 " %s (%d)", strerror(-res), res);
5624 return INVALID_OPERATION;
5625 }
5626 }
5627
5628 return OK;
5629}
5630
Igor Murashkin1e479c02013-09-06 16:55:14 -07005631CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005632 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005633 Mutex::Autolock al(mLatestRequestMutex);
5634
5635 ALOGV("RequestThread::%s", __FUNCTION__);
5636
5637 return mLatestRequest;
5638}
5639
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005640bool Camera3Device::RequestThread::isStreamPending(
5641 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005642 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005643 Mutex::Autolock l(mRequestLock);
5644
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005645 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005646 if (!nextRequest.submitted) {
5647 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5648 if (stream == s) return true;
5649 }
5650 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005651 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005652 }
5653
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005654 for (const auto& request : mRequestQueue) {
5655 for (const auto& s : request->mOutputStreams) {
5656 if (stream == s) return true;
5657 }
5658 if (stream == request->mInputStream) return true;
5659 }
5660
5661 for (const auto& request : mRepeatingRequests) {
5662 for (const auto& s : request->mOutputStreams) {
5663 if (stream == s) return true;
5664 }
5665 if (stream == request->mInputStream) return true;
5666 }
5667
5668 return false;
5669}
Jianing Weicb0652e2014-03-12 18:29:36 -07005670
Emilian Peev40ead602017-09-26 15:46:36 +01005671bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5672 ATRACE_CALL();
5673 Mutex::Autolock l(mRequestLock);
5674
5675 for (const auto& nextRequest : mNextRequests) {
5676 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5677 if (s.first == streamId) {
5678 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5679 if (it != s.second.end()) {
5680 return true;
5681 }
5682 }
5683 }
5684 }
5685
5686 for (const auto& request : mRequestQueue) {
5687 for (const auto& s : request->mOutputSurfaces) {
5688 if (s.first == streamId) {
5689 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5690 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005691 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005692 }
5693 }
5694 }
5695 }
5696
5697 for (const auto& request : mRepeatingRequests) {
5698 for (const auto& s : request->mOutputSurfaces) {
5699 if (s.first == streamId) {
5700 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5701 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005702 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005703 }
5704 }
5705 }
5706 }
5707
5708 return false;
5709}
5710
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005711void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5712 if (!mUseHalBufManager) {
5713 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5714 return;
5715 }
5716
5717 Mutex::Autolock pl(mPauseLock);
5718 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005719 mInterface->signalPipelineDrain(streamIds);
5720 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005721 }
5722 // If request thread is still busy, wait until paused then notify HAL
5723 mNotifyPipelineDrain = true;
5724 mStreamIdsToBeDrained = streamIds;
5725}
5726
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005727nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005728 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005729 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005730 return mExpectedInflightDuration > kMinInflightDuration ?
5731 mExpectedInflightDuration : kMinInflightDuration;
5732}
5733
Emilian Peevaebbe412018-01-15 13:53:24 +00005734void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5735 camera3_capture_request_t *halRequest) {
5736 if ((request == nullptr) || (halRequest == nullptr)) {
5737 ALOGE("%s: Invalid request!", __FUNCTION__);
5738 return;
5739 }
5740
5741 if (halRequest->num_physcam_settings > 0) {
5742 if (halRequest->physcam_id != nullptr) {
5743 delete [] halRequest->physcam_id;
5744 halRequest->physcam_id = nullptr;
5745 }
5746 if (halRequest->physcam_settings != nullptr) {
5747 auto it = ++(request->mSettingsList.begin());
5748 size_t i = 0;
5749 for (; it != request->mSettingsList.end(); it++, i++) {
5750 it->metadata.unlock(halRequest->physcam_settings[i]);
5751 }
5752 delete [] halRequest->physcam_settings;
5753 halRequest->physcam_settings = nullptr;
5754 }
5755 }
5756}
5757
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005758void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5759 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005760 return;
5761 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005762
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005763 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005764 // Skip the ones that have been submitted successfully.
5765 if (nextRequest.submitted) {
5766 continue;
5767 }
5768
5769 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5770 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5771 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5772
5773 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005774 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005775 }
5776
Emilian Peevaebbe412018-01-15 13:53:24 +00005777 cleanupPhysicalSettings(captureRequest, halRequest);
5778
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005779 if (captureRequest->mInputStream != NULL) {
5780 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5781 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5782 }
5783
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005784 // No output buffer can be returned when using HAL buffer manager
5785 if (!mUseHalBufManager) {
5786 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5787 //Buffers that failed processing could still have
5788 //valid acquire fence.
5789 int acquireFence = (*outputBuffers)[i].acquire_fence;
5790 if (0 <= acquireFence) {
5791 close(acquireFence);
5792 outputBuffers->editItemAt(i).acquire_fence = -1;
5793 }
5794 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5795 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5796 /*timestampIncreasing*/true, std::vector<size_t> (),
5797 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005798 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005799 }
5800
5801 if (sendRequestError) {
5802 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005803 sp<NotificationListener> listener = mListener.promote();
5804 if (listener != NULL) {
5805 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005806 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005807 captureRequest->mResultExtras);
5808 }
5809 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005810
5811 // Remove yet-to-be submitted inflight request from inflightMap
5812 {
5813 sp<Camera3Device> parent = mParent.promote();
5814 if (parent != NULL) {
5815 Mutex::Autolock l(parent->mInFlightLock);
5816 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5817 if (idx >= 0) {
5818 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5819 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5820 parent->removeInFlightMapEntryLocked(idx);
5821 }
5822 }
5823 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005824 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005825
5826 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005827 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005828}
5829
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005830void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005831 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005832 // Optimized a bit for the simple steady-state case (single repeating
5833 // request), to avoid putting that request in the queue temporarily.
5834 Mutex::Autolock l(mRequestLock);
5835
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005836 assert(mNextRequests.empty());
5837
5838 NextRequest nextRequest;
5839 nextRequest.captureRequest = waitForNextRequestLocked();
5840 if (nextRequest.captureRequest == nullptr) {
5841 return;
5842 }
5843
5844 nextRequest.halRequest = camera3_capture_request_t();
5845 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005846 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005847
5848 // Wait for additional requests
5849 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5850
5851 for (size_t i = 1; i < batchSize; i++) {
5852 NextRequest additionalRequest;
5853 additionalRequest.captureRequest = waitForNextRequestLocked();
5854 if (additionalRequest.captureRequest == nullptr) {
5855 break;
5856 }
5857
5858 additionalRequest.halRequest = camera3_capture_request_t();
5859 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005860 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005861 }
5862
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005863 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005864 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005865 mNextRequests.size(), batchSize);
5866 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005867 }
5868
5869 return;
5870}
5871
5872sp<Camera3Device::CaptureRequest>
5873 Camera3Device::RequestThread::waitForNextRequestLocked() {
5874 status_t res;
5875 sp<CaptureRequest> nextRequest;
5876
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005877 while (mRequestQueue.empty()) {
5878 if (!mRepeatingRequests.empty()) {
5879 // Always atomically enqueue all requests in a repeating request
5880 // list. Guarantees a complete in-sequence set of captures to
5881 // application.
5882 const RequestList &requests = mRepeatingRequests;
5883 RequestList::const_iterator firstRequest =
5884 requests.begin();
5885 nextRequest = *firstRequest;
5886 mRequestQueue.insert(mRequestQueue.end(),
5887 ++firstRequest,
5888 requests.end());
5889 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005890
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005891 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005892
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005893 break;
5894 }
5895
5896 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5897
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005898 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5899 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005900 Mutex::Autolock pl(mPauseLock);
5901 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005902 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005903 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005904 if (mNotifyPipelineDrain) {
5905 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5906 mNotifyPipelineDrain = false;
5907 mStreamIdsToBeDrained.clear();
5908 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005909 // Let the tracker know
5910 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5911 if (statusTracker != 0) {
5912 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5913 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005914 sp<Camera3Device> parent = mParent.promote();
5915 if (parent != nullptr) {
5916 parent->mRequestBufferSM.onRequestThreadPaused();
5917 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005918 }
5919 // Stop waiting for now and let thread management happen
5920 return NULL;
5921 }
5922 }
5923
5924 if (nextRequest == NULL) {
5925 // Don't have a repeating request already in hand, so queue
5926 // must have an entry now.
5927 RequestList::iterator firstRequest =
5928 mRequestQueue.begin();
5929 nextRequest = *firstRequest;
5930 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005931 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5932 sp<NotificationListener> listener = mListener.promote();
5933 if (listener != NULL) {
5934 listener->notifyRequestQueueEmpty();
5935 }
5936 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005937 }
5938
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005939 // In case we've been unpaused by setPaused clearing mDoPause, need to
5940 // update internal pause state (capture/setRepeatingRequest unpause
5941 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005942 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005943 if (mPaused) {
5944 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5945 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5946 if (statusTracker != 0) {
5947 statusTracker->markComponentActive(mStatusId);
5948 }
5949 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005950 mPaused = false;
5951
5952 // Check if we've reconfigured since last time, and reset the preview
5953 // request if so. Can't use 'NULL request == repeat' across configure calls.
5954 if (mReconfigured) {
5955 mPrevRequest.clear();
5956 mReconfigured = false;
5957 }
5958
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005959 if (nextRequest != NULL) {
5960 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005961 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5962 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005963
5964 // Since RequestThread::clear() removes buffers from the input stream,
5965 // get the right buffer here before unlocking mRequestLock
5966 if (nextRequest->mInputStream != NULL) {
5967 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5968 if (res != OK) {
5969 // Can't get input buffer from gralloc queue - this could be due to
5970 // disconnected queue or other producer misbehavior, so not a fatal
5971 // error
5972 ALOGE("%s: Can't get input buffer, skipping request:"
5973 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005974
5975 sp<NotificationListener> listener = mListener.promote();
5976 if (listener != NULL) {
5977 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005978 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005979 nextRequest->mResultExtras);
5980 }
5981 return NULL;
5982 }
5983 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005984 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005985
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005986 return nextRequest;
5987}
5988
5989bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005990 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005991 status_t res;
5992 Mutex::Autolock l(mPauseLock);
5993 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005994 if (mPaused == false) {
5995 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005996 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005997 if (mNotifyPipelineDrain) {
5998 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5999 mNotifyPipelineDrain = false;
6000 mStreamIdsToBeDrained.clear();
6001 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006002 // Let the tracker know
6003 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6004 if (statusTracker != 0) {
6005 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6006 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006007 sp<Camera3Device> parent = mParent.promote();
6008 if (parent != nullptr) {
6009 parent->mRequestBufferSM.onRequestThreadPaused();
6010 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006011 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006012
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006013 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006014 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006015 return true;
6016 }
6017 }
6018 // We don't set mPaused to false here, because waitForNextRequest needs
6019 // to further manage the paused state in case of starvation.
6020 return false;
6021}
6022
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006023void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006024 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006025 // With work to do, mark thread as unpaused.
6026 // If paused by request (setPaused), don't resume, to avoid
6027 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006028 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006029 Mutex::Autolock p(mPauseLock);
6030 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006031 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6032 if (mPaused) {
6033 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6034 if (statusTracker != 0) {
6035 statusTracker->markComponentActive(mStatusId);
6036 }
6037 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006038 mPaused = false;
6039 }
6040}
6041
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006042void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6043 sp<Camera3Device> parent = mParent.promote();
6044 if (parent != NULL) {
6045 va_list args;
6046 va_start(args, fmt);
6047
6048 parent->setErrorStateV(fmt, args);
6049
6050 va_end(args);
6051 }
6052}
6053
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006054status_t Camera3Device::RequestThread::insertTriggers(
6055 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006056 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006057 Mutex::Autolock al(mTriggerMutex);
6058
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006059 sp<Camera3Device> parent = mParent.promote();
6060 if (parent == NULL) {
6061 CLOGE("RequestThread: Parent is gone");
6062 return DEAD_OBJECT;
6063 }
6064
Emilian Peevaebbe412018-01-15 13:53:24 +00006065 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006066 size_t count = mTriggerMap.size();
6067
6068 for (size_t i = 0; i < count; ++i) {
6069 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006070 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006071
6072 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6073 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6074 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006075 if (isAeTrigger) {
6076 request->mResultExtras.precaptureTriggerId = triggerId;
6077 mCurrentPreCaptureTriggerId = triggerId;
6078 } else {
6079 request->mResultExtras.afTriggerId = triggerId;
6080 mCurrentAfTriggerId = triggerId;
6081 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006082 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006083 }
6084
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006085 camera_metadata_entry entry = metadata.find(tag);
6086
6087 if (entry.count > 0) {
6088 /**
6089 * Already has an entry for this trigger in the request.
6090 * Rewrite it with our requested trigger value.
6091 */
6092 RequestTrigger oldTrigger = trigger;
6093
6094 oldTrigger.entryValue = entry.data.u8[0];
6095
6096 mTriggerReplacedMap.add(tag, oldTrigger);
6097 } else {
6098 /**
6099 * More typical, no trigger entry, so we just add it
6100 */
6101 mTriggerRemovedMap.add(tag, trigger);
6102 }
6103
6104 status_t res;
6105
6106 switch (trigger.getTagType()) {
6107 case TYPE_BYTE: {
6108 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6109 res = metadata.update(tag,
6110 &entryValue,
6111 /*count*/1);
6112 break;
6113 }
6114 case TYPE_INT32:
6115 res = metadata.update(tag,
6116 &trigger.entryValue,
6117 /*count*/1);
6118 break;
6119 default:
6120 ALOGE("%s: Type not supported: 0x%x",
6121 __FUNCTION__,
6122 trigger.getTagType());
6123 return INVALID_OPERATION;
6124 }
6125
6126 if (res != OK) {
6127 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6128 ", value %d", __FUNCTION__, trigger.getTagName(),
6129 trigger.entryValue);
6130 return res;
6131 }
6132
6133 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6134 trigger.getTagName(),
6135 trigger.entryValue);
6136 }
6137
6138 mTriggerMap.clear();
6139
6140 return count;
6141}
6142
6143status_t Camera3Device::RequestThread::removeTriggers(
6144 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006145 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006146 Mutex::Autolock al(mTriggerMutex);
6147
Emilian Peevaebbe412018-01-15 13:53:24 +00006148 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006149
6150 /**
6151 * Replace all old entries with their old values.
6152 */
6153 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6154 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6155
6156 status_t res;
6157
6158 uint32_t tag = trigger.metadataTag;
6159 switch (trigger.getTagType()) {
6160 case TYPE_BYTE: {
6161 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6162 res = metadata.update(tag,
6163 &entryValue,
6164 /*count*/1);
6165 break;
6166 }
6167 case TYPE_INT32:
6168 res = metadata.update(tag,
6169 &trigger.entryValue,
6170 /*count*/1);
6171 break;
6172 default:
6173 ALOGE("%s: Type not supported: 0x%x",
6174 __FUNCTION__,
6175 trigger.getTagType());
6176 return INVALID_OPERATION;
6177 }
6178
6179 if (res != OK) {
6180 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6181 ", trigger value %d", __FUNCTION__,
6182 trigger.getTagName(), trigger.entryValue);
6183 return res;
6184 }
6185 }
6186 mTriggerReplacedMap.clear();
6187
6188 /**
6189 * Remove all new entries.
6190 */
6191 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6192 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6193 status_t res = metadata.erase(trigger.metadataTag);
6194
6195 if (res != OK) {
6196 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6197 ", trigger value %d", __FUNCTION__,
6198 trigger.getTagName(), trigger.entryValue);
6199 return res;
6200 }
6201 }
6202 mTriggerRemovedMap.clear();
6203
6204 return OK;
6205}
6206
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006207status_t Camera3Device::RequestThread::addDummyTriggerIds(
6208 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006209 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006210 static const int32_t dummyTriggerId = 1;
6211 status_t res;
6212
Emilian Peevaebbe412018-01-15 13:53:24 +00006213 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006214
6215 // If AF trigger is active, insert a dummy AF trigger ID if none already
6216 // exists
6217 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6218 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6219 if (afTrigger.count > 0 &&
6220 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6221 afId.count == 0) {
6222 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6223 if (res != OK) return res;
6224 }
6225
6226 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6227 // if none already exists
6228 camera_metadata_entry pcTrigger =
6229 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6230 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6231 if (pcTrigger.count > 0 &&
6232 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6233 pcId.count == 0) {
6234 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6235 &dummyTriggerId, 1);
6236 if (res != OK) return res;
6237 }
6238
6239 return OK;
6240}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006241
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006242/**
6243 * PreparerThread inner class methods
6244 */
6245
6246Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006247 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006248 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006249}
6250
6251Camera3Device::PreparerThread::~PreparerThread() {
6252 Thread::requestExitAndWait();
6253 if (mCurrentStream != nullptr) {
6254 mCurrentStream->cancelPrepare();
6255 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6256 mCurrentStream.clear();
6257 }
6258 clear();
6259}
6260
Ruben Brunkc78ac262015-08-13 17:58:46 -07006261status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006262 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006263 status_t res;
6264
6265 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006266 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006267
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006268 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006269 if (res == OK) {
6270 // No preparation needed, fire listener right off
6271 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006272 if (listener != NULL) {
6273 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006274 }
6275 return OK;
6276 } else if (res != NOT_ENOUGH_DATA) {
6277 return res;
6278 }
6279
6280 // Need to prepare, start up thread if necessary
6281 if (!mActive) {
6282 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6283 // isn't running
6284 Thread::requestExitAndWait();
6285 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6286 if (res != OK) {
6287 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006288 if (listener != NULL) {
6289 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006290 }
6291 return res;
6292 }
6293 mCancelNow = false;
6294 mActive = true;
6295 ALOGV("%s: Preparer stream started", __FUNCTION__);
6296 }
6297
6298 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006299 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006300 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6301
6302 return OK;
6303}
6304
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006305void Camera3Device::PreparerThread::pause() {
6306 ATRACE_CALL();
6307
6308 Mutex::Autolock l(mLock);
6309
6310 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6311 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6312 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6313 int currentMaxCount = mCurrentMaxCount;
6314 mPendingStreams.clear();
6315 mCancelNow = true;
6316 while (mActive) {
6317 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6318 if (res == TIMED_OUT) {
6319 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6320 return;
6321 } else if (res != OK) {
6322 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6323 return;
6324 }
6325 }
6326
6327 //Check whether the prepare thread was able to complete the current
6328 //stream. In case work is still pending emplace it along with the rest
6329 //of the streams in the pending list.
6330 if (currentStream != nullptr) {
6331 if (!mCurrentPrepareComplete) {
6332 pendingStreams.emplace(currentMaxCount, currentStream);
6333 }
6334 }
6335
6336 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6337 for (const auto& it : mPendingStreams) {
6338 it.second->cancelPrepare();
6339 }
6340}
6341
6342status_t Camera3Device::PreparerThread::resume() {
6343 ATRACE_CALL();
6344 status_t res;
6345
6346 Mutex::Autolock l(mLock);
6347 sp<NotificationListener> listener = mListener.promote();
6348
6349 if (mActive) {
6350 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6351 return NO_INIT;
6352 }
6353
6354 auto it = mPendingStreams.begin();
6355 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006356 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006357 if (res == OK) {
6358 if (listener != NULL) {
6359 listener->notifyPrepared(it->second->getId());
6360 }
6361 it = mPendingStreams.erase(it);
6362 } else if (res != NOT_ENOUGH_DATA) {
6363 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6364 res, strerror(-res));
6365 it = mPendingStreams.erase(it);
6366 } else {
6367 it++;
6368 }
6369 }
6370
6371 if (mPendingStreams.empty()) {
6372 return OK;
6373 }
6374
6375 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6376 if (res != OK) {
6377 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6378 __FUNCTION__, res, strerror(-res));
6379 return res;
6380 }
6381 mCancelNow = false;
6382 mActive = true;
6383 ALOGV("%s: Preparer stream started", __FUNCTION__);
6384
6385 return OK;
6386}
6387
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006388status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006389 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006390 Mutex::Autolock l(mLock);
6391
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006392 for (const auto& it : mPendingStreams) {
6393 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006394 }
6395 mPendingStreams.clear();
6396 mCancelNow = true;
6397
6398 return OK;
6399}
6400
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006401void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006402 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006403 Mutex::Autolock l(mLock);
6404 mListener = listener;
6405}
6406
6407bool Camera3Device::PreparerThread::threadLoop() {
6408 status_t res;
6409 {
6410 Mutex::Autolock l(mLock);
6411 if (mCurrentStream == nullptr) {
6412 // End thread if done with work
6413 if (mPendingStreams.empty()) {
6414 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6415 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6416 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6417 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006418 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006419 return false;
6420 }
6421
6422 // Get next stream to prepare
6423 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006424 mCurrentStream = it->second;
6425 mCurrentMaxCount = it->first;
6426 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006427 mPendingStreams.erase(it);
6428 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6429 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6430 } else if (mCancelNow) {
6431 mCurrentStream->cancelPrepare();
6432 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6433 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6434 mCurrentStream.clear();
6435 mCancelNow = false;
6436 return true;
6437 }
6438 }
6439
6440 res = mCurrentStream->prepareNextBuffer();
6441 if (res == NOT_ENOUGH_DATA) return true;
6442 if (res != OK) {
6443 // Something bad happened; try to recover by cancelling prepare and
6444 // signalling listener anyway
6445 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6446 mCurrentStream->getId(), res, strerror(-res));
6447 mCurrentStream->cancelPrepare();
6448 }
6449
6450 // This stream has finished, notify listener
6451 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006452 sp<NotificationListener> listener = mListener.promote();
6453 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006454 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6455 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006456 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006457 }
6458
6459 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6460 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006461 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006462
6463 return true;
6464}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006465
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006466status_t Camera3Device::RequestBufferStateMachine::initialize(
6467 sp<camera3::StatusTracker> statusTracker) {
6468 if (statusTracker == nullptr) {
6469 ALOGE("%s: statusTracker is null", __FUNCTION__);
6470 return BAD_VALUE;
6471 }
6472
6473 std::lock_guard<std::mutex> lock(mLock);
6474 mStatusTracker = statusTracker;
6475 mRequestBufferStatusId = statusTracker->addComponent();
6476 return OK;
6477}
6478
6479bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6480 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006481 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006482 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006483 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006484 return true;
6485 }
6486 return false;
6487}
6488
6489void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6490 std::lock_guard<std::mutex> lock(mLock);
6491 if (!mRequestBufferOngoing) {
6492 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6493 return;
6494 }
6495 mRequestBufferOngoing = false;
6496 if (mStatus == RB_STATUS_PENDING_STOP) {
6497 checkSwitchToStopLocked();
6498 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006499 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006500}
6501
6502void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6503 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006504 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006505 return;
6506}
6507
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006508void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006509 std::lock_guard<std::mutex> lock(mLock);
6510 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006511 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6512 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006513 mInflightMapEmpty = false;
6514 if (mStatus == RB_STATUS_STOPPED) {
6515 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006516 }
6517 return;
6518}
6519
6520void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6521 std::lock_guard<std::mutex> lock(mLock);
6522 mRequestThreadPaused = true;
6523 if (mStatus == RB_STATUS_PENDING_STOP) {
6524 checkSwitchToStopLocked();
6525 }
6526 return;
6527}
6528
6529void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6530 std::lock_guard<std::mutex> lock(mLock);
6531 mInflightMapEmpty = true;
6532 if (mStatus == RB_STATUS_PENDING_STOP) {
6533 checkSwitchToStopLocked();
6534 }
6535 return;
6536}
6537
6538void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6539 std::lock_guard<std::mutex> lock(mLock);
6540 if (!checkSwitchToStopLocked()) {
6541 mStatus = RB_STATUS_PENDING_STOP;
6542 }
6543 return;
6544}
6545
6546void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6547 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6548 if (statusTracker != nullptr) {
6549 if (active) {
6550 statusTracker->markComponentActive(mRequestBufferStatusId);
6551 } else {
6552 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6553 }
6554 }
6555}
6556
6557bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6558 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6559 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006560 return true;
6561 }
6562 return false;
6563}
6564
Shuzhen Wang268a1362018-10-16 16:32:59 -07006565status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6566 CameraMetadata& resultMetadata) {
6567 status_t res = OK;
6568 if (!mNeedFixupMonochromeTags) {
6569 return res;
6570 }
6571
6572 // Remove tags that are not applicable to monochrome camera.
6573 int32_t tagsToRemove[] = {
6574 ANDROID_SENSOR_GREEN_SPLIT,
6575 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6576 ANDROID_COLOR_CORRECTION_MODE,
6577 ANDROID_COLOR_CORRECTION_TRANSFORM,
6578 ANDROID_COLOR_CORRECTION_GAINS,
6579 };
6580 for (auto tag : tagsToRemove) {
6581 res = resultMetadata.erase(tag);
6582 if (res != OK) {
6583 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6584 return res;
6585 }
6586 }
6587
6588 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6589 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6590 for (size_t i = 1; i < blEntry.count; i++) {
6591 blEntry.data.f[i] = blEntry.data.f[0];
6592 }
6593
6594 // ANDROID_SENSOR_NOISE_PROFILE
6595 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6596 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6597 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6598 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6599 if (res != OK) {
6600 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6601 __FUNCTION__, strerror(-res), res);
6602 return res;
6603 }
6604 }
6605
6606 // ANDROID_STATISTICS_LENS_SHADING_MAP
6607 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6608 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6609 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6610 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6611 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6612 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6613 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6614 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6615 }
6616 }
6617
6618 // ANDROID_TONEMAP_CURVE_BLUE
6619 // ANDROID_TONEMAP_CURVE_GREEN
6620 // ANDROID_TONEMAP_CURVE_RED
6621 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6622 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6623 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6624 if (tcbEntry.count > 0
6625 && tcbEntry.count == tcgEntry.count
6626 && tcbEntry.count == tcrEntry.count) {
6627 for (size_t i = 0; i < tcbEntry.count; i++) {
6628 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6629 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6630 }
6631 }
6632
6633 return res;
6634}
6635
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006636}; // namespace android