blob: f9ef996f65adc8d8e66d28e3f2b3004d6057d348 [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) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002154 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002155
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002156 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2157 maxExpectedDuration);
2158 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002159 if (res != OK) {
2160 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002161 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002162 }
2163
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002164 return res;
2165}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002166
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002167// Resume after internalPauseAndWaitLocked
2168status_t Camera3Device::internalResumeLocked() {
2169 status_t res;
2170
2171 mRequestThread->setPaused(false);
2172
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002173 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2174 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002175 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2176 if (res != OK) {
2177 SET_ERR_L("Can't transition to active in %f seconds!",
2178 kActiveTimeout/1e9);
2179 }
2180 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002181 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002182}
2183
Ruben Brunk183f0562015-08-12 12:55:02 -07002184status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002185 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002186
2187 size_t startIndex = 0;
2188 if (mStatusWaiters == 0) {
2189 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2190 // this status list
2191 mRecentStatusUpdates.clear();
2192 } else {
2193 // If other threads are waiting on updates to this status list, set the position of the
2194 // first element that this list will check rather than clearing the list.
2195 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002196 }
2197
Ruben Brunk183f0562015-08-12 12:55:02 -07002198 mStatusWaiters++;
2199
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002200 if (!active && mUseHalBufManager) {
2201 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08002202 if (mStatus == STATUS_ACTIVE) {
2203 mRequestThread->signalPipelineDrain(streamIds);
2204 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002205 mRequestBufferSM.onWaitUntilIdle();
2206 }
2207
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002208 bool stateSeen = false;
2209 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002210 if (active == (mStatus == STATUS_ACTIVE)) {
2211 // Desired state is current
2212 break;
2213 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002214
2215 res = mStatusChanged.waitRelative(mLock, timeout);
2216 if (res != OK) break;
2217
Ruben Brunk183f0562015-08-12 12:55:02 -07002218 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2219 // transitions.
2220 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2221 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2222 __FUNCTION__);
2223
2224 // Encountered desired state since we began waiting
2225 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002226 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2227 stateSeen = true;
2228 break;
2229 }
2230 }
2231 } while (!stateSeen);
2232
Ruben Brunk183f0562015-08-12 12:55:02 -07002233 mStatusWaiters--;
2234
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002235 return res;
2236}
2237
2238
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002239status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002240 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002241 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002242
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002243 if (listener != NULL && mListener != NULL) {
2244 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2245 }
2246 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002247 mRequestThread->setNotificationListener(listener);
2248 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002249
2250 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002251}
2252
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002253bool Camera3Device::willNotify3A() {
2254 return false;
2255}
2256
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002257status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002258 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002259 status_t res;
2260 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002261
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002262 while (mResultQueue.empty()) {
2263 res = mResultSignal.waitRelative(mOutputLock, timeout);
2264 if (res == TIMED_OUT) {
2265 return res;
2266 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002267 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2268 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002269 return res;
2270 }
2271 }
2272 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002273}
2274
Jianing Weicb0652e2014-03-12 18:29:36 -07002275status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002276 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002277 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002278
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002279 if (mResultQueue.empty()) {
2280 return NOT_ENOUGH_DATA;
2281 }
2282
Jianing Weicb0652e2014-03-12 18:29:36 -07002283 if (frame == NULL) {
2284 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2285 return BAD_VALUE;
2286 }
2287
2288 CaptureResult &result = *(mResultQueue.begin());
2289 frame->mResultExtras = result.mResultExtras;
2290 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002291 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002292 mResultQueue.erase(mResultQueue.begin());
2293
2294 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002295}
2296
2297status_t Camera3Device::triggerAutofocus(uint32_t id) {
2298 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002299 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002300
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002301 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2302 // Mix-in this trigger into the next request and only the next request.
2303 RequestTrigger trigger[] = {
2304 {
2305 ANDROID_CONTROL_AF_TRIGGER,
2306 ANDROID_CONTROL_AF_TRIGGER_START
2307 },
2308 {
2309 ANDROID_CONTROL_AF_TRIGGER_ID,
2310 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002311 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002312 };
2313
2314 return mRequestThread->queueTrigger(trigger,
2315 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002316}
2317
2318status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2319 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002320 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002321
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002322 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2323 // Mix-in this trigger into the next request and only the next request.
2324 RequestTrigger trigger[] = {
2325 {
2326 ANDROID_CONTROL_AF_TRIGGER,
2327 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2328 },
2329 {
2330 ANDROID_CONTROL_AF_TRIGGER_ID,
2331 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002332 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002333 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002334
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002335 return mRequestThread->queueTrigger(trigger,
2336 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002337}
2338
2339status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2340 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002341 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002342
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002343 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2344 // Mix-in this trigger into the next request and only the next request.
2345 RequestTrigger trigger[] = {
2346 {
2347 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2348 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2349 },
2350 {
2351 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2352 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002353 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002354 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002355
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002356 return mRequestThread->queueTrigger(trigger,
2357 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002358}
2359
Jianing Weicb0652e2014-03-12 18:29:36 -07002360status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002361 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002362 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002363 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002364
Zhijun He7ef20392014-04-21 16:04:17 -07002365 {
2366 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002367
2368 // b/116514106 "disconnect()" can get called twice for the same device. The
2369 // camera device will not be initialized during the second run.
2370 if (mStatus == STATUS_UNINITIALIZED) {
2371 return OK;
2372 }
2373
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002374 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002375 }
2376
Emilian Peev08dd2452017-04-06 16:55:14 +01002377 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002378}
2379
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002380status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002381 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2382}
2383
2384status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002385 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002386 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002387 Mutex::Autolock il(mInterfaceLock);
2388 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002389
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002390 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2391 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002392 CLOGE("Stream %d does not exist", streamId);
2393 return BAD_VALUE;
2394 }
2395
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002396 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002397 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002398 return BAD_VALUE;
2399 }
2400
2401 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002402 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002403 return BAD_VALUE;
2404 }
2405
Ruben Brunkc78ac262015-08-13 17:58:46 -07002406 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002407}
2408
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002409status_t Camera3Device::tearDown(int streamId) {
2410 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002411 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002412 Mutex::Autolock il(mInterfaceLock);
2413 Mutex::Autolock l(mLock);
2414
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002415 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2416 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002417 CLOGE("Stream %d does not exist", streamId);
2418 return BAD_VALUE;
2419 }
2420
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002421 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2422 CLOGE("Stream %d is a target of a in-progress request", streamId);
2423 return BAD_VALUE;
2424 }
2425
2426 return stream->tearDown();
2427}
2428
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002429status_t Camera3Device::addBufferListenerForStream(int streamId,
2430 wp<Camera3StreamBufferListener> listener) {
2431 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002432 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002433 Mutex::Autolock il(mInterfaceLock);
2434 Mutex::Autolock l(mLock);
2435
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002436 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2437 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002438 CLOGE("Stream %d does not exist", streamId);
2439 return BAD_VALUE;
2440 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002441 stream->addBufferListener(listener);
2442
2443 return OK;
2444}
2445
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002446/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002447 * Methods called by subclasses
2448 */
2449
2450void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002451 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002452 {
2453 // Need mLock to safely update state and synchronize to current
2454 // state of methods in flight.
2455 Mutex::Autolock l(mLock);
2456 // We can get various system-idle notices from the status tracker
2457 // while starting up. Only care about them if we've actually sent
2458 // in some requests recently.
2459 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2460 return;
2461 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002462 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2463 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002464 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002465
2466 // Skip notifying listener if we're doing some user-transparent
2467 // state changes
2468 if (mPauseStateNotify) return;
2469 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002470
2471 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002472 {
2473 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002474 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002475 }
2476 if (idle && listener != NULL) {
2477 listener->notifyIdle();
2478 }
2479}
2480
Shuzhen Wang758c2152017-01-10 18:26:18 -08002481status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002482 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002483 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002484 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2485 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002486
2487 if (surfaceIds == nullptr) {
2488 return BAD_VALUE;
2489 }
2490
Zhijun He5d677d12016-05-29 16:52:39 -07002491 Mutex::Autolock il(mInterfaceLock);
2492 Mutex::Autolock l(mLock);
2493
Shuzhen Wang758c2152017-01-10 18:26:18 -08002494 if (consumers.size() == 0) {
2495 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002496 return BAD_VALUE;
2497 }
2498
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002499 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2500 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002501 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002502 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002503 }
Shuzhen Wang758c2152017-01-10 18:26:18 -08002504 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002505 if (res != OK) {
2506 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2507 return res;
2508 }
2509
Emilian Peev40ead602017-09-26 15:46:36 +01002510 for (auto &consumer : consumers) {
2511 int id = stream->getSurfaceId(consumer);
2512 if (id < 0) {
2513 CLOGE("Invalid surface id!");
2514 return BAD_VALUE;
2515 }
2516 surfaceIds->push_back(id);
2517 }
2518
Shuzhen Wang0129d522016-10-30 22:43:41 -07002519 if (stream->isConsumerConfigurationDeferred()) {
2520 if (!stream->isConfiguring()) {
2521 CLOGE("Stream %d was already fully configured.", streamId);
2522 return INVALID_OPERATION;
2523 }
Zhijun He5d677d12016-05-29 16:52:39 -07002524
Shuzhen Wang0129d522016-10-30 22:43:41 -07002525 res = stream->finishConfiguration();
2526 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002527 // If finishConfiguration fails due to abandoned surface, do not set
2528 // device to error state.
2529 bool isSurfaceAbandoned =
2530 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2531 if (!isSurfaceAbandoned) {
2532 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2533 stream->getId(), strerror(-res), res);
2534 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002535 return res;
2536 }
Zhijun He5d677d12016-05-29 16:52:39 -07002537 }
2538
2539 return OK;
2540}
2541
Emilian Peev40ead602017-09-26 15:46:36 +01002542status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2543 const std::vector<OutputStreamInfo> &outputInfo,
2544 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2545 Mutex::Autolock il(mInterfaceLock);
2546 Mutex::Autolock l(mLock);
2547
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002548 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2549 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002550 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002551 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002552 }
2553
2554 for (const auto &it : removedSurfaceIds) {
2555 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2556 CLOGE("Shared surface still part of a pending request!");
2557 return -EBUSY;
2558 }
2559 }
2560
Emilian Peev40ead602017-09-26 15:46:36 +01002561 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2562 if (res != OK) {
2563 CLOGE("Stream %d failed to update stream (error %d %s) ",
2564 streamId, res, strerror(-res));
2565 if (res == UNKNOWN_ERROR) {
2566 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2567 __FUNCTION__);
2568 }
2569 return res;
2570 }
2571
2572 return res;
2573}
2574
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002575status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2576 Mutex::Autolock il(mInterfaceLock);
2577 Mutex::Autolock l(mLock);
2578
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002579 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2580 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002581 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2582 return BAD_VALUE;
2583 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002584 return stream->dropBuffers(dropping);
2585}
2586
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002587/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002588 * Camera3Device private methods
2589 */
2590
2591sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002592 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002593 ATRACE_CALL();
2594 status_t res;
2595
2596 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002597 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002598
2599 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002600 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002601 if (inputStreams.count > 0) {
2602 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002603 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002604 CLOGE("Request references unknown input stream %d",
2605 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002606 return NULL;
2607 }
2608 // Lazy completion of stream configuration (allocation/registration)
2609 // on first use
2610 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002611 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002612 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002613 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002614 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002615 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002616 return NULL;
2617 }
2618 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002619 // Check if stream prepare is blocking requests.
2620 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002621 CLOGE("Request references an input stream that's being prepared!");
2622 return NULL;
2623 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002624
2625 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002626 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002627 }
2628
2629 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002630 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002631 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002632 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002633 return NULL;
2634 }
2635
2636 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002637 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2638 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002639 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002640 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002641 return NULL;
2642 }
Zhijun He5d677d12016-05-29 16:52:39 -07002643 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002644 auto iter = surfaceMap.find(streams.data.i32[i]);
2645 if (iter != surfaceMap.end()) {
2646 const std::vector<size_t>& surfaces = iter->second;
2647 for (const auto& surface : surfaces) {
2648 if (stream->isConsumerConfigurationDeferred(surface)) {
2649 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2650 "due to deferred consumer", stream->getId(), surface);
2651 return NULL;
2652 }
2653 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002654 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002655 }
2656
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002657 // Lazy completion of stream configuration (allocation/registration)
2658 // on first use
2659 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002660 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002661 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002662 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2663 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002664 return NULL;
2665 }
2666 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002667 // Check if stream prepare is blocking requests.
2668 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002669 CLOGE("Request references an output stream that's being prepared!");
2670 return NULL;
2671 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002672
2673 newRequest->mOutputStreams.push(stream);
2674 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002675 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002676 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002677
2678 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002679}
2680
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002681bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2682 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2683 Size size = mSupportedOpaqueInputSizes[i];
2684 if (size.width == width && size.height == height) {
2685 return true;
2686 }
2687 }
2688
2689 return false;
2690}
2691
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002692void Camera3Device::cancelStreamsConfigurationLocked() {
2693 int res = OK;
2694 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2695 res = mInputStream->cancelConfiguration();
2696 if (res != OK) {
2697 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2698 mInputStream->getId(), strerror(-res), res);
2699 }
2700 }
2701
2702 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002703 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002704 if (outputStream->isConfiguring()) {
2705 res = outputStream->cancelConfiguration();
2706 if (res != OK) {
2707 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2708 outputStream->getId(), strerror(-res), res);
2709 }
2710 }
2711 }
2712
2713 // Return state to that at start of call, so that future configures
2714 // properly clean things up
2715 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2716 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002717
2718 res = mPreparerThread->resume();
2719 if (res != OK) {
2720 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2721 }
2722}
2723
2724bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2725 ATRACE_CALL();
2726 bool ret = false;
2727
2728 Mutex::Autolock il(mInterfaceLock);
2729 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2730
2731 Mutex::Autolock l(mLock);
2732 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2733 if (rc == NO_ERROR) {
2734 mNeedConfig = true;
2735 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2736 if (rc == NO_ERROR) {
2737 ret = true;
2738 mPauseStateNotify = false;
2739 //Moving to active state while holding 'mLock' is important.
2740 //There could be pending calls to 'create-/deleteStream' which
2741 //will trigger another stream configuration while the already
2742 //present streams end up with outstanding buffers that will
2743 //not get drained.
2744 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002745 } else if (rc == DEAD_OBJECT) {
2746 // DEAD_OBJECT can be returned if either the consumer surface is
2747 // abandoned, or the HAL has died.
2748 // - If the HAL has died, configureStreamsLocked call will set
2749 // device to error state,
2750 // - If surface is abandoned, we should not set device to error
2751 // state.
2752 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002753 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002754 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002755 }
2756 } else {
2757 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2758 }
2759
2760 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002761}
2762
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002763status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002764 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002765 ATRACE_CALL();
2766 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002767
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002768 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002769 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002770 return INVALID_OPERATION;
2771 }
2772
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002773 if (operatingMode < 0) {
2774 CLOGE("Invalid operating mode: %d", operatingMode);
2775 return BAD_VALUE;
2776 }
2777
2778 bool isConstrainedHighSpeed =
2779 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2780 operatingMode;
2781
2782 if (mOperatingMode != operatingMode) {
2783 mNeedConfig = true;
2784 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2785 mOperatingMode = operatingMode;
2786 }
2787
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002788 if (!mNeedConfig) {
2789 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2790 return OK;
2791 }
2792
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002793 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2794 // adding a dummy stream instead.
2795 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2796 if (mOutputStreams.size() == 0) {
2797 addDummyStreamLocked();
2798 } else {
2799 tryRemoveDummyStreamLocked();
2800 }
2801
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002802 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002803 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002804
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002805 mPreparerThread->pause();
2806
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002807 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002808 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002809 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2810
2811 Vector<camera3_stream_t*> streams;
2812 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002813 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002814
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002815
2816 if (mInputStream != NULL) {
2817 camera3_stream_t *inputStream;
2818 inputStream = mInputStream->startConfiguration();
2819 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002820 CLOGE("Can't start input stream configuration");
2821 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002822 return INVALID_OPERATION;
2823 }
2824 streams.add(inputStream);
2825 }
2826
2827 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002828
2829 // Don't configure bidi streams twice, nor add them twice to the list
2830 if (mOutputStreams[i].get() ==
2831 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2832
2833 config.num_streams--;
2834 continue;
2835 }
2836
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002837 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002838 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002839 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002840 CLOGE("Can't start output stream configuration");
2841 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002842 return INVALID_OPERATION;
2843 }
2844 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002845
2846 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2847 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002848 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2849 // always occupy the initial entry.
2850 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002851 getJpegBufferSize(outputStream->width, outputStream->height));
2852 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002853 }
2854
2855 config.streams = streams.editArray();
2856
2857 // Do the HAL configuration; will potentially touch stream
2858 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002859
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002860 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002861 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002862 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002863
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002864 if (res == BAD_VALUE) {
2865 // HAL rejected this set of streams as unsupported, clean up config
2866 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002867 CLOGE("Set of requested inputs/outputs not supported by HAL");
2868 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002869 return BAD_VALUE;
2870 } else if (res != OK) {
2871 // Some other kind of error from configure_streams - this is not
2872 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002873 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2874 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002875 return res;
2876 }
2877
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002878 // Finish all stream configuration immediately.
2879 // TODO: Try to relax this later back to lazy completion, which should be
2880 // faster
2881
Igor Murashkin073f8572013-05-02 14:59:28 -07002882 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002883 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002884 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002885 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002886 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002887 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002888 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2889 return DEAD_OBJECT;
2890 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002891 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002892 }
2893 }
2894
2895 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002896 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002897 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002898 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002899 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002900 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002901 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002902 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002903 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2904 return DEAD_OBJECT;
2905 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002906 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002907 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002908 }
2909 }
2910
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002911 // Request thread needs to know to avoid using repeat-last-settings protocol
2912 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002913 if (notifyRequestThread) {
2914 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2915 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002916
Zhijun He90f7c372016-08-16 16:19:43 -07002917 char value[PROPERTY_VALUE_MAX];
2918 property_get("camera.fifo.disable", value, "0");
2919 int32_t disableFifo = atoi(value);
2920 if (disableFifo != 1) {
2921 // Boost priority of request thread to SCHED_FIFO.
2922 pid_t requestThreadTid = mRequestThread->getTid();
2923 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002924 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002925 if (res != OK) {
2926 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2927 strerror(-res), res);
2928 } else {
2929 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2930 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002931 }
2932
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002933 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002934 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2935 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2936 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2937 sessionParams.unlock(newSessionParams);
2938 mSessionParams.unlock(currentSessionParams);
2939 if (updateSessionParams) {
2940 mSessionParams = sessionParams;
2941 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002942
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002943 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002944
Ruben Brunk183f0562015-08-12 12:55:02 -07002945 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2946 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002947
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002948 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002949
Zhijun He0a210512014-07-24 13:45:15 -07002950 // tear down the deleted streams after configure streams.
2951 mDeletedStreams.clear();
2952
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002953 auto rc = mPreparerThread->resume();
2954 if (rc != OK) {
2955 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2956 return rc;
2957 }
2958
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002959 if (mDummyStreamId == NO_STREAM) {
2960 mRequestBufferSM.onStreamsConfigured();
2961 }
2962
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002963 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002964}
2965
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002966status_t Camera3Device::addDummyStreamLocked() {
2967 ATRACE_CALL();
2968 status_t res;
2969
2970 if (mDummyStreamId != NO_STREAM) {
2971 // Should never be adding a second dummy stream when one is already
2972 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002973 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2974 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002975 return INVALID_OPERATION;
2976 }
2977
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002978 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002979
2980 sp<Camera3OutputStreamInterface> dummyStream =
2981 new Camera3DummyStream(mNextStreamId);
2982
2983 res = mOutputStreams.add(mNextStreamId, dummyStream);
2984 if (res < 0) {
2985 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2986 return res;
2987 }
2988
2989 mDummyStreamId = mNextStreamId;
2990 mNextStreamId++;
2991
2992 return OK;
2993}
2994
2995status_t Camera3Device::tryRemoveDummyStreamLocked() {
2996 ATRACE_CALL();
2997 status_t res;
2998
2999 if (mDummyStreamId == NO_STREAM) return OK;
3000 if (mOutputStreams.size() == 1) return OK;
3001
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003002 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003003
3004 // Ok, have a dummy stream and there's at least one other output stream,
3005 // so remove the dummy
3006
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003007 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
3008 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003009 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3010 return INVALID_OPERATION;
3011 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003012 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003013
3014 // Free up the stream endpoint so that it can be used by some other stream
3015 res = deletedStream->disconnect();
3016 if (res != OK) {
3017 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3018 // fall through since we want to still list the stream as deleted.
3019 }
3020 mDeletedStreams.add(deletedStream);
3021 mDummyStreamId = NO_STREAM;
3022
3023 return res;
3024}
3025
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003026void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003027 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003028 Mutex::Autolock l(mLock);
3029 va_list args;
3030 va_start(args, fmt);
3031
3032 setErrorStateLockedV(fmt, args);
3033
3034 va_end(args);
3035}
3036
3037void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
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 setErrorStateLockedV(fmt, args);
3041}
3042
3043void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3044 va_list args;
3045 va_start(args, fmt);
3046
3047 setErrorStateLockedV(fmt, args);
3048
3049 va_end(args);
3050}
3051
3052void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003053 // Print out all error messages to log
3054 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003055 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003056
3057 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003058 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003059
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003060 mErrorCause = errorCause;
3061
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003062 if (mRequestThread != nullptr) {
3063 mRequestThread->setPaused(true);
3064 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003065 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003066
3067 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003068 sp<NotificationListener> listener = mListener.promote();
3069 if (listener != NULL) {
3070 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003071 CaptureResultExtras());
3072 }
3073
3074 // Save stack trace. View by dumping it later.
3075 CameraTraces::saveTrace();
3076 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003077}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003078
3079/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003080 * In-flight request management
3081 */
3082
Jianing Weicb0652e2014-03-12 18:29:36 -07003083status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003084 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003085 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003086 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003087 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003088 ATRACE_CALL();
3089 Mutex::Autolock l(mInFlightLock);
3090
3091 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003092 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003093 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3094 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003095 if (res < 0) return res;
3096
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003097 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003098 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3099 // avoid a deadlock during reprocess requests.
3100 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003101 if (mStatusTracker != nullptr) {
3102 mStatusTracker->markComponentActive(mInFlightStatusId);
3103 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003104 }
3105
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003106 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003107 return OK;
3108}
3109
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003110void Camera3Device::returnOutputBuffers(
3111 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003112 nsecs_t timestamp, bool timestampIncreasing,
3113 const SurfaceMap& outputSurfaces,
3114 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003115
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003116 for (size_t i = 0; i < numBuffers; i++)
3117 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003118 if (outputBuffers[i].buffer == nullptr) {
3119 if (!mUseHalBufManager) {
3120 // With HAL buffer management API, HAL sometimes will have to return buffers that
3121 // has not got a output buffer handle filled yet. This is though illegal if HAL
3122 // buffer management API is not being used.
3123 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3124 }
3125 continue;
3126 }
3127
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003128 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3129 int streamId = stream->getId();
3130 const auto& it = outputSurfaces.find(streamId);
3131 status_t res = OK;
3132 if (it != outputSurfaces.end()) {
3133 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003134 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3135 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003136 } else {
3137 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003138 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3139 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003140 }
3141
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003142 // Note: stream may be deallocated at this point, if this buffer was
3143 // the last reference to it.
3144 if (res != OK) {
3145 ALOGE("Can't return buffer to its stream: %s (%d)",
3146 strerror(-res), res);
3147 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003148
3149 // Long processing consumers can cause returnBuffer timeout for shared stream
3150 // If that happens, cancel the buffer and send a buffer error to client
3151 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3152 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3153 // cancel the buffer
3154 camera3_stream_buffer_t sb = outputBuffers[i];
3155 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003156 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3157 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003158
3159 // notify client buffer error
3160 sp<NotificationListener> listener;
3161 {
3162 Mutex::Autolock l(mOutputLock);
3163 listener = mListener.promote();
3164 }
3165
3166 if (listener != nullptr) {
3167 CaptureResultExtras extras = inResultExtras;
3168 extras.errorStreamId = streamId;
3169 listener->notifyError(
3170 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3171 extras);
3172 }
3173 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003174 }
3175}
3176
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003177void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003178 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003179 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003180 mInFlightMap.removeItemsAt(idx, 1);
3181
3182 // Indicate idle inFlightMap to the status tracker
3183 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003184 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003185 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3186 // avoid a deadlock during reprocess requests.
3187 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003188 if (mStatusTracker != nullptr) {
3189 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3190 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003191 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003192 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003193}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003194
3195void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3196
3197 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3198 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3199
3200 nsecs_t sensorTimestamp = request.sensorTimestamp;
3201 nsecs_t shutterTimestamp = request.shutterTimestamp;
3202
3203 // Check if it's okay to remove the request from InFlightMap:
3204 // In the case of a successful request:
3205 // all input and output buffers, all result metadata, shutter callback
3206 // arrived.
3207 // In the case of a unsuccessful request:
3208 // all input and output buffers arrived.
3209 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003210 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003211 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003212 if (request.stillCapture) {
3213 ATRACE_ASYNC_END("still capture", frameNumber);
3214 }
3215
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003216 ATRACE_ASYNC_END("frame capture", frameNumber);
3217
Shuzhen Wang403044a2017-02-26 23:29:04 -08003218 // Sanity check - if sensor timestamp matches shutter timestamp in the
3219 // case of request having callback.
3220 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003221 sensorTimestamp != shutterTimestamp) {
3222 SET_ERR("sensor timestamp (%" PRId64
3223 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3224 sensorTimestamp, frameNumber, shutterTimestamp);
3225 }
3226
3227 // for an unsuccessful request, it may have pending output buffers to
3228 // return.
3229 assert(request.requestStatus != OK ||
3230 request.pendingOutputBuffers.size() == 0);
3231 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003232 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3233 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003234
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003235 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003236 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3237 }
3238
3239 // Sanity check - if we have too many in-flight frames, something has
3240 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003241 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003242 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003243 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3244 kInFlightWarnLimitHighSpeed) {
3245 CLOGE("In-flight list too large for high speed configuration: %zu",
3246 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003247 }
3248}
3249
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003250void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003251 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003252 { // First return buffers cached in mInFlightMap
3253 Mutex::Autolock l(mInFlightLock);
3254 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3255 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3256 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003257 request.pendingOutputBuffers.size(), 0,
3258 /*timestampIncreasing*/true, request.outputSurfaces,
3259 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003260 }
3261 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003262 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003263 }
3264
3265 // Then return all inflight buffers not returned by HAL
3266 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3267 mInterface->getInflightBufferKeys(&inflightKeys);
3268
3269 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3270 for (auto& pair : inflightKeys) {
3271 int32_t frameNumber = pair.first;
3272 int32_t streamId = pair.second;
3273 buffer_handle_t* buffer;
3274 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3275 if (res != OK) {
3276 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3277 __FUNCTION__, frameNumber, streamId);
3278 continue;
3279 }
3280
3281 camera3_stream_buffer_t streamBuffer;
3282 streamBuffer.buffer = buffer;
3283 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3284 streamBuffer.acquire_fence = -1;
3285 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003286
3287 // First check if the buffer belongs to deleted stream
3288 bool streamDeleted = false;
3289 for (auto& stream : mDeletedStreams) {
3290 if (streamId == stream->getId()) {
3291 streamDeleted = true;
3292 // Return buffer to deleted stream
3293 camera3_stream* halStream = stream->asHalStream();
3294 streamBuffer.stream = halStream;
3295 switch (halStream->stream_type) {
3296 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003297 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3298 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003299 if (res != OK) {
3300 ALOGE("%s: Can't return output buffer for frame %d to"
3301 " stream %d: %s (%d)", __FUNCTION__,
3302 frameNumber, streamId, strerror(-res), res);
3303 }
3304 break;
3305 case CAMERA3_STREAM_INPUT:
3306 res = stream->returnInputBuffer(streamBuffer);
3307 if (res != OK) {
3308 ALOGE("%s: Can't return input buffer for frame %d to"
3309 " stream %d: %s (%d)", __FUNCTION__,
3310 frameNumber, streamId, strerror(-res), res);
3311 }
3312 break;
3313 default: // Bi-direcitonal stream is deprecated
3314 ALOGE("%s: stream %d has unknown stream type %d",
3315 __FUNCTION__, streamId, halStream->stream_type);
3316 break;
3317 }
3318 break;
3319 }
3320 }
3321 if (streamDeleted) {
3322 continue;
3323 }
3324
3325 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003326 if (streamId == inputStreamId) {
3327 streamBuffer.stream = mInputStream->asHalStream();
3328 res = mInputStream->returnInputBuffer(streamBuffer);
3329 if (res != OK) {
3330 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003331 " stream %d: %s (%d)", __FUNCTION__,
3332 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003333 }
3334 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003335 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3336 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003337 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3338 continue;
3339 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003340 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003341 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3342 }
3343 }
3344}
3345
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003346void Camera3Device::insertResultLocked(CaptureResult *result,
3347 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003348 if (result == nullptr) return;
3349
Emilian Peev71c73a22017-03-21 16:35:51 +00003350 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3351 result->mMetadata.getAndLock());
3352 set_camera_metadata_vendor_id(meta, mVendorTagId);
3353 result->mMetadata.unlock(meta);
3354
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003355 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3356 (int32_t*)&frameNumber, 1) != OK) {
3357 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3358 return;
3359 }
3360
3361 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3362 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3363 return;
3364 }
3365
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003366 // Valid result, insert into queue
3367 List<CaptureResult>::iterator queuedResult =
3368 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3369 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3370 ", burstId = %" PRId32, __FUNCTION__,
3371 queuedResult->mResultExtras.requestId,
3372 queuedResult->mResultExtras.frameNumber,
3373 queuedResult->mResultExtras.burstId);
3374
3375 mResultSignal.signal();
3376}
3377
3378
3379void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003380 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003381 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003382 Mutex::Autolock l(mOutputLock);
3383
3384 CaptureResult captureResult;
3385 captureResult.mResultExtras = resultExtras;
3386 captureResult.mMetadata = partialResult;
3387
Shuzhen Wang268a1362018-10-16 16:32:59 -07003388 // Fix up result metadata for monochrome camera.
3389 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3390 if (res != OK) {
3391 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3392 return;
3393 }
3394
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003395 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003396}
3397
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003398
3399void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3400 CaptureResultExtras &resultExtras,
3401 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003402 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003403 bool reprocess,
3404 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003405 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003406 if (pendingMetadata.isEmpty())
3407 return;
3408
3409 Mutex::Autolock l(mOutputLock);
3410
3411 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003412 if (reprocess) {
3413 if (frameNumber < mNextReprocessResultFrameNumber) {
3414 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003415 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003416 frameNumber, mNextReprocessResultFrameNumber);
3417 return;
3418 }
3419 mNextReprocessResultFrameNumber = frameNumber + 1;
3420 } else {
3421 if (frameNumber < mNextResultFrameNumber) {
3422 SET_ERR("Out-of-order capture result metadata submitted! "
3423 "(got frame number %d, expecting %d)",
3424 frameNumber, mNextResultFrameNumber);
3425 return;
3426 }
3427 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003428 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003429
3430 CaptureResult captureResult;
3431 captureResult.mResultExtras = resultExtras;
3432 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003433 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003434
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003435 // Append any previous partials to form a complete result
3436 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3437 captureResult.mMetadata.append(collectedPartialResult);
3438 }
3439
3440 captureResult.mMetadata.sort();
3441
3442 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003443 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3444 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003445 SET_ERR("No timestamp provided by HAL for frame %d!",
3446 frameNumber);
3447 return;
3448 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003449 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3450 camera_metadata_entry timestamp =
3451 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3452 if (timestamp.count == 0) {
3453 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3454 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3455 return;
3456 }
3457 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003458
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003459 // Fix up some result metadata to account for HAL-level distortion correction
3460 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3461 if (res != OK) {
3462 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3463 frameNumber, strerror(res), res);
3464 return;
3465 }
Shuzhen Wang268a1362018-10-16 16:32:59 -07003466 // Fix up result metadata for monochrome camera.
3467 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3468 if (res != OK) {
3469 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3470 return;
3471 }
3472 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3473 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3474 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3475 physicalMetadata.mPhysicalCameraMetadata);
3476 if (res != OK) {
3477 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3478 return;
3479 }
3480 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003481
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003482 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3483 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3484
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003485 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003486}
3487
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003488/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003489 * Camera HAL device callback methods
3490 */
3491
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003492void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003493 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003494
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003495 status_t res;
3496
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003497 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003498 if (result->result == NULL && result->num_output_buffers == 0 &&
3499 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003500 SET_ERR("No result data provided by HAL for frame %d",
3501 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003502 return;
3503 }
Zhijun He204e3292014-07-14 17:09:23 -07003504
Zhijun He204e3292014-07-14 17:09:23 -07003505 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003506 result->result != NULL &&
3507 result->partial_result != 1) {
3508 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3509 " if partial result is not supported",
3510 frameNumber, result->partial_result);
3511 return;
3512 }
3513
3514 bool isPartialResult = false;
3515 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003516 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003517
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003518 // Get shutter timestamp and resultExtras from list of in-flight requests,
3519 // where it was added by the shutter notification for this frame. If the
3520 // shutter timestamp isn't received yet, append the output buffers to the
3521 // in-flight request and they will be returned when the shutter timestamp
3522 // arrives. Update the in-flight status and remove the in-flight entry if
3523 // all result data and shutter timestamp have been received.
3524 nsecs_t shutterTimestamp = 0;
3525
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003526 {
3527 Mutex::Autolock l(mInFlightLock);
3528 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3529 if (idx == NAME_NOT_FOUND) {
3530 SET_ERR("Unknown frame number for capture result: %d",
3531 frameNumber);
3532 return;
3533 }
3534 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003535 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3536 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003537 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003538 __FUNCTION__, request.resultExtras.requestId,
3539 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003540 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003541 // Always update the partial count to the latest one if it's not 0
3542 // (buffers only). When framework aggregates adjacent partial results
3543 // into one, the latest partial count will be used.
3544 if (result->partial_result != 0)
3545 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003546
3547 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003548 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003549 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3550 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3551 " the range of [1, %d] when metadata is included in the result",
3552 frameNumber, result->partial_result, mNumPartialResults);
3553 return;
3554 }
3555 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003556 if (isPartialResult && result->num_physcam_metadata) {
3557 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3558 " physical camera result", frameNumber);
3559 return;
3560 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003561 if (isPartialResult) {
3562 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003563 }
3564
Shuzhen Wang4a472662017-02-26 23:29:04 -08003565 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003566 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003567 sendPartialCaptureResult(result->result, request.resultExtras,
3568 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003569 }
3570 }
3571
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003572 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003573 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003574
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003575 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003576 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003577 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3578 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3579 request.physicalCameraIds.size(), result->num_physcam_metadata);
3580 return;
3581 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003582 if (request.haveResultMetadata) {
3583 SET_ERR("Called multiple times with metadata for frame %d",
3584 frameNumber);
3585 return;
3586 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003587 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3588 String8 physicalId(result->physcam_ids[i]);
3589 std::set<String8>::iterator cameraIdIter =
3590 request.physicalCameraIds.find(physicalId);
3591 if (cameraIdIter != request.physicalCameraIds.end()) {
3592 request.physicalCameraIds.erase(cameraIdIter);
3593 } else {
3594 SET_ERR("Total result for frame %d has already returned for camera %s",
3595 frameNumber, physicalId.c_str());
3596 return;
3597 }
3598 }
Zhijun He204e3292014-07-14 17:09:23 -07003599 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003600 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003601 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003602 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003603 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003604 request.haveResultMetadata = true;
3605 }
3606
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003607 uint32_t numBuffersReturned = result->num_output_buffers;
3608 if (result->input_buffer != NULL) {
3609 if (hasInputBufferInRequest) {
3610 numBuffersReturned += 1;
3611 } else {
3612 ALOGW("%s: Input buffer should be NULL if there is no input"
3613 " buffer sent in the request",
3614 __FUNCTION__);
3615 }
3616 }
3617 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003618 if (request.numBuffersLeft < 0) {
3619 SET_ERR("Too many buffers returned for frame %d",
3620 frameNumber);
3621 return;
3622 }
3623
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003624 camera_metadata_ro_entry_t entry;
3625 res = find_camera_metadata_ro_entry(result->result,
3626 ANDROID_SENSOR_TIMESTAMP, &entry);
3627 if (res == OK && entry.count == 1) {
3628 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003629 }
3630
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003631 // If shutter event isn't received yet, append the output buffers to
3632 // the in-flight request. Otherwise, return the output buffers to
3633 // streams.
3634 if (shutterTimestamp == 0) {
3635 request.pendingOutputBuffers.appendArray(result->output_buffers,
3636 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003637 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003638 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003639 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003640 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3641 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003642 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003643
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003644 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003645 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3646 CameraMetadata physicalMetadata;
3647 physicalMetadata.append(result->physcam_metadata[i]);
3648 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3649 physicalMetadata});
3650 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003651 if (shutterTimestamp == 0) {
3652 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003653 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003654 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003655 CameraMetadata metadata;
3656 metadata = result->result;
3657 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003658 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003659 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003660 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003661 }
3662
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003663 removeInFlightRequestIfReadyLocked(idx);
3664 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003665
Zhijun Hef0d962a2014-06-30 10:24:11 -07003666 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003667 if (hasInputBufferInRequest) {
3668 Camera3Stream *stream =
3669 Camera3Stream::cast(result->input_buffer->stream);
3670 res = stream->returnInputBuffer(*(result->input_buffer));
3671 // Note: stream may be deallocated at this point, if this buffer was the
3672 // last reference to it.
3673 if (res != OK) {
3674 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3675 " its stream:%s (%d)", __FUNCTION__,
3676 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003677 }
3678 } else {
3679 ALOGW("%s: Input buffer should be NULL if there is no input"
3680 " buffer sent in the request, skipping input buffer return.",
3681 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003682 }
3683 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003684}
3685
3686void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003687 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003688 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003689 {
3690 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003691 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003692 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003693
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003694 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003695 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003696 return;
3697 }
3698
3699 switch (msg->type) {
3700 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003701 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003702 break;
3703 }
3704 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003705 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003706 break;
3707 }
3708 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003709 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003710 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003711 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003712}
3713
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003714void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003715 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003716 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003717 // Map camera HAL error codes to ICameraDeviceCallback error codes
3718 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003719 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003720 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003721 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003722 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003723 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003724 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003725 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003726 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003727 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003728 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003729 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003730 };
3731
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003732 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003733 ((msg.error_code >= 0) &&
3734 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3735 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003736 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003737
3738 int streamId = 0;
3739 if (msg.error_stream != NULL) {
3740 Camera3Stream *stream =
3741 Camera3Stream::cast(msg.error_stream);
3742 streamId = stream->getId();
3743 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003744 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3745 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003746 streamId, msg.error_code);
3747
3748 CaptureResultExtras resultExtras;
3749 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003750 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003751 // SET_ERR calls notifyError
3752 SET_ERR("Camera HAL reported serious device error");
3753 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003754 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3755 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3756 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003757 {
3758 Mutex::Autolock l(mInFlightLock);
3759 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3760 if (idx >= 0) {
3761 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3762 r.requestStatus = msg.error_code;
3763 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003764 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3765 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3766 errorCode) {
3767 r.skipResultMetadata = true;
3768 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003769 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3770 errorCode) {
3771 // In case of missing result check whether the buffers
3772 // returned. If they returned, then remove inflight
3773 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003774 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3775 // otherwise we are depending on HAL to send the buffers back after
3776 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003777 removeInFlightRequestIfReadyLocked(idx);
3778 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003779 } else {
3780 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003781 ALOGE("Camera %s: %s: cannot find in-flight request on "
3782 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003783 resultExtras.frameNumber);
3784 }
3785 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003786 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003787 if (listener != NULL) {
3788 listener->notifyError(errorCode, resultExtras);
3789 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003790 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003791 }
3792 break;
3793 default:
3794 // SET_ERR calls notifyError
3795 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3796 break;
3797 }
3798}
3799
3800void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003801 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003802 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003803 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003804
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003805 // Set timestamp for the request in the in-flight tracking
3806 // and get the request ID to send upstream
3807 {
3808 Mutex::Autolock l(mInFlightLock);
3809 idx = mInFlightMap.indexOfKey(msg.frame_number);
3810 if (idx >= 0) {
3811 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003812
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003813 // Verify ordering of shutter notifications
3814 {
3815 Mutex::Autolock l(mOutputLock);
3816 // TODO: need to track errors for tighter bounds on expected frame number.
3817 if (r.hasInputBuffer) {
3818 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3819 SET_ERR("Shutter notification out-of-order. Expected "
3820 "notification for frame %d, got frame %d",
3821 mNextReprocessShutterFrameNumber, msg.frame_number);
3822 return;
3823 }
3824 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3825 } else {
3826 if (msg.frame_number < mNextShutterFrameNumber) {
3827 SET_ERR("Shutter notification out-of-order. Expected "
3828 "notification for frame %d, got frame %d",
3829 mNextShutterFrameNumber, msg.frame_number);
3830 return;
3831 }
3832 mNextShutterFrameNumber = msg.frame_number + 1;
3833 }
3834 }
3835
Shuzhen Wang4a472662017-02-26 23:29:04 -08003836 r.shutterTimestamp = msg.timestamp;
3837 if (r.hasCallback) {
3838 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003839 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003840 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003841 // Call listener, if any
3842 if (listener != NULL) {
3843 listener->notifyShutter(r.resultExtras, msg.timestamp);
3844 }
3845 // send pending result and buffers
3846 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3847 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003848 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003849 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003850 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003851 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003852 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3853 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003854 r.pendingOutputBuffers.clear();
3855
3856 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003857 }
3858 }
3859 if (idx < 0) {
3860 SET_ERR("Shutter notification for non-existent frame number %d",
3861 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003862 }
3863}
3864
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003865CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003866 ALOGV("%s", __FUNCTION__);
3867
Igor Murashkin1e479c02013-09-06 16:55:14 -07003868 CameraMetadata retVal;
3869
3870 if (mRequestThread != NULL) {
3871 retVal = mRequestThread->getLatestRequest();
3872 }
3873
Igor Murashkin1e479c02013-09-06 16:55:14 -07003874 return retVal;
3875}
3876
Jianing Weicb0652e2014-03-12 18:29:36 -07003877
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003878void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3879 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3880 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3881}
3882
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003883/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003884 * HalInterface inner class methods
3885 */
3886
Yifan Hongf79b5542017-04-11 14:44:25 -07003887Camera3Device::HalInterface::HalInterface(
3888 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003889 std::shared_ptr<RequestMetadataQueue> queue,
3890 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003891 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003892 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003893 mUseHalBufManager(useHalBufManager),
3894 mIsReconfigurationQuerySupported(true) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003895 // Check with hardware service manager if we can downcast these interfaces
3896 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003897 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3898 if (castResult_3_5.isOk()) {
3899 mHidlSession_3_5 = castResult_3_5;
3900 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003901 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3902 if (castResult_3_4.isOk()) {
3903 mHidlSession_3_4 = castResult_3_4;
3904 }
3905 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3906 if (castResult_3_3.isOk()) {
3907 mHidlSession_3_3 = castResult_3_3;
3908 }
3909}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003910
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003911Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003912
3913Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003914 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003915 mRequestMetadataQueue(other.mRequestMetadataQueue),
3916 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003917
3918bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003919 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003920}
3921
3922void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00003923 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003924 mHidlSession_3_4.clear();
3925 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003926 mHidlSession.clear();
3927}
3928
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003929bool Camera3Device::HalInterface::supportBatchRequest() {
3930 return mHidlSession != nullptr;
3931}
3932
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003933status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3934 camera3_request_template_t templateId,
3935 /*out*/ camera_metadata_t **requestTemplate) {
3936 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3937 if (!valid()) return INVALID_OPERATION;
3938 status_t res = OK;
3939
Emilian Peev31abd0a2017-05-11 18:37:46 +01003940 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003941
3942 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003943 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003944 status = s;
3945 if (status == common::V1_0::Status::OK) {
3946 const camera_metadata *r =
3947 reinterpret_cast<const camera_metadata_t*>(request.data());
3948 size_t expectedSize = request.size();
3949 int ret = validate_camera_metadata_structure(r, &expectedSize);
3950 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3951 *requestTemplate = clone_camera_metadata(r);
3952 if (*requestTemplate == nullptr) {
3953 ALOGE("%s: Unable to clone camera metadata received from HAL",
3954 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003955 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003956 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003957 } else {
3958 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3959 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003960 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003961 }
3962 };
3963 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003964 RequestTemplate id;
3965 switch (templateId) {
3966 case CAMERA3_TEMPLATE_PREVIEW:
3967 id = RequestTemplate::PREVIEW;
3968 break;
3969 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3970 id = RequestTemplate::STILL_CAPTURE;
3971 break;
3972 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3973 id = RequestTemplate::VIDEO_RECORD;
3974 break;
3975 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3976 id = RequestTemplate::VIDEO_SNAPSHOT;
3977 break;
3978 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3979 id = RequestTemplate::ZERO_SHUTTER_LAG;
3980 break;
3981 case CAMERA3_TEMPLATE_MANUAL:
3982 id = RequestTemplate::MANUAL;
3983 break;
3984 default:
3985 // Unknown template ID, or this HAL is too old to support it
3986 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003987 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003988 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003989
Emilian Peev31abd0a2017-05-11 18:37:46 +01003990 if (!err.isOk()) {
3991 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3992 res = DEAD_OBJECT;
3993 } else {
3994 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003995 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003996
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003997 return res;
3998}
3999
Emilian Peev4ec17882019-01-24 17:16:58 -08004000bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4001 CameraMetadata& newSessionParams) {
4002 // We do reconfiguration by default;
4003 bool ret = true;
4004 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4005 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4006 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4007 oldSessionParams.getAndLock());
4008 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4009 newSessionParams.getAndLock());
4010 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4011 get_camera_metadata_size(oldSessioMeta));
4012 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4013 get_camera_metadata_size(newSessioMeta));
4014 hardware::camera::common::V1_0::Status callStatus;
4015 bool required;
4016 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4017 bool requiredFlag) {
4018 callStatus = s;
4019 required = requiredFlag;
4020 };
4021 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4022 oldSessionParams.unlock(oldSessioMeta);
4023 newSessionParams.unlock(newSessioMeta);
4024 if (err.isOk()) {
4025 switch (callStatus) {
4026 case hardware::camera::common::V1_0::Status::OK:
4027 ret = required;
4028 break;
4029 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4030 mIsReconfigurationQuerySupported = false;
4031 ret = true;
4032 break;
4033 default:
4034 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4035 ret = true;
4036 }
4037 } else {
4038 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4039 ret = true;
4040 }
4041 }
4042
4043 return ret;
4044}
4045
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004046status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004047 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004048 ATRACE_NAME("CameraHal::configureStreams");
4049 if (!valid()) return INVALID_OPERATION;
4050 status_t res = OK;
4051
Emilian Peev31abd0a2017-05-11 18:37:46 +01004052 // Convert stream config to HIDL
4053 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004054 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4055 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4056 requestedConfiguration3_2.streams.resize(config->num_streams);
4057 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004058 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004059 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4060 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004061 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004062
Emilian Peev31abd0a2017-05-11 18:37:46 +01004063 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4064 cam3stream->setBufferFreedListener(this);
4065 int streamId = cam3stream->getId();
4066 StreamType streamType;
4067 switch (src->stream_type) {
4068 case CAMERA3_STREAM_OUTPUT:
4069 streamType = StreamType::OUTPUT;
4070 break;
4071 case CAMERA3_STREAM_INPUT:
4072 streamType = StreamType::INPUT;
4073 break;
4074 default:
4075 ALOGE("%s: Stream %d: Unsupported stream type %d",
4076 __FUNCTION__, streamId, config->streams[i]->stream_type);
4077 return BAD_VALUE;
4078 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004079 dst3_2.id = streamId;
4080 dst3_2.streamType = streamType;
4081 dst3_2.width = src->width;
4082 dst3_2.height = src->height;
4083 dst3_2.format = mapToPixelFormat(src->format);
4084 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
4085 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4086 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
4087 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004088 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004089 if (src->physical_camera_id != nullptr) {
4090 dst3_4.physicalCameraId = src->physical_camera_id;
4091 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004092
4093 activeStreams.insert(streamId);
4094 // Create Buffer ID map if necessary
4095 if (mBufferIdMaps.count(streamId) == 0) {
4096 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4097 }
4098 }
4099 // remove BufferIdMap for deleted streams
4100 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4101 int streamId = it->first;
4102 bool active = activeStreams.count(streamId) > 0;
4103 if (!active) {
4104 it = mBufferIdMaps.erase(it);
4105 } else {
4106 ++it;
4107 }
4108 }
4109
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004110 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004111 res = mapToStreamConfigurationMode(
4112 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004113 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004114 if (res != OK) {
4115 return res;
4116 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004117 requestedConfiguration3_2.operationMode = operationMode;
4118 requestedConfiguration3_4.operationMode = operationMode;
4119 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004120 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4121 get_camera_metadata_size(sessionParams));
4122
Emilian Peev31abd0a2017-05-11 18:37:46 +01004123 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004124 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004125 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004126 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004127
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004128 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004129 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4130 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004131 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004132 };
4133
4134 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4135 (hardware::Return<void>& err) -> status_t {
4136 if (!err.isOk()) {
4137 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4138 return DEAD_OBJECT;
4139 }
4140 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4141 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4142 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4143 }
4144 return OK;
4145 };
4146
4147 // See if we have v3.4 or v3.3 HAL
4148 if (mHidlSession_3_5 != nullptr) {
4149 ALOGV("%s: v3.5 device found", __FUNCTION__);
4150 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4151 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4152 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4153 auto err = mHidlSession_3_5->configureStreams_3_5(
4154 requestedConfiguration3_5, configStream34Cb);
4155 res = postprocConfigStream34(err);
4156 if (res != OK) {
4157 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004158 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004159 } else if (mHidlSession_3_4 != nullptr) {
4160 // We do; use v3.4 for the call
4161 ALOGV("%s: v3.4 device found", __FUNCTION__);
4162 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
4163 auto err = mHidlSession_3_4->configureStreams_3_4(
4164 requestedConfiguration3_4, configStream34Cb);
4165 res = postprocConfigStream34(err);
4166 if (res != OK) {
4167 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004168 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004169 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004170 // We do; use v3.3 for the call
4171 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004172 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004173 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004174 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004175 finalConfiguration = halConfiguration;
4176 status = s;
4177 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004178 if (!err.isOk()) {
4179 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4180 return DEAD_OBJECT;
4181 }
4182 } else {
4183 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4184 ALOGV("%s: v3.2 device found", __FUNCTION__);
4185 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004186 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004187 [&status, &finalConfiguration_3_2]
4188 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4189 finalConfiguration_3_2 = halConfiguration;
4190 status = s;
4191 });
4192 if (!err.isOk()) {
4193 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4194 return DEAD_OBJECT;
4195 }
4196 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4197 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4198 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4199 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004200 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004201 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004202 }
4203
4204 if (status != common::V1_0::Status::OK ) {
4205 return CameraProviderManager::mapToStatusT(status);
4206 }
4207
4208 // And convert output stream configuration from HIDL
4209
4210 for (size_t i = 0; i < config->num_streams; i++) {
4211 camera3_stream_t *dst = config->streams[i];
4212 int streamId = Camera3Stream::cast(dst)->getId();
4213
4214 // Start scan at i, with the assumption that the stream order matches
4215 size_t realIdx = i;
4216 bool found = false;
4217 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004218 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004219 found = true;
4220 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004221 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004222 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4223 }
4224 if (!found) {
4225 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4226 __FUNCTION__, streamId);
4227 return INVALID_OPERATION;
4228 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004229 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004230
Emilian Peev710c1422017-08-30 11:19:38 +01004231 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4232 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004233 dstStream->setDataSpaceOverride(false);
4234 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4235 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4236
Emilian Peev31abd0a2017-05-11 18:37:46 +01004237 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4238 if (dst->format != overrideFormat) {
4239 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4240 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004241 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004242 if (dst->data_space != overrideDataSpace) {
4243 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4244 streamId, dst->format);
4245 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004246 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004247 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004248 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4249
Emilian Peev31abd0a2017-05-11 18:37:46 +01004250 // Override allowed with IMPLEMENTATION_DEFINED
4251 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004252 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004253 }
4254
Emilian Peev31abd0a2017-05-11 18:37:46 +01004255 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004256 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004257 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004258 __FUNCTION__, streamId);
4259 return INVALID_OPERATION;
4260 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004261 dstStream->setUsage(
4262 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004263 } else {
4264 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004265 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004266 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4267 __FUNCTION__, streamId);
4268 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004269 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004270 dstStream->setUsage(
4271 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004272 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004273 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004274 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004275
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004276 return res;
4277}
4278
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004279status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004280 /*out*/device::V3_2::CaptureRequest* captureRequest,
4281 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004282 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004283 if (captureRequest == nullptr || handlesCreated == nullptr) {
4284 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4285 __FUNCTION__, captureRequest, handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004286 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004287 }
4288
4289 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004290
4291 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004292
4293 {
4294 std::lock_guard<std::mutex> lock(mInflightLock);
4295 if (request->input_buffer != nullptr) {
4296 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4297 buffer_handle_t buf = *(request->input_buffer->buffer);
4298 auto pair = getBufferId(buf, streamId);
4299 bool isNewBuffer = pair.first;
4300 uint64_t bufferId = pair.second;
4301 captureRequest->inputBuffer.streamId = streamId;
4302 captureRequest->inputBuffer.bufferId = bufferId;
4303 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4304 captureRequest->inputBuffer.status = BufferStatus::OK;
4305 native_handle_t *acquireFence = nullptr;
4306 if (request->input_buffer->acquire_fence != -1) {
4307 acquireFence = native_handle_create(1,0);
4308 acquireFence->data[0] = request->input_buffer->acquire_fence;
4309 handlesCreated->push_back(acquireFence);
4310 }
4311 captureRequest->inputBuffer.acquireFence = acquireFence;
4312 captureRequest->inputBuffer.releaseFence = nullptr;
4313
4314 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4315 request->input_buffer->buffer,
4316 request->input_buffer->acquire_fence);
4317 } else {
4318 captureRequest->inputBuffer.streamId = -1;
4319 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4320 }
4321
4322 captureRequest->outputBuffers.resize(request->num_output_buffers);
4323 for (size_t i = 0; i < request->num_output_buffers; i++) {
4324 const camera3_stream_buffer_t *src = request->output_buffers + i;
4325 StreamBuffer &dst = captureRequest->outputBuffers[i];
4326 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004327 if (src->buffer != nullptr) {
4328 buffer_handle_t buf = *(src->buffer);
4329 auto pair = getBufferId(buf, streamId);
4330 bool isNewBuffer = pair.first;
4331 dst.bufferId = pair.second;
4332 dst.buffer = isNewBuffer ? buf : nullptr;
4333 native_handle_t *acquireFence = nullptr;
4334 if (src->acquire_fence != -1) {
4335 acquireFence = native_handle_create(1,0);
4336 acquireFence->data[0] = src->acquire_fence;
4337 handlesCreated->push_back(acquireFence);
4338 }
4339 dst.acquireFence = acquireFence;
4340 } else if (mUseHalBufManager) {
4341 // HAL buffer management path
4342 dst.bufferId = BUFFER_ID_NO_BUFFER;
4343 dst.buffer = nullptr;
4344 dst.acquireFence = nullptr;
4345 } else {
4346 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4347 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004348 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004349 dst.streamId = streamId;
4350 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004351 dst.releaseFence = nullptr;
4352
4353 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4354 src->buffer, src->acquire_fence);
4355 }
4356 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004357 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004358}
4359
4360status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4361 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4362 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4363 if (!valid()) return INVALID_OPERATION;
4364
Emilian Peevaebbe412018-01-15 13:53:24 +00004365 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4366 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4367 if (castResult_3_4.isOk()) {
4368 hidlSession_3_4 = castResult_3_4;
4369 }
4370
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004371 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004372 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004373 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004374 if (hidlSession_3_4 != nullptr) {
4375 captureRequests_3_4.resize(batchSize);
4376 } else {
4377 captureRequests.resize(batchSize);
4378 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004379 std::vector<native_handle_t*> handlesCreated;
4380
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004381 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004382 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004383 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004384 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Emilian Peevaebbe412018-01-15 13:53:24 +00004385 /*out*/&handlesCreated);
4386 } else {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004387 res = wrapAsHidlRequest(requests[i],
4388 /*out*/&captureRequests[i], /*out*/&handlesCreated);
4389 }
4390 if (res != OK) {
4391 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004392 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004393 }
4394
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004395 std::vector<device::V3_2::BufferCache> cachesToRemove;
4396 {
4397 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4398 for (auto& pair : mFreedBuffers) {
4399 // The stream might have been removed since onBufferFreed
4400 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4401 cachesToRemove.push_back({pair.first, pair.second});
4402 }
4403 }
4404 mFreedBuffers.clear();
4405 }
4406
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004407 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4408 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004409
4410 // Write metadata to FMQ.
4411 for (size_t i = 0; i < batchSize; i++) {
4412 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004413 device::V3_2::CaptureRequest* captureRequest;
4414 if (hidlSession_3_4 != nullptr) {
4415 captureRequest = &captureRequests_3_4[i].v3_2;
4416 } else {
4417 captureRequest = &captureRequests[i];
4418 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004419
4420 if (request->settings != nullptr) {
4421 size_t settingsSize = get_camera_metadata_size(request->settings);
4422 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4423 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4424 captureRequest->settings.resize(0);
4425 captureRequest->fmqSettingsSize = settingsSize;
4426 } else {
4427 if (mRequestMetadataQueue != nullptr) {
4428 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4429 }
4430 captureRequest->settings.setToExternal(
4431 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4432 get_camera_metadata_size(request->settings));
4433 captureRequest->fmqSettingsSize = 0u;
4434 }
4435 } else {
4436 // A null request settings maps to a size-0 CameraMetadata
4437 captureRequest->settings.resize(0);
4438 captureRequest->fmqSettingsSize = 0u;
4439 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004440
4441 if (hidlSession_3_4 != nullptr) {
4442 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4443 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004444 if (request->physcam_settings != nullptr) {
4445 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4446 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4447 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4448 settingsSize)) {
4449 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4450 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4451 settingsSize;
4452 } else {
4453 if (mRequestMetadataQueue != nullptr) {
4454 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4455 }
4456 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4457 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4458 request->physcam_settings[j])),
4459 get_camera_metadata_size(request->physcam_settings[j]));
4460 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004461 }
Emilian Peev00420d22018-02-05 21:33:13 +00004462 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004463 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004464 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004465 }
4466 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4467 request->physcam_id[j];
4468 }
4469 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004470 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004471
4472 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004473 auto resultCallback =
4474 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4475 status = s;
4476 *numRequestProcessed = n;
4477 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004478 if (hidlSession_3_4 != nullptr) {
4479 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004480 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004481 } else {
4482 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004483 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004484 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004485 if (!err.isOk()) {
4486 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4487 return DEAD_OBJECT;
4488 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004489 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4490 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4491 __FUNCTION__, *numRequestProcessed, batchSize);
4492 status = common::V1_0::Status::INTERNAL_ERROR;
4493 }
4494
4495 for (auto& handle : handlesCreated) {
4496 native_handle_delete(handle);
4497 }
4498 return CameraProviderManager::mapToStatusT(status);
4499}
4500
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004501status_t Camera3Device::HalInterface::processCaptureRequest(
4502 camera3_capture_request_t *request) {
4503 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004504 if (!valid()) return INVALID_OPERATION;
4505 status_t res = OK;
4506
Emilian Peev31abd0a2017-05-11 18:37:46 +01004507 uint32_t numRequestProcessed = 0;
4508 std::vector<camera3_capture_request_t*> requests(1);
4509 requests[0] = request;
4510 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4511
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004512 return res;
4513}
4514
4515status_t Camera3Device::HalInterface::flush() {
4516 ATRACE_NAME("CameraHal::flush");
4517 if (!valid()) return INVALID_OPERATION;
4518 status_t res = OK;
4519
Emilian Peev31abd0a2017-05-11 18:37:46 +01004520 auto err = mHidlSession->flush();
4521 if (!err.isOk()) {
4522 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4523 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004524 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004525 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004526 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004527
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004528 return res;
4529}
4530
Emilian Peev31abd0a2017-05-11 18:37:46 +01004531status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004532 ATRACE_NAME("CameraHal::dump");
4533 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004534
Emilian Peev31abd0a2017-05-11 18:37:46 +01004535 // Handled by CameraProviderManager::dump
4536
4537 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004538}
4539
4540status_t Camera3Device::HalInterface::close() {
4541 ATRACE_NAME("CameraHal::close()");
4542 if (!valid()) return INVALID_OPERATION;
4543 status_t res = OK;
4544
Emilian Peev31abd0a2017-05-11 18:37:46 +01004545 auto err = mHidlSession->close();
4546 // Interface will be dead shortly anyway, so don't log errors
4547 if (!err.isOk()) {
4548 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004549 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004550
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004551 return res;
4552}
4553
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004554void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4555 ATRACE_NAME("CameraHal::signalPipelineDrain");
4556 if (!valid() || mHidlSession_3_5 == nullptr) {
4557 ALOGE("%s called on invalid camera!", __FUNCTION__);
4558 return;
4559 }
4560
4561 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter);
4562 if (!err.isOk()) {
4563 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4564 return;
4565 }
4566}
4567
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004568void Camera3Device::HalInterface::getInflightBufferKeys(
4569 std::vector<std::pair<int32_t, int32_t>>* out) {
4570 std::lock_guard<std::mutex> lock(mInflightLock);
4571 out->clear();
4572 out->reserve(mInflightBufferMap.size());
4573 for (auto& pair : mInflightBufferMap) {
4574 uint64_t key = pair.first;
4575 int32_t streamId = key & 0xFFFFFFFF;
4576 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4577 out->push_back(std::make_pair(frameNumber, streamId));
4578 }
4579 return;
4580}
4581
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004582status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004583 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004584 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004585 auto pair = std::make_pair(buffer, acquireFence);
4586 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004587 return OK;
4588}
4589
4590status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004591 int32_t frameNumber, int32_t streamId,
4592 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004593 std::lock_guard<std::mutex> lock(mInflightLock);
4594
4595 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4596 auto it = mInflightBufferMap.find(key);
4597 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004598 auto pair = it->second;
4599 *buffer = pair.first;
4600 int acquireFence = pair.second;
4601 if (acquireFence > 0) {
4602 ::close(acquireFence);
4603 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004604 mInflightBufferMap.erase(it);
4605 return OK;
4606}
4607
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004608status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4609 uint64_t bufferId, buffer_handle_t* buf) {
4610 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4611 auto pair = mRequestedBuffers.insert({bufferId, buf});
4612 if (!pair.second) {
4613 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4614 __FUNCTION__, bufferId);
4615 return BAD_VALUE;
4616 }
4617 return OK;
4618}
4619
4620// Find and pop a buffer_handle_t based on bufferId
4621status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4622 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4623 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4624 auto it = mRequestedBuffers.find(bufferId);
4625 if (it == mRequestedBuffers.end()) {
4626 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4627 __FUNCTION__, bufferId);
4628 return BAD_VALUE;
4629 }
4630 *buffer = it->second;
4631 mRequestedBuffers.erase(it);
4632 return OK;
4633}
4634
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004635std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4636 const buffer_handle_t& buf, int streamId) {
4637 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4638
4639 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4640 auto it = bIdMap.find(buf);
4641 if (it == bIdMap.end()) {
4642 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004643 ALOGV("stream %d now have %zu buffer caches, buf %p",
4644 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004645 return std::make_pair(true, mNextBufferId - 1);
4646 } else {
4647 return std::make_pair(false, it->second);
4648 }
4649}
4650
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004651void Camera3Device::HalInterface::onBufferFreed(
4652 int streamId, const native_handle_t* handle) {
4653 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4654 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4655 auto mapIt = mBufferIdMaps.find(streamId);
4656 if (mapIt == mBufferIdMaps.end()) {
4657 // streamId might be from a deleted stream here
4658 ALOGI("%s: stream %d has been removed",
4659 __FUNCTION__, streamId);
4660 return;
4661 }
4662 BufferIdMap& bIdMap = mapIt->second;
4663 auto it = bIdMap.find(handle);
4664 if (it == bIdMap.end()) {
4665 ALOGW("%s: cannot find buffer %p in stream %d",
4666 __FUNCTION__, handle, streamId);
4667 return;
4668 } else {
4669 bufferId = it->second;
4670 bIdMap.erase(it);
4671 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4672 __FUNCTION__, streamId, bIdMap.size(), handle);
4673 }
4674 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4675}
4676
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004677/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004678 * RequestThread inner class methods
4679 */
4680
4681Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004682 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004683 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4684 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004685 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004686 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004687 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004688 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004689 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004690 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004691 mReconfigured(false),
4692 mDoPause(false),
4693 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004694 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004695 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004696 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004697 mCurrentAfTriggerId(0),
4698 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004699 mRepeatingLastFrameNumber(
4700 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004701 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004702 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004703 mRequestLatency(kRequestLatencyBinSize),
4704 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004705 mLatestSessionParams(sessionParamKeys.size()),
4706 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004707 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004708}
4709
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004710Camera3Device::RequestThread::~RequestThread() {}
4711
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004712void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004713 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004714 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004715 Mutex::Autolock l(mRequestLock);
4716 mListener = listener;
4717}
4718
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004719void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4720 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004721 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004722 Mutex::Autolock l(mRequestLock);
4723 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004724 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004725 // Prepare video stream for high speed recording.
4726 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004727 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004728}
4729
Jianing Wei90e59c92014-03-12 18:29:36 -07004730status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004731 List<sp<CaptureRequest> > &requests,
4732 /*out*/
4733 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004734 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004735 Mutex::Autolock l(mRequestLock);
4736 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4737 ++it) {
4738 mRequestQueue.push_back(*it);
4739 }
4740
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004741 if (lastFrameNumber != NULL) {
4742 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4743 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4744 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4745 *lastFrameNumber);
4746 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004747
Jianing Wei90e59c92014-03-12 18:29:36 -07004748 unpauseForNewRequests();
4749
4750 return OK;
4751}
4752
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004753
4754status_t Camera3Device::RequestThread::queueTrigger(
4755 RequestTrigger trigger[],
4756 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004757 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004758 Mutex::Autolock l(mTriggerMutex);
4759 status_t ret;
4760
4761 for (size_t i = 0; i < count; ++i) {
4762 ret = queueTriggerLocked(trigger[i]);
4763
4764 if (ret != OK) {
4765 return ret;
4766 }
4767 }
4768
4769 return OK;
4770}
4771
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004772const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4773 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004774 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004775 if (d != nullptr) return d->mId;
4776 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004777}
4778
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004779status_t Camera3Device::RequestThread::queueTriggerLocked(
4780 RequestTrigger trigger) {
4781
4782 uint32_t tag = trigger.metadataTag;
4783 ssize_t index = mTriggerMap.indexOfKey(tag);
4784
4785 switch (trigger.getTagType()) {
4786 case TYPE_BYTE:
4787 // fall-through
4788 case TYPE_INT32:
4789 break;
4790 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004791 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4792 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004793 return INVALID_OPERATION;
4794 }
4795
4796 /**
4797 * Collect only the latest trigger, since we only have 1 field
4798 * in the request settings per trigger tag, and can't send more than 1
4799 * trigger per request.
4800 */
4801 if (index != NAME_NOT_FOUND) {
4802 mTriggerMap.editValueAt(index) = trigger;
4803 } else {
4804 mTriggerMap.add(tag, trigger);
4805 }
4806
4807 return OK;
4808}
4809
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004810status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004811 const RequestList &requests,
4812 /*out*/
4813 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004814 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004815 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004816 if (lastFrameNumber != NULL) {
4817 *lastFrameNumber = mRepeatingLastFrameNumber;
4818 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004819 mRepeatingRequests.clear();
4820 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4821 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004822
4823 unpauseForNewRequests();
4824
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004825 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004826 return OK;
4827}
4828
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004829bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004830 if (mRepeatingRequests.empty()) {
4831 return false;
4832 }
4833 int32_t requestId = requestIn->mResultExtras.requestId;
4834 const RequestList &repeatRequests = mRepeatingRequests;
4835 // All repeating requests are guaranteed to have same id so only check first quest
4836 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4837 return (firstRequest->mResultExtras.requestId == requestId);
4838}
4839
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004840status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004841 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004842 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004843 return clearRepeatingRequestsLocked(lastFrameNumber);
4844
4845}
4846
4847status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004848 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004849 if (lastFrameNumber != NULL) {
4850 *lastFrameNumber = mRepeatingLastFrameNumber;
4851 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004852 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004853 return OK;
4854}
4855
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004856status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004857 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004858 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004859 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004860 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004861
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004862 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004863
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004864 // Send errors for all requests pending in the request queue, including
4865 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004866 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004867 if (listener != NULL) {
4868 for (RequestList::iterator it = mRequestQueue.begin();
4869 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004870 // Abort the input buffers for reprocess requests.
4871 if ((*it)->mInputStream != NULL) {
4872 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004873 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4874 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004875 if (res != OK) {
4876 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4877 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4878 } else {
4879 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4880 if (res != OK) {
4881 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4882 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4883 }
4884 }
4885 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004886 // Set the frame number this request would have had, if it
4887 // had been submitted; this frame number will not be reused.
4888 // The requestId and burstId fields were set when the request was
4889 // submitted originally (in convertMetadataListToRequestListLocked)
4890 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004891 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004892 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004893 }
4894 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004895 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004896
4897 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004898 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004899 if (lastFrameNumber != NULL) {
4900 *lastFrameNumber = mRepeatingLastFrameNumber;
4901 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004902 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004903 return OK;
4904}
4905
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004906status_t Camera3Device::RequestThread::flush() {
4907 ATRACE_CALL();
4908 Mutex::Autolock l(mFlushLock);
4909
Emilian Peev08dd2452017-04-06 16:55:14 +01004910 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004911}
4912
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004913void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004914 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004915 Mutex::Autolock l(mPauseLock);
4916 mDoPause = paused;
4917 mDoPauseSignal.signal();
4918}
4919
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004920status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4921 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004922 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004923 Mutex::Autolock l(mLatestRequestMutex);
4924 status_t res;
4925 while (mLatestRequestId != requestId) {
4926 nsecs_t startTime = systemTime();
4927
4928 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4929 if (res != OK) return res;
4930
4931 timeout -= (systemTime() - startTime);
4932 }
4933
4934 return OK;
4935}
4936
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004937void Camera3Device::RequestThread::requestExit() {
4938 // Call parent to set up shutdown
4939 Thread::requestExit();
4940 // The exit from any possible waits
4941 mDoPauseSignal.signal();
4942 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004943
4944 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4945 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004946}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004947
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004948void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004949 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004950 bool surfaceAbandoned = false;
4951 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004952 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004953 {
4954 Mutex::Autolock l(mRequestLock);
4955 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4956 // repeating requests.
4957 for (const auto& request : mRepeatingRequests) {
4958 for (const auto& s : request->mOutputStreams) {
4959 if (s->isAbandoned()) {
4960 surfaceAbandoned = true;
4961 clearRepeatingRequestsLocked(&lastFrameNumber);
4962 break;
4963 }
4964 }
4965 if (surfaceAbandoned) {
4966 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004967 }
4968 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004969 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004970 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004971
4972 if (listener != NULL && surfaceAbandoned) {
4973 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004974 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004975}
4976
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004977bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004978 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004979 status_t res;
4980 size_t batchSize = mNextRequests.size();
4981 std::vector<camera3_capture_request_t*> requests(batchSize);
4982 uint32_t numRequestProcessed = 0;
4983 for (size_t i = 0; i < batchSize; i++) {
4984 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004985 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004986 }
4987
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004988 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4989
4990 bool triggerRemoveFailed = false;
4991 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4992 for (size_t i = 0; i < numRequestProcessed; i++) {
4993 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4994 nextRequest.submitted = true;
4995
4996
4997 // Update the latest request sent to HAL
4998 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4999 Mutex::Autolock al(mLatestRequestMutex);
5000
5001 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5002 mLatestRequest.acquire(cloned);
5003
5004 sp<Camera3Device> parent = mParent.promote();
5005 if (parent != NULL) {
5006 parent->monitorMetadata(TagMonitor::REQUEST,
5007 nextRequest.halRequest.frame_number,
5008 0, mLatestRequest);
5009 }
5010 }
5011
5012 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005013 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5014 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005015 }
5016
Emilian Peevaebbe412018-01-15 13:53:24 +00005017 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5018
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005019 if (!triggerRemoveFailed) {
5020 // Remove any previously queued triggers (after unlock)
5021 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5022 if (removeTriggerRes != OK) {
5023 triggerRemoveFailed = true;
5024 triggerFailedRequest = nextRequest;
5025 }
5026 }
5027 }
5028
5029 if (triggerRemoveFailed) {
5030 SET_ERR("RequestThread: Unable to remove triggers "
5031 "(capture request %d, HAL device: %s (%d)",
5032 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5033 cleanUpFailedRequests(/*sendRequestError*/ false);
5034 return false;
5035 }
5036
5037 if (res != OK) {
5038 // Should only get a failure here for malformed requests or device-level
5039 // errors, so consider all errors fatal. Bad metadata failures should
5040 // come through notify.
5041 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5042 mNextRequests[numRequestProcessed].halRequest.frame_number,
5043 strerror(-res), res);
5044 cleanUpFailedRequests(/*sendRequestError*/ false);
5045 return false;
5046 }
5047 return true;
5048}
5049
5050bool Camera3Device::RequestThread::sendRequestsOneByOne() {
5051 status_t res;
5052
5053 for (auto& nextRequest : mNextRequests) {
5054 // Submit request and block until ready for next one
5055 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
5056 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
5057
5058 if (res != OK) {
5059 // Should only get a failure here for malformed requests or device-level
5060 // errors, so consider all errors fatal. Bad metadata failures should
5061 // come through notify.
5062 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
5063 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
5064 res);
5065 cleanUpFailedRequests(/*sendRequestError*/ false);
5066 return false;
5067 }
5068
5069 // Mark that the request has be submitted successfully.
5070 nextRequest.submitted = true;
5071
5072 // Update the latest request sent to HAL
5073 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5074 Mutex::Autolock al(mLatestRequestMutex);
5075
5076 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5077 mLatestRequest.acquire(cloned);
5078
5079 sp<Camera3Device> parent = mParent.promote();
5080 if (parent != NULL) {
5081 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
5082 0, mLatestRequest);
5083 }
5084 }
5085
5086 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005087 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5088 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005089 }
5090
Emilian Peevaebbe412018-01-15 13:53:24 +00005091 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5092
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005093 // Remove any previously queued triggers (after unlock)
5094 res = removeTriggers(mPrevRequest);
5095 if (res != OK) {
5096 SET_ERR("RequestThread: Unable to remove triggers "
5097 "(capture request %d, HAL device: %s (%d)",
5098 nextRequest.halRequest.frame_number, strerror(-res), res);
5099 cleanUpFailedRequests(/*sendRequestError*/ false);
5100 return false;
5101 }
5102 }
5103 return true;
5104}
5105
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005106nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5107 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5108 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5109 find_camera_metadata_ro_entry(request,
5110 ANDROID_CONTROL_AE_MODE,
5111 &e);
5112 if (e.count == 0) return maxExpectedDuration;
5113
5114 switch (e.data.u8[0]) {
5115 case ANDROID_CONTROL_AE_MODE_OFF:
5116 find_camera_metadata_ro_entry(request,
5117 ANDROID_SENSOR_EXPOSURE_TIME,
5118 &e);
5119 if (e.count > 0) {
5120 maxExpectedDuration = e.data.i64[0];
5121 }
5122 find_camera_metadata_ro_entry(request,
5123 ANDROID_SENSOR_FRAME_DURATION,
5124 &e);
5125 if (e.count > 0) {
5126 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5127 }
5128 break;
5129 default:
5130 find_camera_metadata_ro_entry(request,
5131 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5132 &e);
5133 if (e.count > 1) {
5134 maxExpectedDuration = 1e9 / e.data.u8[0];
5135 }
5136 break;
5137 }
5138
5139 return maxExpectedDuration;
5140}
5141
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005142bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5143 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5144 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5145 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5146 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5147 return true;
5148 }
5149
5150 return false;
5151}
5152
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005153bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5154 ATRACE_CALL();
5155 bool updatesDetected = false;
5156
Emilian Peev4ec17882019-01-24 17:16:58 -08005157 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005158 for (auto tag : mSessionParamKeys) {
5159 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005160 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005161
5162 if (entry.count > 0) {
5163 bool isDifferent = false;
5164 if (lastEntry.count > 0) {
5165 // Have a last value, compare to see if changed
5166 if (lastEntry.type == entry.type &&
5167 lastEntry.count == entry.count) {
5168 // Same type and count, compare values
5169 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5170 size_t entryBytes = bytesPerValue * lastEntry.count;
5171 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5172 if (cmp != 0) {
5173 isDifferent = true;
5174 }
5175 } else {
5176 // Count or type has changed
5177 isDifferent = true;
5178 }
5179 } else {
5180 // No last entry, so always consider to be different
5181 isDifferent = true;
5182 }
5183
5184 if (isDifferent) {
5185 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005186 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5187 updatesDetected = true;
5188 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005189 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005190 }
5191 } else if (lastEntry.count > 0) {
5192 // Value has been removed
5193 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005194 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005195 updatesDetected = true;
5196 }
5197 }
5198
Emilian Peev4ec17882019-01-24 17:16:58 -08005199 bool reconfigureRequired;
5200 if (updatesDetected) {
5201 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5202 updatedParams);
5203 mLatestSessionParams = updatedParams;
5204 } else {
5205 reconfigureRequired = false;
5206 }
5207
5208 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005209}
5210
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005211bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005212 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005213 status_t res;
5214
5215 // Handle paused state.
5216 if (waitIfPaused()) {
5217 return true;
5218 }
5219
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005220 // Wait for the next batch of requests.
5221 waitForNextRequestBatch();
5222 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005223 return true;
5224 }
5225
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005226 // Get the latest request ID, if any
5227 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005228 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005229 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005230 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005231 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005232 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005233 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5234 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005235 }
5236
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005237 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5238 // or a single request from streaming or burst. In either case the first element
5239 // should contain the latest camera settings that we need to check for any session
5240 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005241 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005242 res = OK;
5243
5244 //Input stream buffers are already acquired at this point so an input stream
5245 //will not be able to move to idle state unless we force it.
5246 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5247 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5248 if (res != OK) {
5249 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5250 cleanUpFailedRequests(/*sendRequestError*/ false);
5251 return false;
5252 }
5253 }
5254
5255 if (res == OK) {
5256 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5257 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005258 sp<Camera3Device> parent = mParent.promote();
5259 if (parent != nullptr) {
5260 parent->pauseStateNotify(true);
5261 }
5262
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005263 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5264
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005265 if (parent != nullptr) {
5266 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5267 }
5268
5269 statusTracker->markComponentActive(mStatusId);
5270 setPaused(false);
5271 }
5272
5273 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5274 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5275 if (res != OK) {
5276 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5277 cleanUpFailedRequests(/*sendRequestError*/ false);
5278 return false;
5279 }
5280 }
5281 }
5282 }
5283
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005284 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005285 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005286 if (res == TIMED_OUT) {
5287 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005288 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005289 // Check if any stream is abandoned.
5290 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005291 return true;
5292 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005293 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005294 return false;
5295 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005296
Zhijun Hecc27e112013-10-03 16:12:43 -07005297 // Inform waitUntilRequestProcessed thread of a new request ID
5298 {
5299 Mutex::Autolock al(mLatestRequestMutex);
5300
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005301 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005302 mLatestRequestSignal.signal();
5303 }
5304
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005305 // Submit a batch of requests to HAL.
5306 // Use flush lock only when submitting multilple requests in a batch.
5307 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5308 // which may take a long time to finish so synchronizing flush() and
5309 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5310 // For now, only synchronize for high speed recording and we should figure something out for
5311 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005312 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005313
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005314 if (useFlushLock) {
5315 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005316 }
5317
Zhijun Hef0645c12016-08-02 00:58:11 -07005318 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005319 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005320
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005321 sp<Camera3Device> parent = mParent.promote();
5322 if (parent != nullptr) {
5323 parent->mRequestBufferSM.onSubmittingRequest();
5324 }
5325
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005326 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005327 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005328 if (mInterface->supportBatchRequest()) {
5329 submitRequestSuccess = sendRequestsBatch();
5330 } else {
5331 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005332 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005333 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5334 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005335
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005336 if (useFlushLock) {
5337 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005338 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005339
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005340 // Unset as current request
5341 {
5342 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005343 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005344 }
5345
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005346 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005347}
5348
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005349status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005350 ATRACE_CALL();
5351
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005352 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005353 for (size_t i = 0; i < mNextRequests.size(); i++) {
5354 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005355 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5356 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5357 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5358
5359 // Prepare a request to HAL
5360 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5361
5362 // Insert any queued triggers (before metadata is locked)
5363 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005364 if (res < 0) {
5365 SET_ERR("RequestThread: Unable to insert triggers "
5366 "(capture request %d, HAL device: %s (%d)",
5367 halRequest->frame_number, strerror(-res), res);
5368 return INVALID_OPERATION;
5369 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005370
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005371 int triggerCount = res;
5372 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5373 mPrevTriggers = triggerCount;
5374
5375 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005376 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5377 // Request settings are all the same within one batch, so only treat the first
5378 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005379 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005380 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005381 /**
5382 * HAL workaround:
5383 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5384 */
5385 res = addDummyTriggerIds(captureRequest);
5386 if (res != OK) {
5387 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5388 "(capture request %d, HAL device: %s (%d)",
5389 halRequest->frame_number, strerror(-res), res);
5390 return INVALID_OPERATION;
5391 }
5392
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005393 {
5394 // Correct metadata regions for distortion correction if enabled
5395 sp<Camera3Device> parent = mParent.promote();
5396 if (parent != nullptr) {
5397 res = parent->mDistortionMapper.correctCaptureRequest(
5398 &(captureRequest->mSettingsList.begin()->metadata));
5399 if (res != OK) {
5400 SET_ERR("RequestThread: Unable to correct capture requests "
5401 "for lens distortion for request %d: %s (%d)",
5402 halRequest->frame_number, strerror(-res), res);
5403 return INVALID_OPERATION;
5404 }
5405 }
5406 }
5407
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005408 /**
5409 * The request should be presorted so accesses in HAL
5410 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5411 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005412 captureRequest->mSettingsList.begin()->metadata.sort();
5413 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005414 mPrevRequest = captureRequest;
5415 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5416
5417 IF_ALOGV() {
5418 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5419 find_camera_metadata_ro_entry(
5420 halRequest->settings,
5421 ANDROID_CONTROL_AF_TRIGGER,
5422 &e
5423 );
5424 if (e.count > 0) {
5425 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5426 __FUNCTION__,
5427 halRequest->frame_number,
5428 e.data.u8[0]);
5429 }
5430 }
5431 } else {
5432 // leave request.settings NULL to indicate 'reuse latest given'
5433 ALOGVV("%s: Request settings are REUSED",
5434 __FUNCTION__);
5435 }
5436
Emilian Peevaebbe412018-01-15 13:53:24 +00005437 if (captureRequest->mSettingsList.size() > 1) {
5438 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5439 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005440 if (newRequest) {
5441 halRequest->physcam_settings =
5442 new const camera_metadata* [halRequest->num_physcam_settings];
5443 } else {
5444 halRequest->physcam_settings = nullptr;
5445 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005446 auto it = ++captureRequest->mSettingsList.begin();
5447 size_t i = 0;
5448 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5449 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005450 if (newRequest) {
5451 it->metadata.sort();
5452 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5453 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005454 }
5455 }
5456
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005457 uint32_t totalNumBuffers = 0;
5458
5459 // Fill in buffers
5460 if (captureRequest->mInputStream != NULL) {
5461 halRequest->input_buffer = &captureRequest->mInputBuffer;
5462 totalNumBuffers += 1;
5463 } else {
5464 halRequest->input_buffer = NULL;
5465 }
5466
5467 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5468 captureRequest->mOutputStreams.size());
5469 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005470 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005471
5472 sp<Camera3Device> parent = mParent.promote();
5473 if (parent == NULL) {
5474 // Should not happen, and nowhere to send errors to, so just log it
5475 CLOGE("RequestThread: Parent is gone");
5476 return INVALID_OPERATION;
5477 }
5478 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5479
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005480 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005481 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005482 sp<Camera3OutputStreamInterface> outputStream =
5483 captureRequest->mOutputStreams.editItemAt(j);
5484 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005485
5486 // Prepare video buffers for high speed recording on the first video request.
5487 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5488 // Only try to prepare video stream on the first video request.
5489 mPrepareVideoStream = false;
5490
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005491 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5492 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005493 while (res == NOT_ENOUGH_DATA) {
5494 res = outputStream->prepareNextBuffer();
5495 }
5496 if (res != OK) {
5497 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5498 __FUNCTION__, strerror(-res), res);
5499 outputStream->cancelPrepare();
5500 }
5501 }
5502
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005503 std::vector<size_t> uniqueSurfaceIds;
5504 res = outputStream->getUniqueSurfaceIds(
5505 captureRequest->mOutputSurfaces[streamId],
5506 &uniqueSurfaceIds);
5507 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5508 if (res != OK && res != INVALID_OPERATION) {
5509 ALOGE("%s: failed to query stream %d unique surface IDs",
5510 __FUNCTION__, streamId);
5511 return res;
5512 }
5513 if (res == OK) {
5514 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5515 }
5516
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005517 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005518 if (outputStream->isAbandoned()) {
5519 ALOGE("%s: stream %d is abandoned.", __FUNCTION__, streamId);
5520 return TIMED_OUT;
5521 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005522 // HAL will request buffer through requestStreamBuffer API
5523 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5524 buffer.stream = outputStream->asHalStream();
5525 buffer.buffer = nullptr;
5526 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5527 buffer.acquire_fence = -1;
5528 buffer.release_fence = -1;
5529 } else {
5530 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5531 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005532 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005533 if (res != OK) {
5534 // Can't get output buffer from gralloc queue - this could be due to
5535 // abandoned queue or other consumer misbehavior, so not a fatal
5536 // error
5537 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5538 " %s (%d)", strerror(-res), res);
5539
5540 return TIMED_OUT;
5541 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005542 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005543
5544 {
5545 sp<Camera3Device> parent = mParent.promote();
5546 if (parent != nullptr) {
5547 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5548 for (const auto& settings : captureRequest->mSettingsList) {
5549 if ((streamCameraId.isEmpty() &&
5550 parent->getId() == settings.cameraId.c_str()) ||
5551 streamCameraId == settings.cameraId.c_str()) {
5552 outputStream->fireBufferRequestForFrameNumber(
5553 captureRequest->mResultExtras.frameNumber,
5554 settings.metadata);
5555 }
5556 }
5557 }
5558 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005559
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005560 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5561
5562 if (!physicalCameraId.isEmpty()) {
5563 // Physical stream isn't supported for input request.
5564 if (halRequest->input_buffer) {
5565 CLOGE("Physical stream is not supported for input request");
5566 return INVALID_OPERATION;
5567 }
5568 requestedPhysicalCameras.insert(physicalCameraId);
5569 }
5570 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005571 }
5572 totalNumBuffers += halRequest->num_output_buffers;
5573
5574 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005575 // If this request list is for constrained high speed recording (not
5576 // preview), and the current request is not the last one in the batch,
5577 // do not send callback to the app.
5578 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005579 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005580 hasCallback = false;
5581 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005582 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005583 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005584 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5585 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5586 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5587 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5588 isStillCapture = true;
5589 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5590 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005591
5592 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5593 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5594 isZslCapture = true;
5595 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005596 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005597 res = parent->registerInFlight(halRequest->frame_number,
5598 totalNumBuffers, captureRequest->mResultExtras,
5599 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005600 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005601 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005602 requestedPhysicalCameras, isStillCapture, isZslCapture,
5603 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5604 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005605 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5606 ", burstId = %" PRId32 ".",
5607 __FUNCTION__,
5608 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5609 captureRequest->mResultExtras.burstId);
5610 if (res != OK) {
5611 SET_ERR("RequestThread: Unable to register new in-flight request:"
5612 " %s (%d)", strerror(-res), res);
5613 return INVALID_OPERATION;
5614 }
5615 }
5616
5617 return OK;
5618}
5619
Igor Murashkin1e479c02013-09-06 16:55:14 -07005620CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005621 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005622 Mutex::Autolock al(mLatestRequestMutex);
5623
5624 ALOGV("RequestThread::%s", __FUNCTION__);
5625
5626 return mLatestRequest;
5627}
5628
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005629bool Camera3Device::RequestThread::isStreamPending(
5630 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005631 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005632 Mutex::Autolock l(mRequestLock);
5633
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005634 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005635 if (!nextRequest.submitted) {
5636 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5637 if (stream == s) return true;
5638 }
5639 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005640 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005641 }
5642
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005643 for (const auto& request : mRequestQueue) {
5644 for (const auto& s : request->mOutputStreams) {
5645 if (stream == s) return true;
5646 }
5647 if (stream == request->mInputStream) return true;
5648 }
5649
5650 for (const auto& request : mRepeatingRequests) {
5651 for (const auto& s : request->mOutputStreams) {
5652 if (stream == s) return true;
5653 }
5654 if (stream == request->mInputStream) return true;
5655 }
5656
5657 return false;
5658}
Jianing Weicb0652e2014-03-12 18:29:36 -07005659
Emilian Peev40ead602017-09-26 15:46:36 +01005660bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5661 ATRACE_CALL();
5662 Mutex::Autolock l(mRequestLock);
5663
5664 for (const auto& nextRequest : mNextRequests) {
5665 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5666 if (s.first == streamId) {
5667 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5668 if (it != s.second.end()) {
5669 return true;
5670 }
5671 }
5672 }
5673 }
5674
5675 for (const auto& request : mRequestQueue) {
5676 for (const auto& s : request->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()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005680 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005681 }
5682 }
5683 }
5684 }
5685
5686 for (const auto& request : mRepeatingRequests) {
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 return false;
5698}
5699
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005700void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5701 if (!mUseHalBufManager) {
5702 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5703 return;
5704 }
5705
5706 Mutex::Autolock pl(mPauseLock);
5707 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005708 mInterface->signalPipelineDrain(streamIds);
5709 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005710 }
5711 // If request thread is still busy, wait until paused then notify HAL
5712 mNotifyPipelineDrain = true;
5713 mStreamIdsToBeDrained = streamIds;
5714}
5715
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005716nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005717 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005718 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005719 return mExpectedInflightDuration > kMinInflightDuration ?
5720 mExpectedInflightDuration : kMinInflightDuration;
5721}
5722
Emilian Peevaebbe412018-01-15 13:53:24 +00005723void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5724 camera3_capture_request_t *halRequest) {
5725 if ((request == nullptr) || (halRequest == nullptr)) {
5726 ALOGE("%s: Invalid request!", __FUNCTION__);
5727 return;
5728 }
5729
5730 if (halRequest->num_physcam_settings > 0) {
5731 if (halRequest->physcam_id != nullptr) {
5732 delete [] halRequest->physcam_id;
5733 halRequest->physcam_id = nullptr;
5734 }
5735 if (halRequest->physcam_settings != nullptr) {
5736 auto it = ++(request->mSettingsList.begin());
5737 size_t i = 0;
5738 for (; it != request->mSettingsList.end(); it++, i++) {
5739 it->metadata.unlock(halRequest->physcam_settings[i]);
5740 }
5741 delete [] halRequest->physcam_settings;
5742 halRequest->physcam_settings = nullptr;
5743 }
5744 }
5745}
5746
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005747void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5748 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005749 return;
5750 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005751
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005752 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005753 // Skip the ones that have been submitted successfully.
5754 if (nextRequest.submitted) {
5755 continue;
5756 }
5757
5758 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5759 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5760 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5761
5762 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005763 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005764 }
5765
Emilian Peevaebbe412018-01-15 13:53:24 +00005766 cleanupPhysicalSettings(captureRequest, halRequest);
5767
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005768 if (captureRequest->mInputStream != NULL) {
5769 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5770 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5771 }
5772
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005773 // No output buffer can be returned when using HAL buffer manager
5774 if (!mUseHalBufManager) {
5775 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5776 //Buffers that failed processing could still have
5777 //valid acquire fence.
5778 int acquireFence = (*outputBuffers)[i].acquire_fence;
5779 if (0 <= acquireFence) {
5780 close(acquireFence);
5781 outputBuffers->editItemAt(i).acquire_fence = -1;
5782 }
5783 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5784 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5785 /*timestampIncreasing*/true, std::vector<size_t> (),
5786 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005787 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005788 }
5789
5790 if (sendRequestError) {
5791 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005792 sp<NotificationListener> listener = mListener.promote();
5793 if (listener != NULL) {
5794 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005795 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005796 captureRequest->mResultExtras);
5797 }
5798 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005799
5800 // Remove yet-to-be submitted inflight request from inflightMap
5801 {
5802 sp<Camera3Device> parent = mParent.promote();
5803 if (parent != NULL) {
5804 Mutex::Autolock l(parent->mInFlightLock);
5805 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5806 if (idx >= 0) {
5807 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5808 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5809 parent->removeInFlightMapEntryLocked(idx);
5810 }
5811 }
5812 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005813 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005814
5815 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005816 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005817}
5818
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005819void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005820 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005821 // Optimized a bit for the simple steady-state case (single repeating
5822 // request), to avoid putting that request in the queue temporarily.
5823 Mutex::Autolock l(mRequestLock);
5824
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005825 assert(mNextRequests.empty());
5826
5827 NextRequest nextRequest;
5828 nextRequest.captureRequest = waitForNextRequestLocked();
5829 if (nextRequest.captureRequest == nullptr) {
5830 return;
5831 }
5832
5833 nextRequest.halRequest = camera3_capture_request_t();
5834 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005835 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005836
5837 // Wait for additional requests
5838 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5839
5840 for (size_t i = 1; i < batchSize; i++) {
5841 NextRequest additionalRequest;
5842 additionalRequest.captureRequest = waitForNextRequestLocked();
5843 if (additionalRequest.captureRequest == nullptr) {
5844 break;
5845 }
5846
5847 additionalRequest.halRequest = camera3_capture_request_t();
5848 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005849 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005850 }
5851
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005852 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005853 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005854 mNextRequests.size(), batchSize);
5855 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005856 }
5857
5858 return;
5859}
5860
5861sp<Camera3Device::CaptureRequest>
5862 Camera3Device::RequestThread::waitForNextRequestLocked() {
5863 status_t res;
5864 sp<CaptureRequest> nextRequest;
5865
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005866 while (mRequestQueue.empty()) {
5867 if (!mRepeatingRequests.empty()) {
5868 // Always atomically enqueue all requests in a repeating request
5869 // list. Guarantees a complete in-sequence set of captures to
5870 // application.
5871 const RequestList &requests = mRepeatingRequests;
5872 RequestList::const_iterator firstRequest =
5873 requests.begin();
5874 nextRequest = *firstRequest;
5875 mRequestQueue.insert(mRequestQueue.end(),
5876 ++firstRequest,
5877 requests.end());
5878 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005879
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005880 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005881
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005882 break;
5883 }
5884
5885 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5886
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005887 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5888 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005889 Mutex::Autolock pl(mPauseLock);
5890 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005891 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005892 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005893 // Let the tracker know
5894 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5895 if (statusTracker != 0) {
5896 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5897 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005898 if (mNotifyPipelineDrain) {
5899 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5900 mNotifyPipelineDrain = false;
5901 mStreamIdsToBeDrained.clear();
5902 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005903 sp<Camera3Device> parent = mParent.promote();
5904 if (parent != nullptr) {
5905 parent->mRequestBufferSM.onRequestThreadPaused();
5906 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005907 }
5908 // Stop waiting for now and let thread management happen
5909 return NULL;
5910 }
5911 }
5912
5913 if (nextRequest == NULL) {
5914 // Don't have a repeating request already in hand, so queue
5915 // must have an entry now.
5916 RequestList::iterator firstRequest =
5917 mRequestQueue.begin();
5918 nextRequest = *firstRequest;
5919 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005920 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5921 sp<NotificationListener> listener = mListener.promote();
5922 if (listener != NULL) {
5923 listener->notifyRequestQueueEmpty();
5924 }
5925 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005926 }
5927
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005928 // In case we've been unpaused by setPaused clearing mDoPause, need to
5929 // update internal pause state (capture/setRepeatingRequest unpause
5930 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005931 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005932 if (mPaused) {
5933 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5934 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5935 if (statusTracker != 0) {
5936 statusTracker->markComponentActive(mStatusId);
5937 }
5938 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005939 mPaused = false;
5940
5941 // Check if we've reconfigured since last time, and reset the preview
5942 // request if so. Can't use 'NULL request == repeat' across configure calls.
5943 if (mReconfigured) {
5944 mPrevRequest.clear();
5945 mReconfigured = false;
5946 }
5947
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005948 if (nextRequest != NULL) {
5949 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005950 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5951 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005952
5953 // Since RequestThread::clear() removes buffers from the input stream,
5954 // get the right buffer here before unlocking mRequestLock
5955 if (nextRequest->mInputStream != NULL) {
5956 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5957 if (res != OK) {
5958 // Can't get input buffer from gralloc queue - this could be due to
5959 // disconnected queue or other producer misbehavior, so not a fatal
5960 // error
5961 ALOGE("%s: Can't get input buffer, skipping request:"
5962 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005963
5964 sp<NotificationListener> listener = mListener.promote();
5965 if (listener != NULL) {
5966 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005967 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005968 nextRequest->mResultExtras);
5969 }
5970 return NULL;
5971 }
5972 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005973 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005974
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005975 return nextRequest;
5976}
5977
5978bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005979 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005980 status_t res;
5981 Mutex::Autolock l(mPauseLock);
5982 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005983 if (mPaused == false) {
5984 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005985 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5986 // Let the tracker know
5987 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5988 if (statusTracker != 0) {
5989 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5990 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005991 if (mNotifyPipelineDrain) {
5992 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5993 mNotifyPipelineDrain = false;
5994 mStreamIdsToBeDrained.clear();
5995 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005996 sp<Camera3Device> parent = mParent.promote();
5997 if (parent != nullptr) {
5998 parent->mRequestBufferSM.onRequestThreadPaused();
5999 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006000 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006001
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006002 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006003 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006004 return true;
6005 }
6006 }
6007 // We don't set mPaused to false here, because waitForNextRequest needs
6008 // to further manage the paused state in case of starvation.
6009 return false;
6010}
6011
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006012void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006013 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006014 // With work to do, mark thread as unpaused.
6015 // If paused by request (setPaused), don't resume, to avoid
6016 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006017 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006018 Mutex::Autolock p(mPauseLock);
6019 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006020 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6021 if (mPaused) {
6022 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6023 if (statusTracker != 0) {
6024 statusTracker->markComponentActive(mStatusId);
6025 }
6026 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006027 mPaused = false;
6028 }
6029}
6030
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006031void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6032 sp<Camera3Device> parent = mParent.promote();
6033 if (parent != NULL) {
6034 va_list args;
6035 va_start(args, fmt);
6036
6037 parent->setErrorStateV(fmt, args);
6038
6039 va_end(args);
6040 }
6041}
6042
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006043status_t Camera3Device::RequestThread::insertTriggers(
6044 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006045 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006046 Mutex::Autolock al(mTriggerMutex);
6047
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006048 sp<Camera3Device> parent = mParent.promote();
6049 if (parent == NULL) {
6050 CLOGE("RequestThread: Parent is gone");
6051 return DEAD_OBJECT;
6052 }
6053
Emilian Peevaebbe412018-01-15 13:53:24 +00006054 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006055 size_t count = mTriggerMap.size();
6056
6057 for (size_t i = 0; i < count; ++i) {
6058 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006059 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006060
6061 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6062 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6063 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006064 if (isAeTrigger) {
6065 request->mResultExtras.precaptureTriggerId = triggerId;
6066 mCurrentPreCaptureTriggerId = triggerId;
6067 } else {
6068 request->mResultExtras.afTriggerId = triggerId;
6069 mCurrentAfTriggerId = triggerId;
6070 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006071 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006072 }
6073
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006074 camera_metadata_entry entry = metadata.find(tag);
6075
6076 if (entry.count > 0) {
6077 /**
6078 * Already has an entry for this trigger in the request.
6079 * Rewrite it with our requested trigger value.
6080 */
6081 RequestTrigger oldTrigger = trigger;
6082
6083 oldTrigger.entryValue = entry.data.u8[0];
6084
6085 mTriggerReplacedMap.add(tag, oldTrigger);
6086 } else {
6087 /**
6088 * More typical, no trigger entry, so we just add it
6089 */
6090 mTriggerRemovedMap.add(tag, trigger);
6091 }
6092
6093 status_t res;
6094
6095 switch (trigger.getTagType()) {
6096 case TYPE_BYTE: {
6097 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6098 res = metadata.update(tag,
6099 &entryValue,
6100 /*count*/1);
6101 break;
6102 }
6103 case TYPE_INT32:
6104 res = metadata.update(tag,
6105 &trigger.entryValue,
6106 /*count*/1);
6107 break;
6108 default:
6109 ALOGE("%s: Type not supported: 0x%x",
6110 __FUNCTION__,
6111 trigger.getTagType());
6112 return INVALID_OPERATION;
6113 }
6114
6115 if (res != OK) {
6116 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6117 ", value %d", __FUNCTION__, trigger.getTagName(),
6118 trigger.entryValue);
6119 return res;
6120 }
6121
6122 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6123 trigger.getTagName(),
6124 trigger.entryValue);
6125 }
6126
6127 mTriggerMap.clear();
6128
6129 return count;
6130}
6131
6132status_t Camera3Device::RequestThread::removeTriggers(
6133 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006134 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006135 Mutex::Autolock al(mTriggerMutex);
6136
Emilian Peevaebbe412018-01-15 13:53:24 +00006137 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006138
6139 /**
6140 * Replace all old entries with their old values.
6141 */
6142 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6143 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6144
6145 status_t res;
6146
6147 uint32_t tag = trigger.metadataTag;
6148 switch (trigger.getTagType()) {
6149 case TYPE_BYTE: {
6150 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6151 res = metadata.update(tag,
6152 &entryValue,
6153 /*count*/1);
6154 break;
6155 }
6156 case TYPE_INT32:
6157 res = metadata.update(tag,
6158 &trigger.entryValue,
6159 /*count*/1);
6160 break;
6161 default:
6162 ALOGE("%s: Type not supported: 0x%x",
6163 __FUNCTION__,
6164 trigger.getTagType());
6165 return INVALID_OPERATION;
6166 }
6167
6168 if (res != OK) {
6169 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6170 ", trigger value %d", __FUNCTION__,
6171 trigger.getTagName(), trigger.entryValue);
6172 return res;
6173 }
6174 }
6175 mTriggerReplacedMap.clear();
6176
6177 /**
6178 * Remove all new entries.
6179 */
6180 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6181 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6182 status_t res = metadata.erase(trigger.metadataTag);
6183
6184 if (res != OK) {
6185 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6186 ", trigger value %d", __FUNCTION__,
6187 trigger.getTagName(), trigger.entryValue);
6188 return res;
6189 }
6190 }
6191 mTriggerRemovedMap.clear();
6192
6193 return OK;
6194}
6195
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006196status_t Camera3Device::RequestThread::addDummyTriggerIds(
6197 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006198 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006199 static const int32_t dummyTriggerId = 1;
6200 status_t res;
6201
Emilian Peevaebbe412018-01-15 13:53:24 +00006202 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006203
6204 // If AF trigger is active, insert a dummy AF trigger ID if none already
6205 // exists
6206 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6207 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6208 if (afTrigger.count > 0 &&
6209 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6210 afId.count == 0) {
6211 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6212 if (res != OK) return res;
6213 }
6214
6215 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6216 // if none already exists
6217 camera_metadata_entry pcTrigger =
6218 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6219 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6220 if (pcTrigger.count > 0 &&
6221 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6222 pcId.count == 0) {
6223 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6224 &dummyTriggerId, 1);
6225 if (res != OK) return res;
6226 }
6227
6228 return OK;
6229}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006230
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006231/**
6232 * PreparerThread inner class methods
6233 */
6234
6235Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006236 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006237 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006238}
6239
6240Camera3Device::PreparerThread::~PreparerThread() {
6241 Thread::requestExitAndWait();
6242 if (mCurrentStream != nullptr) {
6243 mCurrentStream->cancelPrepare();
6244 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6245 mCurrentStream.clear();
6246 }
6247 clear();
6248}
6249
Ruben Brunkc78ac262015-08-13 17:58:46 -07006250status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006251 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006252 status_t res;
6253
6254 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006255 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006256
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006257 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006258 if (res == OK) {
6259 // No preparation needed, fire listener right off
6260 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006261 if (listener != NULL) {
6262 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006263 }
6264 return OK;
6265 } else if (res != NOT_ENOUGH_DATA) {
6266 return res;
6267 }
6268
6269 // Need to prepare, start up thread if necessary
6270 if (!mActive) {
6271 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6272 // isn't running
6273 Thread::requestExitAndWait();
6274 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6275 if (res != OK) {
6276 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006277 if (listener != NULL) {
6278 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006279 }
6280 return res;
6281 }
6282 mCancelNow = false;
6283 mActive = true;
6284 ALOGV("%s: Preparer stream started", __FUNCTION__);
6285 }
6286
6287 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006288 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006289 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6290
6291 return OK;
6292}
6293
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006294void Camera3Device::PreparerThread::pause() {
6295 ATRACE_CALL();
6296
6297 Mutex::Autolock l(mLock);
6298
6299 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6300 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6301 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6302 int currentMaxCount = mCurrentMaxCount;
6303 mPendingStreams.clear();
6304 mCancelNow = true;
6305 while (mActive) {
6306 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6307 if (res == TIMED_OUT) {
6308 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6309 return;
6310 } else if (res != OK) {
6311 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6312 return;
6313 }
6314 }
6315
6316 //Check whether the prepare thread was able to complete the current
6317 //stream. In case work is still pending emplace it along with the rest
6318 //of the streams in the pending list.
6319 if (currentStream != nullptr) {
6320 if (!mCurrentPrepareComplete) {
6321 pendingStreams.emplace(currentMaxCount, currentStream);
6322 }
6323 }
6324
6325 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6326 for (const auto& it : mPendingStreams) {
6327 it.second->cancelPrepare();
6328 }
6329}
6330
6331status_t Camera3Device::PreparerThread::resume() {
6332 ATRACE_CALL();
6333 status_t res;
6334
6335 Mutex::Autolock l(mLock);
6336 sp<NotificationListener> listener = mListener.promote();
6337
6338 if (mActive) {
6339 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6340 return NO_INIT;
6341 }
6342
6343 auto it = mPendingStreams.begin();
6344 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006345 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006346 if (res == OK) {
6347 if (listener != NULL) {
6348 listener->notifyPrepared(it->second->getId());
6349 }
6350 it = mPendingStreams.erase(it);
6351 } else if (res != NOT_ENOUGH_DATA) {
6352 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6353 res, strerror(-res));
6354 it = mPendingStreams.erase(it);
6355 } else {
6356 it++;
6357 }
6358 }
6359
6360 if (mPendingStreams.empty()) {
6361 return OK;
6362 }
6363
6364 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6365 if (res != OK) {
6366 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6367 __FUNCTION__, res, strerror(-res));
6368 return res;
6369 }
6370 mCancelNow = false;
6371 mActive = true;
6372 ALOGV("%s: Preparer stream started", __FUNCTION__);
6373
6374 return OK;
6375}
6376
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006377status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006378 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006379 Mutex::Autolock l(mLock);
6380
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006381 for (const auto& it : mPendingStreams) {
6382 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006383 }
6384 mPendingStreams.clear();
6385 mCancelNow = true;
6386
6387 return OK;
6388}
6389
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006390void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006391 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006392 Mutex::Autolock l(mLock);
6393 mListener = listener;
6394}
6395
6396bool Camera3Device::PreparerThread::threadLoop() {
6397 status_t res;
6398 {
6399 Mutex::Autolock l(mLock);
6400 if (mCurrentStream == nullptr) {
6401 // End thread if done with work
6402 if (mPendingStreams.empty()) {
6403 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6404 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6405 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6406 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006407 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006408 return false;
6409 }
6410
6411 // Get next stream to prepare
6412 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006413 mCurrentStream = it->second;
6414 mCurrentMaxCount = it->first;
6415 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006416 mPendingStreams.erase(it);
6417 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6418 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6419 } else if (mCancelNow) {
6420 mCurrentStream->cancelPrepare();
6421 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6422 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6423 mCurrentStream.clear();
6424 mCancelNow = false;
6425 return true;
6426 }
6427 }
6428
6429 res = mCurrentStream->prepareNextBuffer();
6430 if (res == NOT_ENOUGH_DATA) return true;
6431 if (res != OK) {
6432 // Something bad happened; try to recover by cancelling prepare and
6433 // signalling listener anyway
6434 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6435 mCurrentStream->getId(), res, strerror(-res));
6436 mCurrentStream->cancelPrepare();
6437 }
6438
6439 // This stream has finished, notify listener
6440 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006441 sp<NotificationListener> listener = mListener.promote();
6442 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006443 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6444 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006445 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006446 }
6447
6448 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6449 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006450 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006451
6452 return true;
6453}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006454
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006455status_t Camera3Device::RequestBufferStateMachine::initialize(
6456 sp<camera3::StatusTracker> statusTracker) {
6457 if (statusTracker == nullptr) {
6458 ALOGE("%s: statusTracker is null", __FUNCTION__);
6459 return BAD_VALUE;
6460 }
6461
6462 std::lock_guard<std::mutex> lock(mLock);
6463 mStatusTracker = statusTracker;
6464 mRequestBufferStatusId = statusTracker->addComponent();
6465 return OK;
6466}
6467
6468bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6469 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006470 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006471 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006472 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006473 return true;
6474 }
6475 return false;
6476}
6477
6478void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6479 std::lock_guard<std::mutex> lock(mLock);
6480 if (!mRequestBufferOngoing) {
6481 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6482 return;
6483 }
6484 mRequestBufferOngoing = false;
6485 if (mStatus == RB_STATUS_PENDING_STOP) {
6486 checkSwitchToStopLocked();
6487 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006488 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006489}
6490
6491void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6492 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006493 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006494 return;
6495}
6496
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006497void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006498 std::lock_guard<std::mutex> lock(mLock);
6499 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006500 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6501 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006502 mInflightMapEmpty = false;
6503 if (mStatus == RB_STATUS_STOPPED) {
6504 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006505 }
6506 return;
6507}
6508
6509void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6510 std::lock_guard<std::mutex> lock(mLock);
6511 mRequestThreadPaused = true;
6512 if (mStatus == RB_STATUS_PENDING_STOP) {
6513 checkSwitchToStopLocked();
6514 }
6515 return;
6516}
6517
6518void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6519 std::lock_guard<std::mutex> lock(mLock);
6520 mInflightMapEmpty = true;
6521 if (mStatus == RB_STATUS_PENDING_STOP) {
6522 checkSwitchToStopLocked();
6523 }
6524 return;
6525}
6526
6527void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6528 std::lock_guard<std::mutex> lock(mLock);
6529 if (!checkSwitchToStopLocked()) {
6530 mStatus = RB_STATUS_PENDING_STOP;
6531 }
6532 return;
6533}
6534
6535void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6536 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6537 if (statusTracker != nullptr) {
6538 if (active) {
6539 statusTracker->markComponentActive(mRequestBufferStatusId);
6540 } else {
6541 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6542 }
6543 }
6544}
6545
6546bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6547 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6548 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006549 return true;
6550 }
6551 return false;
6552}
6553
Shuzhen Wang268a1362018-10-16 16:32:59 -07006554status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6555 CameraMetadata& resultMetadata) {
6556 status_t res = OK;
6557 if (!mNeedFixupMonochromeTags) {
6558 return res;
6559 }
6560
6561 // Remove tags that are not applicable to monochrome camera.
6562 int32_t tagsToRemove[] = {
6563 ANDROID_SENSOR_GREEN_SPLIT,
6564 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6565 ANDROID_COLOR_CORRECTION_MODE,
6566 ANDROID_COLOR_CORRECTION_TRANSFORM,
6567 ANDROID_COLOR_CORRECTION_GAINS,
6568 };
6569 for (auto tag : tagsToRemove) {
6570 res = resultMetadata.erase(tag);
6571 if (res != OK) {
6572 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6573 return res;
6574 }
6575 }
6576
6577 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6578 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6579 for (size_t i = 1; i < blEntry.count; i++) {
6580 blEntry.data.f[i] = blEntry.data.f[0];
6581 }
6582
6583 // ANDROID_SENSOR_NOISE_PROFILE
6584 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6585 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6586 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6587 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6588 if (res != OK) {
6589 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6590 __FUNCTION__, strerror(-res), res);
6591 return res;
6592 }
6593 }
6594
6595 // ANDROID_STATISTICS_LENS_SHADING_MAP
6596 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6597 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6598 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6599 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6600 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6601 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6602 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6603 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6604 }
6605 }
6606
6607 // ANDROID_TONEMAP_CURVE_BLUE
6608 // ANDROID_TONEMAP_CURVE_GREEN
6609 // ANDROID_TONEMAP_CURVE_RED
6610 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6611 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6612 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6613 if (tcbEntry.count > 0
6614 && tcbEntry.count == tcgEntry.count
6615 && tcbEntry.count == tcrEntry.count) {
6616 for (size_t i = 0; i < tcbEntry.count; i++) {
6617 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6618 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6619 }
6620 }
6621
6622 return res;
6623}
6624
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006625}; // namespace android