blob: 2b39254d08af68d5eaee5b13a79fd563de6933dc [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
Jianing Weicb0652e2014-03-12 18:29:36 -0700888status_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
Emilian Peevaebbe412018-01-15 13:53:24 +0000895 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
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),
3893 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003894 // Check with hardware service manager if we can downcast these interfaces
3895 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003896 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3897 if (castResult_3_5.isOk()) {
3898 mHidlSession_3_5 = castResult_3_5;
3899 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003900 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3901 if (castResult_3_4.isOk()) {
3902 mHidlSession_3_4 = castResult_3_4;
3903 }
3904 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3905 if (castResult_3_3.isOk()) {
3906 mHidlSession_3_3 = castResult_3_3;
3907 }
3908}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003909
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003910Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003911
3912Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003913 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003914 mRequestMetadataQueue(other.mRequestMetadataQueue),
3915 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003916
3917bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003918 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003919}
3920
3921void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00003922 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003923 mHidlSession_3_4.clear();
3924 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003925 mHidlSession.clear();
3926}
3927
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003928bool Camera3Device::HalInterface::supportBatchRequest() {
3929 return mHidlSession != nullptr;
3930}
3931
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003932status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3933 camera3_request_template_t templateId,
3934 /*out*/ camera_metadata_t **requestTemplate) {
3935 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3936 if (!valid()) return INVALID_OPERATION;
3937 status_t res = OK;
3938
Emilian Peev31abd0a2017-05-11 18:37:46 +01003939 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003940
3941 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003942 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003943 status = s;
3944 if (status == common::V1_0::Status::OK) {
3945 const camera_metadata *r =
3946 reinterpret_cast<const camera_metadata_t*>(request.data());
3947 size_t expectedSize = request.size();
3948 int ret = validate_camera_metadata_structure(r, &expectedSize);
3949 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3950 *requestTemplate = clone_camera_metadata(r);
3951 if (*requestTemplate == nullptr) {
3952 ALOGE("%s: Unable to clone camera metadata received from HAL",
3953 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003954 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003955 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003956 } else {
3957 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3958 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003959 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003960 }
3961 };
3962 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003963 RequestTemplate id;
3964 switch (templateId) {
3965 case CAMERA3_TEMPLATE_PREVIEW:
3966 id = RequestTemplate::PREVIEW;
3967 break;
3968 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3969 id = RequestTemplate::STILL_CAPTURE;
3970 break;
3971 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3972 id = RequestTemplate::VIDEO_RECORD;
3973 break;
3974 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3975 id = RequestTemplate::VIDEO_SNAPSHOT;
3976 break;
3977 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3978 id = RequestTemplate::ZERO_SHUTTER_LAG;
3979 break;
3980 case CAMERA3_TEMPLATE_MANUAL:
3981 id = RequestTemplate::MANUAL;
3982 break;
3983 default:
3984 // Unknown template ID, or this HAL is too old to support it
3985 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003986 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003987 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003988
Emilian Peev31abd0a2017-05-11 18:37:46 +01003989 if (!err.isOk()) {
3990 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3991 res = DEAD_OBJECT;
3992 } else {
3993 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003994 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003995
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003996 return res;
3997}
3998
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003999status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004000 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004001 ATRACE_NAME("CameraHal::configureStreams");
4002 if (!valid()) return INVALID_OPERATION;
4003 status_t res = OK;
4004
Emilian Peev31abd0a2017-05-11 18:37:46 +01004005 // Convert stream config to HIDL
4006 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004007 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4008 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4009 requestedConfiguration3_2.streams.resize(config->num_streams);
4010 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004011 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004012 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4013 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004014 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004015
Emilian Peev31abd0a2017-05-11 18:37:46 +01004016 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4017 cam3stream->setBufferFreedListener(this);
4018 int streamId = cam3stream->getId();
4019 StreamType streamType;
4020 switch (src->stream_type) {
4021 case CAMERA3_STREAM_OUTPUT:
4022 streamType = StreamType::OUTPUT;
4023 break;
4024 case CAMERA3_STREAM_INPUT:
4025 streamType = StreamType::INPUT;
4026 break;
4027 default:
4028 ALOGE("%s: Stream %d: Unsupported stream type %d",
4029 __FUNCTION__, streamId, config->streams[i]->stream_type);
4030 return BAD_VALUE;
4031 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004032 dst3_2.id = streamId;
4033 dst3_2.streamType = streamType;
4034 dst3_2.width = src->width;
4035 dst3_2.height = src->height;
4036 dst3_2.format = mapToPixelFormat(src->format);
4037 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
4038 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4039 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
4040 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004041 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004042 if (src->physical_camera_id != nullptr) {
4043 dst3_4.physicalCameraId = src->physical_camera_id;
4044 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004045
4046 activeStreams.insert(streamId);
4047 // Create Buffer ID map if necessary
4048 if (mBufferIdMaps.count(streamId) == 0) {
4049 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4050 }
4051 }
4052 // remove BufferIdMap for deleted streams
4053 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4054 int streamId = it->first;
4055 bool active = activeStreams.count(streamId) > 0;
4056 if (!active) {
4057 it = mBufferIdMaps.erase(it);
4058 } else {
4059 ++it;
4060 }
4061 }
4062
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004063 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004064 res = mapToStreamConfigurationMode(
4065 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004066 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004067 if (res != OK) {
4068 return res;
4069 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004070 requestedConfiguration3_2.operationMode = operationMode;
4071 requestedConfiguration3_4.operationMode = operationMode;
4072 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004073 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4074 get_camera_metadata_size(sessionParams));
4075
Emilian Peev31abd0a2017-05-11 18:37:46 +01004076 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004077 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004078 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004079 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004080
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004081 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004082 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4083 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004084 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004085 };
4086
4087 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4088 (hardware::Return<void>& err) -> status_t {
4089 if (!err.isOk()) {
4090 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4091 return DEAD_OBJECT;
4092 }
4093 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4094 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4095 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4096 }
4097 return OK;
4098 };
4099
4100 // See if we have v3.4 or v3.3 HAL
4101 if (mHidlSession_3_5 != nullptr) {
4102 ALOGV("%s: v3.5 device found", __FUNCTION__);
4103 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4104 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4105 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4106 auto err = mHidlSession_3_5->configureStreams_3_5(
4107 requestedConfiguration3_5, configStream34Cb);
4108 res = postprocConfigStream34(err);
4109 if (res != OK) {
4110 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004111 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004112 } else if (mHidlSession_3_4 != nullptr) {
4113 // We do; use v3.4 for the call
4114 ALOGV("%s: v3.4 device found", __FUNCTION__);
4115 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
4116 auto err = mHidlSession_3_4->configureStreams_3_4(
4117 requestedConfiguration3_4, configStream34Cb);
4118 res = postprocConfigStream34(err);
4119 if (res != OK) {
4120 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004121 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004122 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004123 // We do; use v3.3 for the call
4124 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004125 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004126 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004127 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004128 finalConfiguration = halConfiguration;
4129 status = s;
4130 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004131 if (!err.isOk()) {
4132 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4133 return DEAD_OBJECT;
4134 }
4135 } else {
4136 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4137 ALOGV("%s: v3.2 device found", __FUNCTION__);
4138 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004139 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004140 [&status, &finalConfiguration_3_2]
4141 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4142 finalConfiguration_3_2 = halConfiguration;
4143 status = s;
4144 });
4145 if (!err.isOk()) {
4146 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4147 return DEAD_OBJECT;
4148 }
4149 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4150 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4151 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4152 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004153 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004154 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004155 }
4156
4157 if (status != common::V1_0::Status::OK ) {
4158 return CameraProviderManager::mapToStatusT(status);
4159 }
4160
4161 // And convert output stream configuration from HIDL
4162
4163 for (size_t i = 0; i < config->num_streams; i++) {
4164 camera3_stream_t *dst = config->streams[i];
4165 int streamId = Camera3Stream::cast(dst)->getId();
4166
4167 // Start scan at i, with the assumption that the stream order matches
4168 size_t realIdx = i;
4169 bool found = false;
4170 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004171 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004172 found = true;
4173 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004174 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004175 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4176 }
4177 if (!found) {
4178 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4179 __FUNCTION__, streamId);
4180 return INVALID_OPERATION;
4181 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004182 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004183
Emilian Peev710c1422017-08-30 11:19:38 +01004184 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4185 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004186 dstStream->setDataSpaceOverride(false);
4187 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4188 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4189
Emilian Peev31abd0a2017-05-11 18:37:46 +01004190 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4191 if (dst->format != overrideFormat) {
4192 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4193 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004194 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004195 if (dst->data_space != overrideDataSpace) {
4196 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4197 streamId, dst->format);
4198 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004199 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004200 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004201 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4202
Emilian Peev31abd0a2017-05-11 18:37:46 +01004203 // Override allowed with IMPLEMENTATION_DEFINED
4204 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004205 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004206 }
4207
Emilian Peev31abd0a2017-05-11 18:37:46 +01004208 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004209 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004210 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004211 __FUNCTION__, streamId);
4212 return INVALID_OPERATION;
4213 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004214 dstStream->setUsage(
4215 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004216 } else {
4217 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004218 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004219 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4220 __FUNCTION__, streamId);
4221 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004222 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004223 dstStream->setUsage(
4224 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004225 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004226 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004227 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004228
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004229 return res;
4230}
4231
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004232status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004233 /*out*/device::V3_2::CaptureRequest* captureRequest,
4234 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004235 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004236 if (captureRequest == nullptr || handlesCreated == nullptr) {
4237 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4238 __FUNCTION__, captureRequest, handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004239 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004240 }
4241
4242 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004243
4244 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004245
4246 {
4247 std::lock_guard<std::mutex> lock(mInflightLock);
4248 if (request->input_buffer != nullptr) {
4249 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4250 buffer_handle_t buf = *(request->input_buffer->buffer);
4251 auto pair = getBufferId(buf, streamId);
4252 bool isNewBuffer = pair.first;
4253 uint64_t bufferId = pair.second;
4254 captureRequest->inputBuffer.streamId = streamId;
4255 captureRequest->inputBuffer.bufferId = bufferId;
4256 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4257 captureRequest->inputBuffer.status = BufferStatus::OK;
4258 native_handle_t *acquireFence = nullptr;
4259 if (request->input_buffer->acquire_fence != -1) {
4260 acquireFence = native_handle_create(1,0);
4261 acquireFence->data[0] = request->input_buffer->acquire_fence;
4262 handlesCreated->push_back(acquireFence);
4263 }
4264 captureRequest->inputBuffer.acquireFence = acquireFence;
4265 captureRequest->inputBuffer.releaseFence = nullptr;
4266
4267 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4268 request->input_buffer->buffer,
4269 request->input_buffer->acquire_fence);
4270 } else {
4271 captureRequest->inputBuffer.streamId = -1;
4272 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4273 }
4274
4275 captureRequest->outputBuffers.resize(request->num_output_buffers);
4276 for (size_t i = 0; i < request->num_output_buffers; i++) {
4277 const camera3_stream_buffer_t *src = request->output_buffers + i;
4278 StreamBuffer &dst = captureRequest->outputBuffers[i];
4279 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004280 if (src->buffer != nullptr) {
4281 buffer_handle_t buf = *(src->buffer);
4282 auto pair = getBufferId(buf, streamId);
4283 bool isNewBuffer = pair.first;
4284 dst.bufferId = pair.second;
4285 dst.buffer = isNewBuffer ? buf : nullptr;
4286 native_handle_t *acquireFence = nullptr;
4287 if (src->acquire_fence != -1) {
4288 acquireFence = native_handle_create(1,0);
4289 acquireFence->data[0] = src->acquire_fence;
4290 handlesCreated->push_back(acquireFence);
4291 }
4292 dst.acquireFence = acquireFence;
4293 } else if (mUseHalBufManager) {
4294 // HAL buffer management path
4295 dst.bufferId = BUFFER_ID_NO_BUFFER;
4296 dst.buffer = nullptr;
4297 dst.acquireFence = nullptr;
4298 } else {
4299 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4300 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004301 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004302 dst.streamId = streamId;
4303 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004304 dst.releaseFence = nullptr;
4305
4306 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4307 src->buffer, src->acquire_fence);
4308 }
4309 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004310 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004311}
4312
4313status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4314 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4315 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4316 if (!valid()) return INVALID_OPERATION;
4317
Emilian Peevaebbe412018-01-15 13:53:24 +00004318 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4319 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4320 if (castResult_3_4.isOk()) {
4321 hidlSession_3_4 = castResult_3_4;
4322 }
4323
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004324 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004325 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004326 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004327 if (hidlSession_3_4 != nullptr) {
4328 captureRequests_3_4.resize(batchSize);
4329 } else {
4330 captureRequests.resize(batchSize);
4331 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004332 std::vector<native_handle_t*> handlesCreated;
4333
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004334 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004335 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004336 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004337 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Emilian Peevaebbe412018-01-15 13:53:24 +00004338 /*out*/&handlesCreated);
4339 } else {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004340 res = wrapAsHidlRequest(requests[i],
4341 /*out*/&captureRequests[i], /*out*/&handlesCreated);
4342 }
4343 if (res != OK) {
4344 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004345 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004346 }
4347
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004348 std::vector<device::V3_2::BufferCache> cachesToRemove;
4349 {
4350 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4351 for (auto& pair : mFreedBuffers) {
4352 // The stream might have been removed since onBufferFreed
4353 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4354 cachesToRemove.push_back({pair.first, pair.second});
4355 }
4356 }
4357 mFreedBuffers.clear();
4358 }
4359
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004360 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4361 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004362
4363 // Write metadata to FMQ.
4364 for (size_t i = 0; i < batchSize; i++) {
4365 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004366 device::V3_2::CaptureRequest* captureRequest;
4367 if (hidlSession_3_4 != nullptr) {
4368 captureRequest = &captureRequests_3_4[i].v3_2;
4369 } else {
4370 captureRequest = &captureRequests[i];
4371 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004372
4373 if (request->settings != nullptr) {
4374 size_t settingsSize = get_camera_metadata_size(request->settings);
4375 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4376 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4377 captureRequest->settings.resize(0);
4378 captureRequest->fmqSettingsSize = settingsSize;
4379 } else {
4380 if (mRequestMetadataQueue != nullptr) {
4381 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4382 }
4383 captureRequest->settings.setToExternal(
4384 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4385 get_camera_metadata_size(request->settings));
4386 captureRequest->fmqSettingsSize = 0u;
4387 }
4388 } else {
4389 // A null request settings maps to a size-0 CameraMetadata
4390 captureRequest->settings.resize(0);
4391 captureRequest->fmqSettingsSize = 0u;
4392 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004393
4394 if (hidlSession_3_4 != nullptr) {
4395 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4396 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004397 if (request->physcam_settings != nullptr) {
4398 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4399 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4400 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4401 settingsSize)) {
4402 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4403 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4404 settingsSize;
4405 } else {
4406 if (mRequestMetadataQueue != nullptr) {
4407 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4408 }
4409 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4410 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4411 request->physcam_settings[j])),
4412 get_camera_metadata_size(request->physcam_settings[j]));
4413 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004414 }
Emilian Peev00420d22018-02-05 21:33:13 +00004415 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004416 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004417 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004418 }
4419 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4420 request->physcam_id[j];
4421 }
4422 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004423 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004424
4425 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004426 auto resultCallback =
4427 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4428 status = s;
4429 *numRequestProcessed = n;
4430 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004431 if (hidlSession_3_4 != nullptr) {
4432 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004433 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004434 } else {
4435 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004436 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004437 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004438 if (!err.isOk()) {
4439 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4440 return DEAD_OBJECT;
4441 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004442 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4443 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4444 __FUNCTION__, *numRequestProcessed, batchSize);
4445 status = common::V1_0::Status::INTERNAL_ERROR;
4446 }
4447
4448 for (auto& handle : handlesCreated) {
4449 native_handle_delete(handle);
4450 }
4451 return CameraProviderManager::mapToStatusT(status);
4452}
4453
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004454status_t Camera3Device::HalInterface::processCaptureRequest(
4455 camera3_capture_request_t *request) {
4456 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004457 if (!valid()) return INVALID_OPERATION;
4458 status_t res = OK;
4459
Emilian Peev31abd0a2017-05-11 18:37:46 +01004460 uint32_t numRequestProcessed = 0;
4461 std::vector<camera3_capture_request_t*> requests(1);
4462 requests[0] = request;
4463 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4464
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004465 return res;
4466}
4467
4468status_t Camera3Device::HalInterface::flush() {
4469 ATRACE_NAME("CameraHal::flush");
4470 if (!valid()) return INVALID_OPERATION;
4471 status_t res = OK;
4472
Emilian Peev31abd0a2017-05-11 18:37:46 +01004473 auto err = mHidlSession->flush();
4474 if (!err.isOk()) {
4475 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4476 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004477 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004478 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004479 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004480
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004481 return res;
4482}
4483
Emilian Peev31abd0a2017-05-11 18:37:46 +01004484status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004485 ATRACE_NAME("CameraHal::dump");
4486 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004487
Emilian Peev31abd0a2017-05-11 18:37:46 +01004488 // Handled by CameraProviderManager::dump
4489
4490 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004491}
4492
4493status_t Camera3Device::HalInterface::close() {
4494 ATRACE_NAME("CameraHal::close()");
4495 if (!valid()) return INVALID_OPERATION;
4496 status_t res = OK;
4497
Emilian Peev31abd0a2017-05-11 18:37:46 +01004498 auto err = mHidlSession->close();
4499 // Interface will be dead shortly anyway, so don't log errors
4500 if (!err.isOk()) {
4501 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004502 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004503
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004504 return res;
4505}
4506
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004507void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4508 ATRACE_NAME("CameraHal::signalPipelineDrain");
4509 if (!valid() || mHidlSession_3_5 == nullptr) {
4510 ALOGE("%s called on invalid camera!", __FUNCTION__);
4511 return;
4512 }
4513
4514 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter);
4515 if (!err.isOk()) {
4516 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4517 return;
4518 }
4519}
4520
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004521void Camera3Device::HalInterface::getInflightBufferKeys(
4522 std::vector<std::pair<int32_t, int32_t>>* out) {
4523 std::lock_guard<std::mutex> lock(mInflightLock);
4524 out->clear();
4525 out->reserve(mInflightBufferMap.size());
4526 for (auto& pair : mInflightBufferMap) {
4527 uint64_t key = pair.first;
4528 int32_t streamId = key & 0xFFFFFFFF;
4529 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4530 out->push_back(std::make_pair(frameNumber, streamId));
4531 }
4532 return;
4533}
4534
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004535status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004536 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004537 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004538 auto pair = std::make_pair(buffer, acquireFence);
4539 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004540 return OK;
4541}
4542
4543status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004544 int32_t frameNumber, int32_t streamId,
4545 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004546 std::lock_guard<std::mutex> lock(mInflightLock);
4547
4548 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4549 auto it = mInflightBufferMap.find(key);
4550 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004551 auto pair = it->second;
4552 *buffer = pair.first;
4553 int acquireFence = pair.second;
4554 if (acquireFence > 0) {
4555 ::close(acquireFence);
4556 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004557 mInflightBufferMap.erase(it);
4558 return OK;
4559}
4560
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004561status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4562 uint64_t bufferId, buffer_handle_t* buf) {
4563 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4564 auto pair = mRequestedBuffers.insert({bufferId, buf});
4565 if (!pair.second) {
4566 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4567 __FUNCTION__, bufferId);
4568 return BAD_VALUE;
4569 }
4570 return OK;
4571}
4572
4573// Find and pop a buffer_handle_t based on bufferId
4574status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4575 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4576 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4577 auto it = mRequestedBuffers.find(bufferId);
4578 if (it == mRequestedBuffers.end()) {
4579 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4580 __FUNCTION__, bufferId);
4581 return BAD_VALUE;
4582 }
4583 *buffer = it->second;
4584 mRequestedBuffers.erase(it);
4585 return OK;
4586}
4587
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004588std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4589 const buffer_handle_t& buf, int streamId) {
4590 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4591
4592 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4593 auto it = bIdMap.find(buf);
4594 if (it == bIdMap.end()) {
4595 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004596 ALOGV("stream %d now have %zu buffer caches, buf %p",
4597 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004598 return std::make_pair(true, mNextBufferId - 1);
4599 } else {
4600 return std::make_pair(false, it->second);
4601 }
4602}
4603
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004604void Camera3Device::HalInterface::onBufferFreed(
4605 int streamId, const native_handle_t* handle) {
4606 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4607 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4608 auto mapIt = mBufferIdMaps.find(streamId);
4609 if (mapIt == mBufferIdMaps.end()) {
4610 // streamId might be from a deleted stream here
4611 ALOGI("%s: stream %d has been removed",
4612 __FUNCTION__, streamId);
4613 return;
4614 }
4615 BufferIdMap& bIdMap = mapIt->second;
4616 auto it = bIdMap.find(handle);
4617 if (it == bIdMap.end()) {
4618 ALOGW("%s: cannot find buffer %p in stream %d",
4619 __FUNCTION__, handle, streamId);
4620 return;
4621 } else {
4622 bufferId = it->second;
4623 bIdMap.erase(it);
4624 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4625 __FUNCTION__, streamId, bIdMap.size(), handle);
4626 }
4627 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4628}
4629
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004630/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004631 * RequestThread inner class methods
4632 */
4633
4634Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004635 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004636 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4637 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004638 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004639 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004640 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004641 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004642 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004643 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004644 mReconfigured(false),
4645 mDoPause(false),
4646 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004647 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004648 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004649 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004650 mCurrentAfTriggerId(0),
4651 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004652 mRepeatingLastFrameNumber(
4653 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004654 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004655 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004656 mRequestLatency(kRequestLatencyBinSize),
4657 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004658 mLatestSessionParams(sessionParamKeys.size()),
4659 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004660 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004661}
4662
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004663Camera3Device::RequestThread::~RequestThread() {}
4664
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004665void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004666 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004667 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004668 Mutex::Autolock l(mRequestLock);
4669 mListener = listener;
4670}
4671
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004672void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4673 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004674 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004675 Mutex::Autolock l(mRequestLock);
4676 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004677 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004678 // Prepare video stream for high speed recording.
4679 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004680 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004681}
4682
Jianing Wei90e59c92014-03-12 18:29:36 -07004683status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004684 List<sp<CaptureRequest> > &requests,
4685 /*out*/
4686 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004687 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004688 Mutex::Autolock l(mRequestLock);
4689 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4690 ++it) {
4691 mRequestQueue.push_back(*it);
4692 }
4693
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004694 if (lastFrameNumber != NULL) {
4695 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4696 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4697 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4698 *lastFrameNumber);
4699 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004700
Jianing Wei90e59c92014-03-12 18:29:36 -07004701 unpauseForNewRequests();
4702
4703 return OK;
4704}
4705
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004706
4707status_t Camera3Device::RequestThread::queueTrigger(
4708 RequestTrigger trigger[],
4709 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004710 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004711 Mutex::Autolock l(mTriggerMutex);
4712 status_t ret;
4713
4714 for (size_t i = 0; i < count; ++i) {
4715 ret = queueTriggerLocked(trigger[i]);
4716
4717 if (ret != OK) {
4718 return ret;
4719 }
4720 }
4721
4722 return OK;
4723}
4724
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004725const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4726 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004727 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004728 if (d != nullptr) return d->mId;
4729 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004730}
4731
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004732status_t Camera3Device::RequestThread::queueTriggerLocked(
4733 RequestTrigger trigger) {
4734
4735 uint32_t tag = trigger.metadataTag;
4736 ssize_t index = mTriggerMap.indexOfKey(tag);
4737
4738 switch (trigger.getTagType()) {
4739 case TYPE_BYTE:
4740 // fall-through
4741 case TYPE_INT32:
4742 break;
4743 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004744 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4745 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004746 return INVALID_OPERATION;
4747 }
4748
4749 /**
4750 * Collect only the latest trigger, since we only have 1 field
4751 * in the request settings per trigger tag, and can't send more than 1
4752 * trigger per request.
4753 */
4754 if (index != NAME_NOT_FOUND) {
4755 mTriggerMap.editValueAt(index) = trigger;
4756 } else {
4757 mTriggerMap.add(tag, trigger);
4758 }
4759
4760 return OK;
4761}
4762
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004763status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004764 const RequestList &requests,
4765 /*out*/
4766 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004767 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004768 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004769 if (lastFrameNumber != NULL) {
4770 *lastFrameNumber = mRepeatingLastFrameNumber;
4771 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004772 mRepeatingRequests.clear();
4773 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4774 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004775
4776 unpauseForNewRequests();
4777
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004778 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004779 return OK;
4780}
4781
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004782bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004783 if (mRepeatingRequests.empty()) {
4784 return false;
4785 }
4786 int32_t requestId = requestIn->mResultExtras.requestId;
4787 const RequestList &repeatRequests = mRepeatingRequests;
4788 // All repeating requests are guaranteed to have same id so only check first quest
4789 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4790 return (firstRequest->mResultExtras.requestId == requestId);
4791}
4792
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004793status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004794 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004795 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004796 return clearRepeatingRequestsLocked(lastFrameNumber);
4797
4798}
4799
4800status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004801 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004802 if (lastFrameNumber != NULL) {
4803 *lastFrameNumber = mRepeatingLastFrameNumber;
4804 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004805 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004806 return OK;
4807}
4808
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004809status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004810 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004811 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004812 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004813 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004814
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004815 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004816
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004817 // Send errors for all requests pending in the request queue, including
4818 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004819 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004820 if (listener != NULL) {
4821 for (RequestList::iterator it = mRequestQueue.begin();
4822 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004823 // Abort the input buffers for reprocess requests.
4824 if ((*it)->mInputStream != NULL) {
4825 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004826 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4827 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004828 if (res != OK) {
4829 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4830 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4831 } else {
4832 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4833 if (res != OK) {
4834 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4835 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4836 }
4837 }
4838 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004839 // Set the frame number this request would have had, if it
4840 // had been submitted; this frame number will not be reused.
4841 // The requestId and burstId fields were set when the request was
4842 // submitted originally (in convertMetadataListToRequestListLocked)
4843 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004844 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004845 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004846 }
4847 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004848 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004849
4850 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004851 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004852 if (lastFrameNumber != NULL) {
4853 *lastFrameNumber = mRepeatingLastFrameNumber;
4854 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004855 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004856 return OK;
4857}
4858
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004859status_t Camera3Device::RequestThread::flush() {
4860 ATRACE_CALL();
4861 Mutex::Autolock l(mFlushLock);
4862
Emilian Peev08dd2452017-04-06 16:55:14 +01004863 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004864}
4865
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004866void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004867 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004868 Mutex::Autolock l(mPauseLock);
4869 mDoPause = paused;
4870 mDoPauseSignal.signal();
4871}
4872
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004873status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4874 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004875 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004876 Mutex::Autolock l(mLatestRequestMutex);
4877 status_t res;
4878 while (mLatestRequestId != requestId) {
4879 nsecs_t startTime = systemTime();
4880
4881 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4882 if (res != OK) return res;
4883
4884 timeout -= (systemTime() - startTime);
4885 }
4886
4887 return OK;
4888}
4889
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004890void Camera3Device::RequestThread::requestExit() {
4891 // Call parent to set up shutdown
4892 Thread::requestExit();
4893 // The exit from any possible waits
4894 mDoPauseSignal.signal();
4895 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004896
4897 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4898 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004899}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004900
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004901void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004902 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004903 bool surfaceAbandoned = false;
4904 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004905 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004906 {
4907 Mutex::Autolock l(mRequestLock);
4908 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4909 // repeating requests.
4910 for (const auto& request : mRepeatingRequests) {
4911 for (const auto& s : request->mOutputStreams) {
4912 if (s->isAbandoned()) {
4913 surfaceAbandoned = true;
4914 clearRepeatingRequestsLocked(&lastFrameNumber);
4915 break;
4916 }
4917 }
4918 if (surfaceAbandoned) {
4919 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004920 }
4921 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004922 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004923 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004924
4925 if (listener != NULL && surfaceAbandoned) {
4926 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004927 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004928}
4929
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004930bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004931 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004932 status_t res;
4933 size_t batchSize = mNextRequests.size();
4934 std::vector<camera3_capture_request_t*> requests(batchSize);
4935 uint32_t numRequestProcessed = 0;
4936 for (size_t i = 0; i < batchSize; i++) {
4937 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004938 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004939 }
4940
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004941 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4942
4943 bool triggerRemoveFailed = false;
4944 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4945 for (size_t i = 0; i < numRequestProcessed; i++) {
4946 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4947 nextRequest.submitted = true;
4948
4949
4950 // Update the latest request sent to HAL
4951 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4952 Mutex::Autolock al(mLatestRequestMutex);
4953
4954 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4955 mLatestRequest.acquire(cloned);
4956
4957 sp<Camera3Device> parent = mParent.promote();
4958 if (parent != NULL) {
4959 parent->monitorMetadata(TagMonitor::REQUEST,
4960 nextRequest.halRequest.frame_number,
4961 0, mLatestRequest);
4962 }
4963 }
4964
4965 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004966 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4967 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004968 }
4969
Emilian Peevaebbe412018-01-15 13:53:24 +00004970 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4971
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004972 if (!triggerRemoveFailed) {
4973 // Remove any previously queued triggers (after unlock)
4974 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4975 if (removeTriggerRes != OK) {
4976 triggerRemoveFailed = true;
4977 triggerFailedRequest = nextRequest;
4978 }
4979 }
4980 }
4981
4982 if (triggerRemoveFailed) {
4983 SET_ERR("RequestThread: Unable to remove triggers "
4984 "(capture request %d, HAL device: %s (%d)",
4985 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4986 cleanUpFailedRequests(/*sendRequestError*/ false);
4987 return false;
4988 }
4989
4990 if (res != OK) {
4991 // Should only get a failure here for malformed requests or device-level
4992 // errors, so consider all errors fatal. Bad metadata failures should
4993 // come through notify.
4994 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4995 mNextRequests[numRequestProcessed].halRequest.frame_number,
4996 strerror(-res), res);
4997 cleanUpFailedRequests(/*sendRequestError*/ false);
4998 return false;
4999 }
5000 return true;
5001}
5002
5003bool Camera3Device::RequestThread::sendRequestsOneByOne() {
5004 status_t res;
5005
5006 for (auto& nextRequest : mNextRequests) {
5007 // Submit request and block until ready for next one
5008 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
5009 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
5010
5011 if (res != OK) {
5012 // Should only get a failure here for malformed requests or device-level
5013 // errors, so consider all errors fatal. Bad metadata failures should
5014 // come through notify.
5015 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
5016 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
5017 res);
5018 cleanUpFailedRequests(/*sendRequestError*/ false);
5019 return false;
5020 }
5021
5022 // Mark that the request has be submitted successfully.
5023 nextRequest.submitted = true;
5024
5025 // Update the latest request sent to HAL
5026 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5027 Mutex::Autolock al(mLatestRequestMutex);
5028
5029 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5030 mLatestRequest.acquire(cloned);
5031
5032 sp<Camera3Device> parent = mParent.promote();
5033 if (parent != NULL) {
5034 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
5035 0, mLatestRequest);
5036 }
5037 }
5038
5039 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005040 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5041 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005042 }
5043
Emilian Peevaebbe412018-01-15 13:53:24 +00005044 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5045
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005046 // Remove any previously queued triggers (after unlock)
5047 res = removeTriggers(mPrevRequest);
5048 if (res != OK) {
5049 SET_ERR("RequestThread: Unable to remove triggers "
5050 "(capture request %d, HAL device: %s (%d)",
5051 nextRequest.halRequest.frame_number, strerror(-res), res);
5052 cleanUpFailedRequests(/*sendRequestError*/ false);
5053 return false;
5054 }
5055 }
5056 return true;
5057}
5058
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005059nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5060 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5061 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5062 find_camera_metadata_ro_entry(request,
5063 ANDROID_CONTROL_AE_MODE,
5064 &e);
5065 if (e.count == 0) return maxExpectedDuration;
5066
5067 switch (e.data.u8[0]) {
5068 case ANDROID_CONTROL_AE_MODE_OFF:
5069 find_camera_metadata_ro_entry(request,
5070 ANDROID_SENSOR_EXPOSURE_TIME,
5071 &e);
5072 if (e.count > 0) {
5073 maxExpectedDuration = e.data.i64[0];
5074 }
5075 find_camera_metadata_ro_entry(request,
5076 ANDROID_SENSOR_FRAME_DURATION,
5077 &e);
5078 if (e.count > 0) {
5079 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5080 }
5081 break;
5082 default:
5083 find_camera_metadata_ro_entry(request,
5084 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5085 &e);
5086 if (e.count > 1) {
5087 maxExpectedDuration = 1e9 / e.data.u8[0];
5088 }
5089 break;
5090 }
5091
5092 return maxExpectedDuration;
5093}
5094
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005095bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5096 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5097 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5098 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5099 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5100 return true;
5101 }
5102
5103 return false;
5104}
5105
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005106bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5107 ATRACE_CALL();
5108 bool updatesDetected = false;
5109
5110 for (auto tag : mSessionParamKeys) {
5111 camera_metadata_ro_entry entry = settings.find(tag);
5112 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
5113
5114 if (entry.count > 0) {
5115 bool isDifferent = false;
5116 if (lastEntry.count > 0) {
5117 // Have a last value, compare to see if changed
5118 if (lastEntry.type == entry.type &&
5119 lastEntry.count == entry.count) {
5120 // Same type and count, compare values
5121 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5122 size_t entryBytes = bytesPerValue * lastEntry.count;
5123 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5124 if (cmp != 0) {
5125 isDifferent = true;
5126 }
5127 } else {
5128 // Count or type has changed
5129 isDifferent = true;
5130 }
5131 } else {
5132 // No last entry, so always consider to be different
5133 isDifferent = true;
5134 }
5135
5136 if (isDifferent) {
5137 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005138 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5139 updatesDetected = true;
5140 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005141 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005142 }
5143 } else if (lastEntry.count > 0) {
5144 // Value has been removed
5145 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
5146 mLatestSessionParams.erase(tag);
5147 updatesDetected = true;
5148 }
5149 }
5150
5151 return updatesDetected;
5152}
5153
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005154bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005155 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005156 status_t res;
5157
5158 // Handle paused state.
5159 if (waitIfPaused()) {
5160 return true;
5161 }
5162
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005163 // Wait for the next batch of requests.
5164 waitForNextRequestBatch();
5165 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005166 return true;
5167 }
5168
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005169 // Get the latest request ID, if any
5170 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005171 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005172 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005173 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005174 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005175 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005176 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5177 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005178 }
5179
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005180 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5181 // or a single request from streaming or burst. In either case the first element
5182 // should contain the latest camera settings that we need to check for any session
5183 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005184 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005185 res = OK;
5186
5187 //Input stream buffers are already acquired at this point so an input stream
5188 //will not be able to move to idle state unless we force it.
5189 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5190 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5191 if (res != OK) {
5192 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5193 cleanUpFailedRequests(/*sendRequestError*/ false);
5194 return false;
5195 }
5196 }
5197
5198 if (res == OK) {
5199 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5200 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005201 sp<Camera3Device> parent = mParent.promote();
5202 if (parent != nullptr) {
5203 parent->pauseStateNotify(true);
5204 }
5205
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005206 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5207
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005208 if (parent != nullptr) {
5209 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5210 }
5211
5212 statusTracker->markComponentActive(mStatusId);
5213 setPaused(false);
5214 }
5215
5216 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5217 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5218 if (res != OK) {
5219 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5220 cleanUpFailedRequests(/*sendRequestError*/ false);
5221 return false;
5222 }
5223 }
5224 }
5225 }
5226
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005227 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005228 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005229 if (res == TIMED_OUT) {
5230 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005231 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005232 // Check if any stream is abandoned.
5233 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005234 return true;
5235 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005236 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005237 return false;
5238 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005239
Zhijun Hecc27e112013-10-03 16:12:43 -07005240 // Inform waitUntilRequestProcessed thread of a new request ID
5241 {
5242 Mutex::Autolock al(mLatestRequestMutex);
5243
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005244 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005245 mLatestRequestSignal.signal();
5246 }
5247
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005248 // Submit a batch of requests to HAL.
5249 // Use flush lock only when submitting multilple requests in a batch.
5250 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5251 // which may take a long time to finish so synchronizing flush() and
5252 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5253 // For now, only synchronize for high speed recording and we should figure something out for
5254 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005255 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005256
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005257 if (useFlushLock) {
5258 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005259 }
5260
Zhijun Hef0645c12016-08-02 00:58:11 -07005261 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005262 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005263
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005264 sp<Camera3Device> parent = mParent.promote();
5265 if (parent != nullptr) {
5266 parent->mRequestBufferSM.onSubmittingRequest();
5267 }
5268
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005269 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005270 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005271 if (mInterface->supportBatchRequest()) {
5272 submitRequestSuccess = sendRequestsBatch();
5273 } else {
5274 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005275 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005276 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5277 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005278
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005279 if (useFlushLock) {
5280 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005281 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005282
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005283 // Unset as current request
5284 {
5285 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005286 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005287 }
5288
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005289 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005290}
5291
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005292status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005293 ATRACE_CALL();
5294
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005295 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005296 for (size_t i = 0; i < mNextRequests.size(); i++) {
5297 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005298 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5299 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5300 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5301
5302 // Prepare a request to HAL
5303 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5304
5305 // Insert any queued triggers (before metadata is locked)
5306 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005307 if (res < 0) {
5308 SET_ERR("RequestThread: Unable to insert triggers "
5309 "(capture request %d, HAL device: %s (%d)",
5310 halRequest->frame_number, strerror(-res), res);
5311 return INVALID_OPERATION;
5312 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005313
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005314 int triggerCount = res;
5315 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5316 mPrevTriggers = triggerCount;
5317
5318 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005319 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5320 // Request settings are all the same within one batch, so only treat the first
5321 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005322 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005323 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005324 /**
5325 * HAL workaround:
5326 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5327 */
5328 res = addDummyTriggerIds(captureRequest);
5329 if (res != OK) {
5330 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5331 "(capture request %d, HAL device: %s (%d)",
5332 halRequest->frame_number, strerror(-res), res);
5333 return INVALID_OPERATION;
5334 }
5335
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005336 {
5337 // Correct metadata regions for distortion correction if enabled
5338 sp<Camera3Device> parent = mParent.promote();
5339 if (parent != nullptr) {
5340 res = parent->mDistortionMapper.correctCaptureRequest(
5341 &(captureRequest->mSettingsList.begin()->metadata));
5342 if (res != OK) {
5343 SET_ERR("RequestThread: Unable to correct capture requests "
5344 "for lens distortion for request %d: %s (%d)",
5345 halRequest->frame_number, strerror(-res), res);
5346 return INVALID_OPERATION;
5347 }
5348 }
5349 }
5350
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005351 /**
5352 * The request should be presorted so accesses in HAL
5353 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5354 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005355 captureRequest->mSettingsList.begin()->metadata.sort();
5356 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005357 mPrevRequest = captureRequest;
5358 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5359
5360 IF_ALOGV() {
5361 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5362 find_camera_metadata_ro_entry(
5363 halRequest->settings,
5364 ANDROID_CONTROL_AF_TRIGGER,
5365 &e
5366 );
5367 if (e.count > 0) {
5368 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5369 __FUNCTION__,
5370 halRequest->frame_number,
5371 e.data.u8[0]);
5372 }
5373 }
5374 } else {
5375 // leave request.settings NULL to indicate 'reuse latest given'
5376 ALOGVV("%s: Request settings are REUSED",
5377 __FUNCTION__);
5378 }
5379
Emilian Peevaebbe412018-01-15 13:53:24 +00005380 if (captureRequest->mSettingsList.size() > 1) {
5381 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5382 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005383 if (newRequest) {
5384 halRequest->physcam_settings =
5385 new const camera_metadata* [halRequest->num_physcam_settings];
5386 } else {
5387 halRequest->physcam_settings = nullptr;
5388 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005389 auto it = ++captureRequest->mSettingsList.begin();
5390 size_t i = 0;
5391 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5392 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005393 if (newRequest) {
5394 it->metadata.sort();
5395 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5396 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005397 }
5398 }
5399
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005400 uint32_t totalNumBuffers = 0;
5401
5402 // Fill in buffers
5403 if (captureRequest->mInputStream != NULL) {
5404 halRequest->input_buffer = &captureRequest->mInputBuffer;
5405 totalNumBuffers += 1;
5406 } else {
5407 halRequest->input_buffer = NULL;
5408 }
5409
5410 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5411 captureRequest->mOutputStreams.size());
5412 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005413 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005414
5415 sp<Camera3Device> parent = mParent.promote();
5416 if (parent == NULL) {
5417 // Should not happen, and nowhere to send errors to, so just log it
5418 CLOGE("RequestThread: Parent is gone");
5419 return INVALID_OPERATION;
5420 }
5421 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5422
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005423 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005424 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005425 sp<Camera3OutputStreamInterface> outputStream =
5426 captureRequest->mOutputStreams.editItemAt(j);
5427 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005428
5429 // Prepare video buffers for high speed recording on the first video request.
5430 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5431 // Only try to prepare video stream on the first video request.
5432 mPrepareVideoStream = false;
5433
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005434 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5435 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005436 while (res == NOT_ENOUGH_DATA) {
5437 res = outputStream->prepareNextBuffer();
5438 }
5439 if (res != OK) {
5440 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5441 __FUNCTION__, strerror(-res), res);
5442 outputStream->cancelPrepare();
5443 }
5444 }
5445
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005446 std::vector<size_t> uniqueSurfaceIds;
5447 res = outputStream->getUniqueSurfaceIds(
5448 captureRequest->mOutputSurfaces[streamId],
5449 &uniqueSurfaceIds);
5450 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5451 if (res != OK && res != INVALID_OPERATION) {
5452 ALOGE("%s: failed to query stream %d unique surface IDs",
5453 __FUNCTION__, streamId);
5454 return res;
5455 }
5456 if (res == OK) {
5457 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5458 }
5459
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005460 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005461 if (outputStream->isAbandoned()) {
5462 ALOGE("%s: stream %d is abandoned.", __FUNCTION__, streamId);
5463 return TIMED_OUT;
5464 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005465 // HAL will request buffer through requestStreamBuffer API
5466 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5467 buffer.stream = outputStream->asHalStream();
5468 buffer.buffer = nullptr;
5469 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5470 buffer.acquire_fence = -1;
5471 buffer.release_fence = -1;
5472 } else {
5473 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5474 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005475 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005476 if (res != OK) {
5477 // Can't get output buffer from gralloc queue - this could be due to
5478 // abandoned queue or other consumer misbehavior, so not a fatal
5479 // error
5480 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5481 " %s (%d)", strerror(-res), res);
5482
5483 return TIMED_OUT;
5484 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005485 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005486
5487 {
5488 sp<Camera3Device> parent = mParent.promote();
5489 if (parent != nullptr) {
5490 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5491 for (const auto& settings : captureRequest->mSettingsList) {
5492 if ((streamCameraId.isEmpty() &&
5493 parent->getId() == settings.cameraId.c_str()) ||
5494 streamCameraId == settings.cameraId.c_str()) {
5495 outputStream->fireBufferRequestForFrameNumber(
5496 captureRequest->mResultExtras.frameNumber,
5497 settings.metadata);
5498 }
5499 }
5500 }
5501 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005502
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005503 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5504
5505 if (!physicalCameraId.isEmpty()) {
5506 // Physical stream isn't supported for input request.
5507 if (halRequest->input_buffer) {
5508 CLOGE("Physical stream is not supported for input request");
5509 return INVALID_OPERATION;
5510 }
5511 requestedPhysicalCameras.insert(physicalCameraId);
5512 }
5513 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005514 }
5515 totalNumBuffers += halRequest->num_output_buffers;
5516
5517 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005518 // If this request list is for constrained high speed recording (not
5519 // preview), and the current request is not the last one in the batch,
5520 // do not send callback to the app.
5521 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005522 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005523 hasCallback = false;
5524 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005525 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005526 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005527 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5528 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5529 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5530 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5531 isStillCapture = true;
5532 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5533 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005534
5535 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5536 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5537 isZslCapture = true;
5538 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005539 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005540 res = parent->registerInFlight(halRequest->frame_number,
5541 totalNumBuffers, captureRequest->mResultExtras,
5542 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005543 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005544 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005545 requestedPhysicalCameras, isStillCapture, isZslCapture,
5546 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5547 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005548 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5549 ", burstId = %" PRId32 ".",
5550 __FUNCTION__,
5551 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5552 captureRequest->mResultExtras.burstId);
5553 if (res != OK) {
5554 SET_ERR("RequestThread: Unable to register new in-flight request:"
5555 " %s (%d)", strerror(-res), res);
5556 return INVALID_OPERATION;
5557 }
5558 }
5559
5560 return OK;
5561}
5562
Igor Murashkin1e479c02013-09-06 16:55:14 -07005563CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005564 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005565 Mutex::Autolock al(mLatestRequestMutex);
5566
5567 ALOGV("RequestThread::%s", __FUNCTION__);
5568
5569 return mLatestRequest;
5570}
5571
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005572bool Camera3Device::RequestThread::isStreamPending(
5573 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005574 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005575 Mutex::Autolock l(mRequestLock);
5576
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005577 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005578 if (!nextRequest.submitted) {
5579 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5580 if (stream == s) return true;
5581 }
5582 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005583 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005584 }
5585
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005586 for (const auto& request : mRequestQueue) {
5587 for (const auto& s : request->mOutputStreams) {
5588 if (stream == s) return true;
5589 }
5590 if (stream == request->mInputStream) return true;
5591 }
5592
5593 for (const auto& request : mRepeatingRequests) {
5594 for (const auto& s : request->mOutputStreams) {
5595 if (stream == s) return true;
5596 }
5597 if (stream == request->mInputStream) return true;
5598 }
5599
5600 return false;
5601}
Jianing Weicb0652e2014-03-12 18:29:36 -07005602
Emilian Peev40ead602017-09-26 15:46:36 +01005603bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5604 ATRACE_CALL();
5605 Mutex::Autolock l(mRequestLock);
5606
5607 for (const auto& nextRequest : mNextRequests) {
5608 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5609 if (s.first == streamId) {
5610 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5611 if (it != s.second.end()) {
5612 return true;
5613 }
5614 }
5615 }
5616 }
5617
5618 for (const auto& request : mRequestQueue) {
5619 for (const auto& s : request->mOutputSurfaces) {
5620 if (s.first == streamId) {
5621 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5622 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005623 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005624 }
5625 }
5626 }
5627 }
5628
5629 for (const auto& request : mRepeatingRequests) {
5630 for (const auto& s : request->mOutputSurfaces) {
5631 if (s.first == streamId) {
5632 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5633 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005634 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005635 }
5636 }
5637 }
5638 }
5639
5640 return false;
5641}
5642
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005643void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5644 if (!mUseHalBufManager) {
5645 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5646 return;
5647 }
5648
5649 Mutex::Autolock pl(mPauseLock);
5650 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005651 mInterface->signalPipelineDrain(streamIds);
5652 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005653 }
5654 // If request thread is still busy, wait until paused then notify HAL
5655 mNotifyPipelineDrain = true;
5656 mStreamIdsToBeDrained = streamIds;
5657}
5658
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005659nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005660 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005661 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005662 return mExpectedInflightDuration > kMinInflightDuration ?
5663 mExpectedInflightDuration : kMinInflightDuration;
5664}
5665
Emilian Peevaebbe412018-01-15 13:53:24 +00005666void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5667 camera3_capture_request_t *halRequest) {
5668 if ((request == nullptr) || (halRequest == nullptr)) {
5669 ALOGE("%s: Invalid request!", __FUNCTION__);
5670 return;
5671 }
5672
5673 if (halRequest->num_physcam_settings > 0) {
5674 if (halRequest->physcam_id != nullptr) {
5675 delete [] halRequest->physcam_id;
5676 halRequest->physcam_id = nullptr;
5677 }
5678 if (halRequest->physcam_settings != nullptr) {
5679 auto it = ++(request->mSettingsList.begin());
5680 size_t i = 0;
5681 for (; it != request->mSettingsList.end(); it++, i++) {
5682 it->metadata.unlock(halRequest->physcam_settings[i]);
5683 }
5684 delete [] halRequest->physcam_settings;
5685 halRequest->physcam_settings = nullptr;
5686 }
5687 }
5688}
5689
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005690void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5691 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005692 return;
5693 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005694
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005695 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005696 // Skip the ones that have been submitted successfully.
5697 if (nextRequest.submitted) {
5698 continue;
5699 }
5700
5701 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5702 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5703 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5704
5705 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005706 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005707 }
5708
Emilian Peevaebbe412018-01-15 13:53:24 +00005709 cleanupPhysicalSettings(captureRequest, halRequest);
5710
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005711 if (captureRequest->mInputStream != NULL) {
5712 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5713 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5714 }
5715
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005716 // No output buffer can be returned when using HAL buffer manager
5717 if (!mUseHalBufManager) {
5718 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5719 //Buffers that failed processing could still have
5720 //valid acquire fence.
5721 int acquireFence = (*outputBuffers)[i].acquire_fence;
5722 if (0 <= acquireFence) {
5723 close(acquireFence);
5724 outputBuffers->editItemAt(i).acquire_fence = -1;
5725 }
5726 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5727 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5728 /*timestampIncreasing*/true, std::vector<size_t> (),
5729 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005730 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005731 }
5732
5733 if (sendRequestError) {
5734 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005735 sp<NotificationListener> listener = mListener.promote();
5736 if (listener != NULL) {
5737 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005738 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005739 captureRequest->mResultExtras);
5740 }
5741 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005742
5743 // Remove yet-to-be submitted inflight request from inflightMap
5744 {
5745 sp<Camera3Device> parent = mParent.promote();
5746 if (parent != NULL) {
5747 Mutex::Autolock l(parent->mInFlightLock);
5748 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5749 if (idx >= 0) {
5750 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5751 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5752 parent->removeInFlightMapEntryLocked(idx);
5753 }
5754 }
5755 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005756 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005757
5758 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005759 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005760}
5761
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005762void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005763 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005764 // Optimized a bit for the simple steady-state case (single repeating
5765 // request), to avoid putting that request in the queue temporarily.
5766 Mutex::Autolock l(mRequestLock);
5767
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005768 assert(mNextRequests.empty());
5769
5770 NextRequest nextRequest;
5771 nextRequest.captureRequest = waitForNextRequestLocked();
5772 if (nextRequest.captureRequest == nullptr) {
5773 return;
5774 }
5775
5776 nextRequest.halRequest = camera3_capture_request_t();
5777 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005778 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005779
5780 // Wait for additional requests
5781 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5782
5783 for (size_t i = 1; i < batchSize; i++) {
5784 NextRequest additionalRequest;
5785 additionalRequest.captureRequest = waitForNextRequestLocked();
5786 if (additionalRequest.captureRequest == nullptr) {
5787 break;
5788 }
5789
5790 additionalRequest.halRequest = camera3_capture_request_t();
5791 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005792 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005793 }
5794
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005795 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005796 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005797 mNextRequests.size(), batchSize);
5798 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005799 }
5800
5801 return;
5802}
5803
5804sp<Camera3Device::CaptureRequest>
5805 Camera3Device::RequestThread::waitForNextRequestLocked() {
5806 status_t res;
5807 sp<CaptureRequest> nextRequest;
5808
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005809 while (mRequestQueue.empty()) {
5810 if (!mRepeatingRequests.empty()) {
5811 // Always atomically enqueue all requests in a repeating request
5812 // list. Guarantees a complete in-sequence set of captures to
5813 // application.
5814 const RequestList &requests = mRepeatingRequests;
5815 RequestList::const_iterator firstRequest =
5816 requests.begin();
5817 nextRequest = *firstRequest;
5818 mRequestQueue.insert(mRequestQueue.end(),
5819 ++firstRequest,
5820 requests.end());
5821 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005822
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005823 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005824
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005825 break;
5826 }
5827
5828 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5829
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005830 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5831 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005832 Mutex::Autolock pl(mPauseLock);
5833 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005834 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005835 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005836 // Let the tracker know
5837 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5838 if (statusTracker != 0) {
5839 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5840 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005841 if (mNotifyPipelineDrain) {
5842 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5843 mNotifyPipelineDrain = false;
5844 mStreamIdsToBeDrained.clear();
5845 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005846 sp<Camera3Device> parent = mParent.promote();
5847 if (parent != nullptr) {
5848 parent->mRequestBufferSM.onRequestThreadPaused();
5849 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005850 }
5851 // Stop waiting for now and let thread management happen
5852 return NULL;
5853 }
5854 }
5855
5856 if (nextRequest == NULL) {
5857 // Don't have a repeating request already in hand, so queue
5858 // must have an entry now.
5859 RequestList::iterator firstRequest =
5860 mRequestQueue.begin();
5861 nextRequest = *firstRequest;
5862 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005863 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5864 sp<NotificationListener> listener = mListener.promote();
5865 if (listener != NULL) {
5866 listener->notifyRequestQueueEmpty();
5867 }
5868 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005869 }
5870
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005871 // In case we've been unpaused by setPaused clearing mDoPause, need to
5872 // update internal pause state (capture/setRepeatingRequest unpause
5873 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005874 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005875 if (mPaused) {
5876 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5877 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5878 if (statusTracker != 0) {
5879 statusTracker->markComponentActive(mStatusId);
5880 }
5881 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005882 mPaused = false;
5883
5884 // Check if we've reconfigured since last time, and reset the preview
5885 // request if so. Can't use 'NULL request == repeat' across configure calls.
5886 if (mReconfigured) {
5887 mPrevRequest.clear();
5888 mReconfigured = false;
5889 }
5890
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005891 if (nextRequest != NULL) {
5892 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005893 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5894 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005895
5896 // Since RequestThread::clear() removes buffers from the input stream,
5897 // get the right buffer here before unlocking mRequestLock
5898 if (nextRequest->mInputStream != NULL) {
5899 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5900 if (res != OK) {
5901 // Can't get input buffer from gralloc queue - this could be due to
5902 // disconnected queue or other producer misbehavior, so not a fatal
5903 // error
5904 ALOGE("%s: Can't get input buffer, skipping request:"
5905 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005906
5907 sp<NotificationListener> listener = mListener.promote();
5908 if (listener != NULL) {
5909 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005910 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005911 nextRequest->mResultExtras);
5912 }
5913 return NULL;
5914 }
5915 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005916 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005917
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005918 return nextRequest;
5919}
5920
5921bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005922 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005923 status_t res;
5924 Mutex::Autolock l(mPauseLock);
5925 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005926 if (mPaused == false) {
5927 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005928 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5929 // Let the tracker know
5930 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5931 if (statusTracker != 0) {
5932 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5933 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005934 if (mNotifyPipelineDrain) {
5935 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5936 mNotifyPipelineDrain = false;
5937 mStreamIdsToBeDrained.clear();
5938 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005939 sp<Camera3Device> parent = mParent.promote();
5940 if (parent != nullptr) {
5941 parent->mRequestBufferSM.onRequestThreadPaused();
5942 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005943 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005944
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005945 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005946 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005947 return true;
5948 }
5949 }
5950 // We don't set mPaused to false here, because waitForNextRequest needs
5951 // to further manage the paused state in case of starvation.
5952 return false;
5953}
5954
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005955void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005956 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005957 // With work to do, mark thread as unpaused.
5958 // If paused by request (setPaused), don't resume, to avoid
5959 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005960 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005961 Mutex::Autolock p(mPauseLock);
5962 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005963 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5964 if (mPaused) {
5965 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5966 if (statusTracker != 0) {
5967 statusTracker->markComponentActive(mStatusId);
5968 }
5969 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005970 mPaused = false;
5971 }
5972}
5973
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005974void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5975 sp<Camera3Device> parent = mParent.promote();
5976 if (parent != NULL) {
5977 va_list args;
5978 va_start(args, fmt);
5979
5980 parent->setErrorStateV(fmt, args);
5981
5982 va_end(args);
5983 }
5984}
5985
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005986status_t Camera3Device::RequestThread::insertTriggers(
5987 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005988 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005989 Mutex::Autolock al(mTriggerMutex);
5990
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005991 sp<Camera3Device> parent = mParent.promote();
5992 if (parent == NULL) {
5993 CLOGE("RequestThread: Parent is gone");
5994 return DEAD_OBJECT;
5995 }
5996
Emilian Peevaebbe412018-01-15 13:53:24 +00005997 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005998 size_t count = mTriggerMap.size();
5999
6000 for (size_t i = 0; i < count; ++i) {
6001 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006002 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006003
6004 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6005 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6006 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006007 if (isAeTrigger) {
6008 request->mResultExtras.precaptureTriggerId = triggerId;
6009 mCurrentPreCaptureTriggerId = triggerId;
6010 } else {
6011 request->mResultExtras.afTriggerId = triggerId;
6012 mCurrentAfTriggerId = triggerId;
6013 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006014 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006015 }
6016
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006017 camera_metadata_entry entry = metadata.find(tag);
6018
6019 if (entry.count > 0) {
6020 /**
6021 * Already has an entry for this trigger in the request.
6022 * Rewrite it with our requested trigger value.
6023 */
6024 RequestTrigger oldTrigger = trigger;
6025
6026 oldTrigger.entryValue = entry.data.u8[0];
6027
6028 mTriggerReplacedMap.add(tag, oldTrigger);
6029 } else {
6030 /**
6031 * More typical, no trigger entry, so we just add it
6032 */
6033 mTriggerRemovedMap.add(tag, trigger);
6034 }
6035
6036 status_t res;
6037
6038 switch (trigger.getTagType()) {
6039 case TYPE_BYTE: {
6040 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6041 res = metadata.update(tag,
6042 &entryValue,
6043 /*count*/1);
6044 break;
6045 }
6046 case TYPE_INT32:
6047 res = metadata.update(tag,
6048 &trigger.entryValue,
6049 /*count*/1);
6050 break;
6051 default:
6052 ALOGE("%s: Type not supported: 0x%x",
6053 __FUNCTION__,
6054 trigger.getTagType());
6055 return INVALID_OPERATION;
6056 }
6057
6058 if (res != OK) {
6059 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6060 ", value %d", __FUNCTION__, trigger.getTagName(),
6061 trigger.entryValue);
6062 return res;
6063 }
6064
6065 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6066 trigger.getTagName(),
6067 trigger.entryValue);
6068 }
6069
6070 mTriggerMap.clear();
6071
6072 return count;
6073}
6074
6075status_t Camera3Device::RequestThread::removeTriggers(
6076 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006077 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006078 Mutex::Autolock al(mTriggerMutex);
6079
Emilian Peevaebbe412018-01-15 13:53:24 +00006080 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006081
6082 /**
6083 * Replace all old entries with their old values.
6084 */
6085 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6086 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6087
6088 status_t res;
6089
6090 uint32_t tag = trigger.metadataTag;
6091 switch (trigger.getTagType()) {
6092 case TYPE_BYTE: {
6093 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6094 res = metadata.update(tag,
6095 &entryValue,
6096 /*count*/1);
6097 break;
6098 }
6099 case TYPE_INT32:
6100 res = metadata.update(tag,
6101 &trigger.entryValue,
6102 /*count*/1);
6103 break;
6104 default:
6105 ALOGE("%s: Type not supported: 0x%x",
6106 __FUNCTION__,
6107 trigger.getTagType());
6108 return INVALID_OPERATION;
6109 }
6110
6111 if (res != OK) {
6112 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6113 ", trigger value %d", __FUNCTION__,
6114 trigger.getTagName(), trigger.entryValue);
6115 return res;
6116 }
6117 }
6118 mTriggerReplacedMap.clear();
6119
6120 /**
6121 * Remove all new entries.
6122 */
6123 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6124 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6125 status_t res = metadata.erase(trigger.metadataTag);
6126
6127 if (res != OK) {
6128 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6129 ", trigger value %d", __FUNCTION__,
6130 trigger.getTagName(), trigger.entryValue);
6131 return res;
6132 }
6133 }
6134 mTriggerRemovedMap.clear();
6135
6136 return OK;
6137}
6138
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006139status_t Camera3Device::RequestThread::addDummyTriggerIds(
6140 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006141 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006142 static const int32_t dummyTriggerId = 1;
6143 status_t res;
6144
Emilian Peevaebbe412018-01-15 13:53:24 +00006145 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006146
6147 // If AF trigger is active, insert a dummy AF trigger ID if none already
6148 // exists
6149 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6150 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6151 if (afTrigger.count > 0 &&
6152 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6153 afId.count == 0) {
6154 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6155 if (res != OK) return res;
6156 }
6157
6158 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6159 // if none already exists
6160 camera_metadata_entry pcTrigger =
6161 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6162 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6163 if (pcTrigger.count > 0 &&
6164 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6165 pcId.count == 0) {
6166 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6167 &dummyTriggerId, 1);
6168 if (res != OK) return res;
6169 }
6170
6171 return OK;
6172}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006173
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006174/**
6175 * PreparerThread inner class methods
6176 */
6177
6178Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006179 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006180 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006181}
6182
6183Camera3Device::PreparerThread::~PreparerThread() {
6184 Thread::requestExitAndWait();
6185 if (mCurrentStream != nullptr) {
6186 mCurrentStream->cancelPrepare();
6187 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6188 mCurrentStream.clear();
6189 }
6190 clear();
6191}
6192
Ruben Brunkc78ac262015-08-13 17:58:46 -07006193status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006194 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006195 status_t res;
6196
6197 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006198 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006199
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006200 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006201 if (res == OK) {
6202 // No preparation needed, fire listener right off
6203 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006204 if (listener != NULL) {
6205 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006206 }
6207 return OK;
6208 } else if (res != NOT_ENOUGH_DATA) {
6209 return res;
6210 }
6211
6212 // Need to prepare, start up thread if necessary
6213 if (!mActive) {
6214 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6215 // isn't running
6216 Thread::requestExitAndWait();
6217 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6218 if (res != OK) {
6219 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006220 if (listener != NULL) {
6221 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006222 }
6223 return res;
6224 }
6225 mCancelNow = false;
6226 mActive = true;
6227 ALOGV("%s: Preparer stream started", __FUNCTION__);
6228 }
6229
6230 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006231 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006232 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6233
6234 return OK;
6235}
6236
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006237void Camera3Device::PreparerThread::pause() {
6238 ATRACE_CALL();
6239
6240 Mutex::Autolock l(mLock);
6241
6242 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6243 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6244 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6245 int currentMaxCount = mCurrentMaxCount;
6246 mPendingStreams.clear();
6247 mCancelNow = true;
6248 while (mActive) {
6249 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6250 if (res == TIMED_OUT) {
6251 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6252 return;
6253 } else if (res != OK) {
6254 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6255 return;
6256 }
6257 }
6258
6259 //Check whether the prepare thread was able to complete the current
6260 //stream. In case work is still pending emplace it along with the rest
6261 //of the streams in the pending list.
6262 if (currentStream != nullptr) {
6263 if (!mCurrentPrepareComplete) {
6264 pendingStreams.emplace(currentMaxCount, currentStream);
6265 }
6266 }
6267
6268 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6269 for (const auto& it : mPendingStreams) {
6270 it.second->cancelPrepare();
6271 }
6272}
6273
6274status_t Camera3Device::PreparerThread::resume() {
6275 ATRACE_CALL();
6276 status_t res;
6277
6278 Mutex::Autolock l(mLock);
6279 sp<NotificationListener> listener = mListener.promote();
6280
6281 if (mActive) {
6282 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6283 return NO_INIT;
6284 }
6285
6286 auto it = mPendingStreams.begin();
6287 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006288 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006289 if (res == OK) {
6290 if (listener != NULL) {
6291 listener->notifyPrepared(it->second->getId());
6292 }
6293 it = mPendingStreams.erase(it);
6294 } else if (res != NOT_ENOUGH_DATA) {
6295 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6296 res, strerror(-res));
6297 it = mPendingStreams.erase(it);
6298 } else {
6299 it++;
6300 }
6301 }
6302
6303 if (mPendingStreams.empty()) {
6304 return OK;
6305 }
6306
6307 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6308 if (res != OK) {
6309 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6310 __FUNCTION__, res, strerror(-res));
6311 return res;
6312 }
6313 mCancelNow = false;
6314 mActive = true;
6315 ALOGV("%s: Preparer stream started", __FUNCTION__);
6316
6317 return OK;
6318}
6319
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006320status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006321 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006322 Mutex::Autolock l(mLock);
6323
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006324 for (const auto& it : mPendingStreams) {
6325 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006326 }
6327 mPendingStreams.clear();
6328 mCancelNow = true;
6329
6330 return OK;
6331}
6332
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006333void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006334 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006335 Mutex::Autolock l(mLock);
6336 mListener = listener;
6337}
6338
6339bool Camera3Device::PreparerThread::threadLoop() {
6340 status_t res;
6341 {
6342 Mutex::Autolock l(mLock);
6343 if (mCurrentStream == nullptr) {
6344 // End thread if done with work
6345 if (mPendingStreams.empty()) {
6346 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6347 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6348 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6349 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006350 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006351 return false;
6352 }
6353
6354 // Get next stream to prepare
6355 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006356 mCurrentStream = it->second;
6357 mCurrentMaxCount = it->first;
6358 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006359 mPendingStreams.erase(it);
6360 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6361 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6362 } else if (mCancelNow) {
6363 mCurrentStream->cancelPrepare();
6364 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6365 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6366 mCurrentStream.clear();
6367 mCancelNow = false;
6368 return true;
6369 }
6370 }
6371
6372 res = mCurrentStream->prepareNextBuffer();
6373 if (res == NOT_ENOUGH_DATA) return true;
6374 if (res != OK) {
6375 // Something bad happened; try to recover by cancelling prepare and
6376 // signalling listener anyway
6377 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6378 mCurrentStream->getId(), res, strerror(-res));
6379 mCurrentStream->cancelPrepare();
6380 }
6381
6382 // This stream has finished, notify listener
6383 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006384 sp<NotificationListener> listener = mListener.promote();
6385 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006386 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6387 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006388 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006389 }
6390
6391 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6392 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006393 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006394
6395 return true;
6396}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006397
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006398status_t Camera3Device::RequestBufferStateMachine::initialize(
6399 sp<camera3::StatusTracker> statusTracker) {
6400 if (statusTracker == nullptr) {
6401 ALOGE("%s: statusTracker is null", __FUNCTION__);
6402 return BAD_VALUE;
6403 }
6404
6405 std::lock_guard<std::mutex> lock(mLock);
6406 mStatusTracker = statusTracker;
6407 mRequestBufferStatusId = statusTracker->addComponent();
6408 return OK;
6409}
6410
6411bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6412 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006413 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006414 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006415 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006416 return true;
6417 }
6418 return false;
6419}
6420
6421void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6422 std::lock_guard<std::mutex> lock(mLock);
6423 if (!mRequestBufferOngoing) {
6424 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6425 return;
6426 }
6427 mRequestBufferOngoing = false;
6428 if (mStatus == RB_STATUS_PENDING_STOP) {
6429 checkSwitchToStopLocked();
6430 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006431 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006432}
6433
6434void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6435 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006436 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006437 return;
6438}
6439
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006440void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006441 std::lock_guard<std::mutex> lock(mLock);
6442 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006443 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6444 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006445 mInflightMapEmpty = false;
6446 if (mStatus == RB_STATUS_STOPPED) {
6447 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006448 }
6449 return;
6450}
6451
6452void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6453 std::lock_guard<std::mutex> lock(mLock);
6454 mRequestThreadPaused = true;
6455 if (mStatus == RB_STATUS_PENDING_STOP) {
6456 checkSwitchToStopLocked();
6457 }
6458 return;
6459}
6460
6461void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6462 std::lock_guard<std::mutex> lock(mLock);
6463 mInflightMapEmpty = true;
6464 if (mStatus == RB_STATUS_PENDING_STOP) {
6465 checkSwitchToStopLocked();
6466 }
6467 return;
6468}
6469
6470void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6471 std::lock_guard<std::mutex> lock(mLock);
6472 if (!checkSwitchToStopLocked()) {
6473 mStatus = RB_STATUS_PENDING_STOP;
6474 }
6475 return;
6476}
6477
6478void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6479 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6480 if (statusTracker != nullptr) {
6481 if (active) {
6482 statusTracker->markComponentActive(mRequestBufferStatusId);
6483 } else {
6484 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6485 }
6486 }
6487}
6488
6489bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6490 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6491 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006492 return true;
6493 }
6494 return false;
6495}
6496
Shuzhen Wang268a1362018-10-16 16:32:59 -07006497status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6498 CameraMetadata& resultMetadata) {
6499 status_t res = OK;
6500 if (!mNeedFixupMonochromeTags) {
6501 return res;
6502 }
6503
6504 // Remove tags that are not applicable to monochrome camera.
6505 int32_t tagsToRemove[] = {
6506 ANDROID_SENSOR_GREEN_SPLIT,
6507 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6508 ANDROID_COLOR_CORRECTION_MODE,
6509 ANDROID_COLOR_CORRECTION_TRANSFORM,
6510 ANDROID_COLOR_CORRECTION_GAINS,
6511 };
6512 for (auto tag : tagsToRemove) {
6513 res = resultMetadata.erase(tag);
6514 if (res != OK) {
6515 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6516 return res;
6517 }
6518 }
6519
6520 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6521 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6522 for (size_t i = 1; i < blEntry.count; i++) {
6523 blEntry.data.f[i] = blEntry.data.f[0];
6524 }
6525
6526 // ANDROID_SENSOR_NOISE_PROFILE
6527 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6528 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6529 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6530 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6531 if (res != OK) {
6532 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6533 __FUNCTION__, strerror(-res), res);
6534 return res;
6535 }
6536 }
6537
6538 // ANDROID_STATISTICS_LENS_SHADING_MAP
6539 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6540 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6541 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6542 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6543 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6544 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6545 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6546 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6547 }
6548 }
6549
6550 // ANDROID_TONEMAP_CURVE_BLUE
6551 // ANDROID_TONEMAP_CURVE_GREEN
6552 // ANDROID_TONEMAP_CURVE_RED
6553 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6554 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6555 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6556 if (tcbEntry.count > 0
6557 && tcbEntry.count == tcgEntry.count
6558 && tcbEntry.count == tcrEntry.count) {
6559 for (size_t i = 0; i < tcbEntry.count; i++) {
6560 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6561 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6562 }
6563 }
6564
6565 return res;
6566}
6567
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006568}; // namespace android