blob: 918dcf775dcf725e5c5f6f0801062f595f2e9213 [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
1030 bufRet.streamId = streamId;
1031 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
1032 size_t totalHandout = outputStream->getOutstandingBuffersCount() + numBuffersRequested;
1033 if (totalHandout > outputStream->asHalStream()->max_buffers) {
1034 // Not able to allocate enough buffer. Exit early for this stream
1035 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1036 allReqsSucceeds = false;
1037 continue;
1038 }
1039
1040 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1041 bool currentReqSucceeds = true;
1042 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1043 size_t numAllocatedBuffers = 0;
1044 size_t numPushedInflightBuffers = 0;
1045 for (size_t b = 0; b < numBuffersRequested; b++) {
1046 camera3_stream_buffer_t& sb = streamBuffers[b];
1047 // Since this method can run concurrently with request thread
1048 // We need to update the wait duration everytime we call getbuffer
1049 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1050 status_t res = outputStream->getBuffer(&sb, waitDuration);
1051 if (res != OK) {
1052 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1053 __FUNCTION__, streamId, strerror(-res), res);
1054 if (res == NO_INIT || res == DEAD_OBJECT) {
1055 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1056 } else if (res == TIMED_OUT || res == NO_MEMORY) {
1057 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1058 } else {
1059 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1060 }
1061 currentReqSucceeds = false;
1062 break;
1063 }
1064 numAllocatedBuffers++;
1065
1066 buffer_handle_t *buffer = sb.buffer;
1067 auto pair = mInterface->getBufferId(*buffer, streamId);
1068 bool isNewBuffer = pair.first;
1069 uint64_t bufferId = pair.second;
1070 StreamBuffer& hBuf = tmpRetBuffers[b];
1071
1072 hBuf.streamId = streamId;
1073 hBuf.bufferId = bufferId;
1074 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1075 hBuf.status = BufferStatus::OK;
1076 hBuf.releaseFence = nullptr;
1077
1078 native_handle_t *acquireFence = nullptr;
1079 if (sb.acquire_fence != -1) {
1080 acquireFence = native_handle_create(1,0);
1081 acquireFence->data[0] = sb.acquire_fence;
1082 }
1083 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1084 hBuf.releaseFence = nullptr;
1085
1086 res = mInterface->pushInflightRequestBuffer(bufferId, buffer);
1087 if (res != OK) {
1088 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1089 __FUNCTION__, streamId, strerror(-res), res);
1090 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1091 currentReqSucceeds = false;
1092 break;
1093 }
1094 numPushedInflightBuffers++;
1095 }
1096 if (currentReqSucceeds) {
1097 bufRet.val.buffers(std::move(tmpRetBuffers));
1098 oneReqSucceeds = true;
1099 } else {
1100 allReqsSucceeds = false;
1101 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1102 StreamBuffer& hBuf = tmpRetBuffers[b];
1103 buffer_handle_t* buffer;
1104 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1105 if (res != OK) {
1106 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1107 __FUNCTION__, streamId, strerror(-res), res);
1108 }
1109 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001110 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1111 camera3_stream_buffer_t& sb = streamBuffers[b];
1112 sb.acquire_fence = -1;
1113 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1114 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001115 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1116 }
1117 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001118
1119 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1120 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1121 BufferRequestStatus::FAILED_UNKNOWN,
1122 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001123 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001124 return hardware::Void();
1125}
1126
1127hardware::Return<void> Camera3Device::returnStreamBuffers(
1128 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1129 if (!mUseHalBufManager) {
1130 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1131 __FUNCTION__, mId.string());
1132 return hardware::Void();
1133 }
1134
1135 for (const auto& buf : buffers) {
1136 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1137 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1138 continue;
1139 }
1140
1141 buffer_handle_t* buffer;
1142 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1143
1144 if (res != OK) {
1145 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1146 __FUNCTION__, buf.bufferId, buf.streamId);
1147 continue;
1148 }
1149
1150 camera3_stream_buffer_t streamBuffer;
1151 streamBuffer.buffer = buffer;
1152 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1153 streamBuffer.acquire_fence = -1;
1154 streamBuffer.release_fence = -1;
1155
1156 if (buf.releaseFence == nullptr) {
1157 streamBuffer.release_fence = -1;
1158 } else if (buf.releaseFence->numFds == 1) {
1159 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1160 } else {
1161 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1162 __FUNCTION__, buf.releaseFence->numFds);
1163 continue;
1164 }
1165
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001166 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1167 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001168 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1169 continue;
1170 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001171 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001172 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1173 }
1174 return hardware::Void();
1175}
1176
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001177hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001178 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001179 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001180 // Ideally we should grab mLock, but that can lead to deadlock, and
1181 // it's not super important to get up to date value of mStatus for this
1182 // warning print, hence skipping the lock here
1183 if (mStatus == STATUS_ERROR) {
1184 // Per API contract, HAL should act as closed after device error
1185 // But mStatus can be set to error by framework as well, so just log
1186 // a warning here.
1187 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001188 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001189
1190 if (mProcessCaptureResultLock.tryLock() != OK) {
1191 // This should never happen; it indicates a wrong client implementation
1192 // that doesn't follow the contract. But, we can be tolerant here.
1193 ALOGE("%s: callback overlapped! waiting 1s...",
1194 __FUNCTION__);
1195 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1196 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1197 __FUNCTION__);
1198 // really don't know what to do, so bail out.
1199 return hardware::Void();
1200 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001201 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001202 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001203 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001204 }
1205 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001206 return hardware::Void();
1207}
1208
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001209// Only one processCaptureResult should be called at a time, so
1210// the locks won't block. The locks are present here simply to enforce this.
1211hardware::Return<void> Camera3Device::processCaptureResult(
1212 const hardware::hidl_vec<
1213 hardware::camera::device::V3_2::CaptureResult>& results) {
1214 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1215
1216 // Ideally we should grab mLock, but that can lead to deadlock, and
1217 // it's not super important to get up to date value of mStatus for this
1218 // warning print, hence skipping the lock here
1219 if (mStatus == STATUS_ERROR) {
1220 // Per API contract, HAL should act as closed after device error
1221 // But mStatus can be set to error by framework as well, so just log
1222 // a warning here.
1223 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1224 }
1225
1226 if (mProcessCaptureResultLock.tryLock() != OK) {
1227 // This should never happen; it indicates a wrong client implementation
1228 // that doesn't follow the contract. But, we can be tolerant here.
1229 ALOGE("%s: callback overlapped! waiting 1s...",
1230 __FUNCTION__);
1231 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1232 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1233 __FUNCTION__);
1234 // really don't know what to do, so bail out.
1235 return hardware::Void();
1236 }
1237 }
1238 for (const auto& result : results) {
1239 processOneCaptureResultLocked(result, noPhysMetadata);
1240 }
1241 mProcessCaptureResultLock.unlock();
1242 return hardware::Void();
1243}
1244
1245status_t Camera3Device::readOneCameraMetadataLocked(
1246 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1247 const hardware::camera::device::V3_2::CameraMetadata& result) {
1248 if (fmqResultSize > 0) {
1249 resultMetadata.resize(fmqResultSize);
1250 if (mResultMetadataQueue == nullptr) {
1251 return NO_MEMORY; // logged in initialize()
1252 }
1253 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1254 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1255 __FUNCTION__, fmqResultSize);
1256 return INVALID_OPERATION;
1257 }
1258 } else {
1259 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1260 result.size());
1261 }
1262
1263 if (resultMetadata.size() != 0) {
1264 status_t res;
1265 const camera_metadata_t* metadata =
1266 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1267 size_t expected_metadata_size = resultMetadata.size();
1268 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1269 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1270 __FUNCTION__, strerror(-res), res);
1271 return INVALID_OPERATION;
1272 }
1273 }
1274
1275 return OK;
1276}
1277
Yifan Honga640c5a2017-04-12 16:30:31 -07001278void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001279 const hardware::camera::device::V3_2::CaptureResult& result,
1280 const hardware::hidl_vec<
1281 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001282 camera3_capture_result r;
1283 status_t res;
1284 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001285
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001286 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001287 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001288 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1289 if (res != OK) {
1290 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1291 __FUNCTION__, result.frameNumber);
1292 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001293 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001294 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001295
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001296 // Read and validate physical camera metadata
1297 size_t physResultCount = physicalCameraMetadatas.size();
1298 std::vector<const char*> physCamIds(physResultCount);
1299 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1300 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1301 physResultMetadata.resize(physResultCount);
1302 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1303 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1304 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1305 if (res != OK) {
1306 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1307 __FUNCTION__, result.frameNumber,
1308 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001309 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001310 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001311 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1312 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1313 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001314 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001315 r.num_physcam_metadata = physResultCount;
1316 r.physcam_ids = physCamIds.data();
1317 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001318
1319 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1320 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1321 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1322 auto& bDst = outputBuffers[i];
1323 const StreamBuffer &bSrc = result.outputBuffers[i];
1324
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001325 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1326 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001327 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1328 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001329 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001330 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001331 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001332
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001333 bool noBufferReturned = false;
1334 buffer_handle_t *buffer = nullptr;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001335 if (mUseHalBufManager) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001336 // This is suspicious most of the time but can be correct during flush where HAL
1337 // has to return capture result before a buffer is requested
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001338 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001339 if (bSrc.status == BufferStatus::OK) {
1340 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1341 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1342 // Still proceeds so other buffers can be returned
1343 }
1344 noBufferReturned = true;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001345 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001346 if (noBufferReturned) {
1347 res = OK;
1348 } else {
1349 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1350 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001351 } else {
1352 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1353 }
1354
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001355 if (res != OK) {
1356 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1357 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001358 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001359 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001360
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001361 bDst.buffer = buffer;
1362 bDst.status = mapHidlBufferStatus(bSrc.status);
1363 bDst.acquire_fence = -1;
1364 if (bSrc.releaseFence == nullptr) {
1365 bDst.release_fence = -1;
1366 } else if (bSrc.releaseFence->numFds == 1) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001367 if (noBufferReturned) {
1368 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
1369 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001370 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1371 } else {
1372 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1373 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001374 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001375 }
1376 }
1377 r.num_output_buffers = outputBuffers.size();
1378 r.output_buffers = outputBuffers.data();
1379
1380 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001381 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001382 r.input_buffer = nullptr;
1383 } else {
1384 if (mInputStream->getId() != result.inputBuffer.streamId) {
1385 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1386 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001387 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001388 }
1389 inputBuffer.stream = mInputStream->asHalStream();
1390 buffer_handle_t *buffer;
1391 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1392 &buffer);
1393 if (res != OK) {
1394 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1395 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001396 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001397 }
1398 inputBuffer.buffer = buffer;
1399 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1400 inputBuffer.acquire_fence = -1;
1401 if (result.inputBuffer.releaseFence == nullptr) {
1402 inputBuffer.release_fence = -1;
1403 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1404 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1405 } else {
1406 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1407 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001408 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001409 }
1410 r.input_buffer = &inputBuffer;
1411 }
1412
1413 r.partial_result = result.partialResult;
1414
1415 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001416}
1417
1418hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001419 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001420 // Ideally we should grab mLock, but that can lead to deadlock, and
1421 // it's not super important to get up to date value of mStatus for this
1422 // warning print, hence skipping the lock here
1423 if (mStatus == STATUS_ERROR) {
1424 // Per API contract, HAL should act as closed after device error
1425 // But mStatus can be set to error by framework as well, so just log
1426 // a warning here.
1427 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001428 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001429
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001430 for (const auto& msg : msgs) {
1431 notify(msg);
1432 }
1433 return hardware::Void();
1434}
1435
1436void Camera3Device::notify(
1437 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1438
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001439 camera3_notify_msg m;
1440 switch (msg.type) {
1441 case MsgType::ERROR:
1442 m.type = CAMERA3_MSG_ERROR;
1443 m.message.error.frame_number = msg.msg.error.frameNumber;
1444 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001445 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1446 if (stream == nullptr) {
1447 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1448 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001449 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001450 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001451 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001452 } else {
1453 m.message.error.error_stream = nullptr;
1454 }
1455 switch (msg.msg.error.errorCode) {
1456 case ErrorCode::ERROR_DEVICE:
1457 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1458 break;
1459 case ErrorCode::ERROR_REQUEST:
1460 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1461 break;
1462 case ErrorCode::ERROR_RESULT:
1463 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1464 break;
1465 case ErrorCode::ERROR_BUFFER:
1466 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1467 break;
1468 }
1469 break;
1470 case MsgType::SHUTTER:
1471 m.type = CAMERA3_MSG_SHUTTER;
1472 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1473 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1474 break;
1475 }
1476 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001477}
1478
Emilian Peevaebbe412018-01-15 13:53:24 +00001479status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001480 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001481 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001482 ATRACE_CALL();
1483
Emilian Peevaebbe412018-01-15 13:53:24 +00001484 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001485}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001486
Jianing Weicb0652e2014-03-12 18:29:36 -07001487status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1488 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001489 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001490
Emilian Peevaebbe412018-01-15 13:53:24 +00001491 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001492 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001493 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001494
Emilian Peevaebbe412018-01-15 13:53:24 +00001495 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001496 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497}
1498
Emilian Peevaebbe412018-01-15 13:53:24 +00001499status_t Camera3Device::setStreamingRequestList(
1500 const List<const PhysicalCameraSettingsList> &requestsList,
1501 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001502 ATRACE_CALL();
1503
Emilian Peevaebbe412018-01-15 13:53:24 +00001504 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001505}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506
1507sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001508 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001509 status_t res;
1510
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001511 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001512 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1513 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001514 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1515 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001516 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001517 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001518 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001519 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001520 } else if (mStatus == STATUS_UNCONFIGURED) {
1521 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001522 CLOGE("No streams configured");
1523 return NULL;
1524 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001525 }
1526
Shuzhen Wang0129d522016-10-30 22:43:41 -07001527 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001529}
1530
Jianing Weicb0652e2014-03-12 18:29:36 -07001531status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001532 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001533 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001535
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 switch (mStatus) {
1537 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001538 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 return INVALID_OPERATION;
1540 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001541 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001543 case STATUS_UNCONFIGURED:
1544 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 case STATUS_ACTIVE:
1546 // OK
1547 break;
1548 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001549 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 return INVALID_OPERATION;
1551 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001552 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001553
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001554 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001555}
1556
1557status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1558 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001559 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001560
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001561 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001562}
1563
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001564status_t Camera3Device::createInputStream(
1565 uint32_t width, uint32_t height, int format, int *id) {
1566 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001567 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001568 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001569 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001570 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1571 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001572
1573 status_t res;
1574 bool wasActive = false;
1575
1576 switch (mStatus) {
1577 case STATUS_ERROR:
1578 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1579 return INVALID_OPERATION;
1580 case STATUS_UNINITIALIZED:
1581 ALOGE("%s: Device not initialized", __FUNCTION__);
1582 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001583 case STATUS_UNCONFIGURED:
1584 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001585 // OK
1586 break;
1587 case STATUS_ACTIVE:
1588 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001589 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001590 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001591 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001592 return res;
1593 }
1594 wasActive = true;
1595 break;
1596 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001597 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001598 return INVALID_OPERATION;
1599 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001600 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001601
1602 if (mInputStream != 0) {
1603 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1604 return INVALID_OPERATION;
1605 }
1606
1607 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1608 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001609 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001610
1611 mInputStream = newStream;
1612
1613 *id = mNextStreamId++;
1614
1615 // Continue captures if active at start
1616 if (wasActive) {
1617 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001618 // Reuse current operating mode and session parameters for new stream config
1619 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001620 if (res != OK) {
1621 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1622 __FUNCTION__, mNextStreamId, strerror(-res), res);
1623 return res;
1624 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001625 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001626 }
1627
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001628 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001629 return OK;
1630}
1631
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001632status_t Camera3Device::StreamSet::add(
1633 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1634 if (stream == nullptr) {
1635 ALOGE("%s: cannot add null stream", __FUNCTION__);
1636 return BAD_VALUE;
1637 }
1638 std::lock_guard<std::mutex> lock(mLock);
1639 return mData.add(streamId, stream);
1640}
1641
1642ssize_t Camera3Device::StreamSet::remove(int streamId) {
1643 std::lock_guard<std::mutex> lock(mLock);
1644 return mData.removeItem(streamId);
1645}
1646
1647sp<camera3::Camera3OutputStreamInterface>
1648Camera3Device::StreamSet::get(int streamId) {
1649 std::lock_guard<std::mutex> lock(mLock);
1650 ssize_t idx = mData.indexOfKey(streamId);
1651 if (idx == NAME_NOT_FOUND) {
1652 return nullptr;
1653 }
1654 return mData.editValueAt(idx);
1655}
1656
1657sp<camera3::Camera3OutputStreamInterface>
1658Camera3Device::StreamSet::operator[] (size_t index) {
1659 std::lock_guard<std::mutex> lock(mLock);
1660 return mData.editValueAt(index);
1661}
1662
1663size_t Camera3Device::StreamSet::size() const {
1664 std::lock_guard<std::mutex> lock(mLock);
1665 return mData.size();
1666}
1667
1668void Camera3Device::StreamSet::clear() {
1669 std::lock_guard<std::mutex> lock(mLock);
1670 return mData.clear();
1671}
1672
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001673std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1674 std::lock_guard<std::mutex> lock(mLock);
1675 std::vector<int> streamIds(mData.size());
1676 for (size_t i = 0; i < mData.size(); i++) {
1677 streamIds[i] = mData.keyAt(i);
1678 }
1679 return streamIds;
1680}
1681
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001682status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001683 uint32_t width, uint32_t height, int format,
1684 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001685 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001686 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001687 ATRACE_CALL();
1688
1689 if (consumer == nullptr) {
1690 ALOGE("%s: consumer must not be null", __FUNCTION__);
1691 return BAD_VALUE;
1692 }
1693
1694 std::vector<sp<Surface>> consumers;
1695 consumers.push_back(consumer);
1696
1697 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001698 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1699 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001700}
1701
1702status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1703 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1704 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001705 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001706 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001707 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001708
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001709 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001710 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001711 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001712 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001713 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1714 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1715 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001716
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001717 status_t res;
1718 bool wasActive = false;
1719
1720 switch (mStatus) {
1721 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001722 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001723 return INVALID_OPERATION;
1724 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001725 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001726 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001727 case STATUS_UNCONFIGURED:
1728 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001729 // OK
1730 break;
1731 case STATUS_ACTIVE:
1732 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001733 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001734 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001735 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001736 return res;
1737 }
1738 wasActive = true;
1739 break;
1740 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001741 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001742 return INVALID_OPERATION;
1743 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001744 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001745
1746 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001747
Shuzhen Wang0129d522016-10-30 22:43:41 -07001748 if (consumers.size() == 0 && !hasDeferredConsumer) {
1749 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1750 return BAD_VALUE;
1751 }
Zhijun He5d677d12016-05-29 16:52:39 -07001752
Shuzhen Wang0129d522016-10-30 22:43:41 -07001753 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001754 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1755 return BAD_VALUE;
1756 }
1757
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001758 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001759 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001760 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001761 blobBufferSize = getPointCloudBufferSize();
1762 if (blobBufferSize <= 0) {
1763 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1764 return BAD_VALUE;
1765 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001766 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1767 blobBufferSize = width * height;
1768 } else {
1769 blobBufferSize = getJpegBufferSize(width, height);
1770 if (blobBufferSize <= 0) {
1771 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1772 return BAD_VALUE;
1773 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001774 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001775 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001776 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001777 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001778 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1779 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1780 if (rawOpaqueBufferSize <= 0) {
1781 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1782 return BAD_VALUE;
1783 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001784 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001785 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001786 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001787 } else if (isShared) {
1788 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1789 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001790 mTimestampOffset, physicalCameraId, streamSetId,
1791 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001792 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001793 newStream = new Camera3OutputStream(mNextStreamId,
1794 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001795 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001796 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001797 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001798 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001799 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001800 }
Emilian Peev40ead602017-09-26 15:46:36 +01001801
1802 size_t consumerCount = consumers.size();
1803 for (size_t i = 0; i < consumerCount; i++) {
1804 int id = newStream->getSurfaceId(consumers[i]);
1805 if (id < 0) {
1806 SET_ERR_L("Invalid surface id");
1807 return BAD_VALUE;
1808 }
1809 if (surfaceIds != nullptr) {
1810 surfaceIds->push_back(id);
1811 }
1812 }
1813
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001814 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001815
Emilian Peev08dd2452017-04-06 16:55:14 +01001816 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001817
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001818 res = mOutputStreams.add(mNextStreamId, newStream);
1819 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001820 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001821 return res;
1822 }
1823
1824 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001825 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001826
1827 // Continue captures if active at start
1828 if (wasActive) {
1829 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001830 // Reuse current operating mode and session parameters for new stream config
1831 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001832 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001833 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1834 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001835 return res;
1836 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001837 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001838 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001839 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001840 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001841}
1842
Emilian Peev710c1422017-08-30 11:19:38 +01001843status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001844 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001845 if (nullptr == streamInfo) {
1846 return BAD_VALUE;
1847 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001848 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001849 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001850
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001851 switch (mStatus) {
1852 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001853 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001854 return INVALID_OPERATION;
1855 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001856 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001857 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001858 case STATUS_UNCONFIGURED:
1859 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001860 case STATUS_ACTIVE:
1861 // OK
1862 break;
1863 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001864 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001865 return INVALID_OPERATION;
1866 }
1867
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001868 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1869 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001870 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001871 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001872 }
1873
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001874 streamInfo->width = stream->getWidth();
1875 streamInfo->height = stream->getHeight();
1876 streamInfo->format = stream->getFormat();
1877 streamInfo->dataSpace = stream->getDataSpace();
1878 streamInfo->formatOverridden = stream->isFormatOverridden();
1879 streamInfo->originalFormat = stream->getOriginalFormat();
1880 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1881 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001882 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001883}
1884
1885status_t Camera3Device::setStreamTransform(int id,
1886 int transform) {
1887 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001888 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001889 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001890
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001891 switch (mStatus) {
1892 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001893 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001894 return INVALID_OPERATION;
1895 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001896 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001897 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001898 case STATUS_UNCONFIGURED:
1899 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001900 case STATUS_ACTIVE:
1901 // OK
1902 break;
1903 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001904 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001905 return INVALID_OPERATION;
1906 }
1907
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001908 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1909 if (stream == nullptr) {
1910 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001911 return BAD_VALUE;
1912 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001913 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001914}
1915
1916status_t Camera3Device::deleteStream(int id) {
1917 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001918 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001919 Mutex::Autolock l(mLock);
1920 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001921
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001922 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001923
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001924 // CameraDevice semantics require device to already be idle before
1925 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001926 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001927 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001928 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001929 }
1930
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001931 if (mStatus == STATUS_ERROR) {
1932 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1933 __FUNCTION__, mId.string());
1934 return -EBUSY;
1935 }
1936
Igor Murashkin2fba5842013-04-22 14:03:54 -07001937 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001938 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001939 if (mInputStream != NULL && id == mInputStream->getId()) {
1940 deletedStream = mInputStream;
1941 mInputStream.clear();
1942 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001943 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001944 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001945 return BAD_VALUE;
1946 }
Zhijun He5f446352014-01-22 09:49:33 -08001947 }
1948
1949 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001950 if (stream != nullptr) {
1951 deletedStream = stream;
1952 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001953 }
1954
1955 // Free up the stream endpoint so that it can be used by some other stream
1956 res = deletedStream->disconnect();
1957 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001958 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001959 // fall through since we want to still list the stream as deleted.
1960 }
1961 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001962 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001963
1964 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001965}
1966
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001967status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001968 ATRACE_CALL();
1969 ALOGV("%s: E", __FUNCTION__);
1970
1971 Mutex::Autolock il(mInterfaceLock);
1972 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001973
Emilian Peev811d2952018-05-25 11:08:40 +01001974 // In case the client doesn't include any session parameter, try a
1975 // speculative configuration using the values from the last cached
1976 // default request.
1977 if (sessionParams.isEmpty() &&
1978 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1979 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1980 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1981 mLastTemplateId);
1982 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1983 operatingMode);
1984 }
1985
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001986 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1987}
1988
1989status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1990 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001991 //Filter out any incoming session parameters
1992 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001993 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1994 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001995 CameraMetadata filteredParams(availableSessionKeys.count);
1996 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1997 filteredParams.getAndLock());
1998 set_camera_metadata_vendor_id(meta, mVendorTagId);
1999 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002000 if (availableSessionKeys.count > 0) {
2001 for (size_t i = 0; i < availableSessionKeys.count; i++) {
2002 camera_metadata_ro_entry entry = params.find(
2003 availableSessionKeys.data.i32[i]);
2004 if (entry.count > 0) {
2005 filteredParams.update(entry);
2006 }
2007 }
2008 }
2009
2010 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07002011}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002012
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002013status_t Camera3Device::getInputBufferProducer(
2014 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002015 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002016 Mutex::Autolock il(mInterfaceLock);
2017 Mutex::Autolock l(mLock);
2018
2019 if (producer == NULL) {
2020 return BAD_VALUE;
2021 } else if (mInputStream == NULL) {
2022 return INVALID_OPERATION;
2023 }
2024
2025 return mInputStream->getInputBufferProducer(producer);
2026}
2027
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002028status_t Camera3Device::createDefaultRequest(int templateId,
2029 CameraMetadata *request) {
2030 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002031 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002032
2033 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2034 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002035 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002036 return BAD_VALUE;
2037 }
2038
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002039 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002040
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002041 {
2042 Mutex::Autolock l(mLock);
2043 switch (mStatus) {
2044 case STATUS_ERROR:
2045 CLOGE("Device has encountered a serious error");
2046 return INVALID_OPERATION;
2047 case STATUS_UNINITIALIZED:
2048 CLOGE("Device is not initialized!");
2049 return INVALID_OPERATION;
2050 case STATUS_UNCONFIGURED:
2051 case STATUS_CONFIGURED:
2052 case STATUS_ACTIVE:
2053 // OK
2054 break;
2055 default:
2056 SET_ERR_L("Unexpected status: %d", mStatus);
2057 return INVALID_OPERATION;
2058 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002059
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002060 if (!mRequestTemplateCache[templateId].isEmpty()) {
2061 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002062 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002063 return OK;
2064 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002065 }
2066
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002067 camera_metadata_t *rawRequest;
2068 status_t res = mInterface->constructDefaultRequestSettings(
2069 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002070
2071 {
2072 Mutex::Autolock l(mLock);
2073 if (res == BAD_VALUE) {
2074 ALOGI("%s: template %d is not supported on this camera device",
2075 __FUNCTION__, templateId);
2076 return res;
2077 } else if (res != OK) {
2078 CLOGE("Unable to construct request template %d: %s (%d)",
2079 templateId, strerror(-res), res);
2080 return res;
2081 }
2082
2083 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2084 mRequestTemplateCache[templateId].acquire(rawRequest);
2085
2086 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002087 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002088 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002089 return OK;
2090}
2091
2092status_t Camera3Device::waitUntilDrained() {
2093 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002094 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002095 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002096 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002097
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002098 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002099}
2100
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002101status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002102 switch (mStatus) {
2103 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002104 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002105 ALOGV("%s: Already idle", __FUNCTION__);
2106 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002107 case STATUS_CONFIGURED:
2108 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002109 case STATUS_ERROR:
2110 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002111 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002112 break;
2113 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002114 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002115 return INVALID_OPERATION;
2116 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002117 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2118 maxExpectedDuration);
2119 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002120 if (res != OK) {
2121 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2122 res);
2123 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002124 return res;
2125}
2126
Ruben Brunk183f0562015-08-12 12:55:02 -07002127
2128void Camera3Device::internalUpdateStatusLocked(Status status) {
2129 mStatus = status;
2130 mRecentStatusUpdates.add(mStatus);
2131 mStatusChanged.broadcast();
2132}
2133
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002134void Camera3Device::pauseStateNotify(bool enable) {
2135 Mutex::Autolock il(mInterfaceLock);
2136 Mutex::Autolock l(mLock);
2137
2138 mPauseStateNotify = enable;
2139}
2140
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002141// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002142status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002143 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002144
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002145 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2146 maxExpectedDuration);
2147 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002148 if (res != OK) {
2149 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002150 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002151 }
2152
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002153 return res;
2154}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002155
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002156// Resume after internalPauseAndWaitLocked
2157status_t Camera3Device::internalResumeLocked() {
2158 status_t res;
2159
2160 mRequestThread->setPaused(false);
2161
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002162 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2163 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002164 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2165 if (res != OK) {
2166 SET_ERR_L("Can't transition to active in %f seconds!",
2167 kActiveTimeout/1e9);
2168 }
2169 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002170 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002171}
2172
Ruben Brunk183f0562015-08-12 12:55:02 -07002173status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002174 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002175
2176 size_t startIndex = 0;
2177 if (mStatusWaiters == 0) {
2178 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2179 // this status list
2180 mRecentStatusUpdates.clear();
2181 } else {
2182 // If other threads are waiting on updates to this status list, set the position of the
2183 // first element that this list will check rather than clearing the list.
2184 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002185 }
2186
Ruben Brunk183f0562015-08-12 12:55:02 -07002187 mStatusWaiters++;
2188
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002189 // Notify HAL to start draining. We need to notify the HalInterface layer
2190 // even when the device is already IDLE, so HalInterface can reject incoming
2191 // requestStreamBuffers call.
2192 if (!active && mUseHalBufManager) {
2193 auto streamIds = mOutputStreams.getStreamIds();
2194 mRequestThread->signalPipelineDrain(streamIds);
2195 mRequestBufferSM.onWaitUntilIdle();
2196 }
2197
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002198 bool stateSeen = false;
2199 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002200 if (active == (mStatus == STATUS_ACTIVE)) {
2201 // Desired state is current
2202 break;
2203 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002204
2205 res = mStatusChanged.waitRelative(mLock, timeout);
2206 if (res != OK) break;
2207
Ruben Brunk183f0562015-08-12 12:55:02 -07002208 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2209 // transitions.
2210 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2211 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2212 __FUNCTION__);
2213
2214 // Encountered desired state since we began waiting
2215 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002216 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2217 stateSeen = true;
2218 break;
2219 }
2220 }
2221 } while (!stateSeen);
2222
Ruben Brunk183f0562015-08-12 12:55:02 -07002223 mStatusWaiters--;
2224
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002225 return res;
2226}
2227
2228
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002229status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002230 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002231 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002232
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002233 if (listener != NULL && mListener != NULL) {
2234 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2235 }
2236 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002237 mRequestThread->setNotificationListener(listener);
2238 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002239
2240 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002241}
2242
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002243bool Camera3Device::willNotify3A() {
2244 return false;
2245}
2246
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002247status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002248 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002249 status_t res;
2250 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002251
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002252 while (mResultQueue.empty()) {
2253 res = mResultSignal.waitRelative(mOutputLock, timeout);
2254 if (res == TIMED_OUT) {
2255 return res;
2256 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002257 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2258 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002259 return res;
2260 }
2261 }
2262 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002263}
2264
Jianing Weicb0652e2014-03-12 18:29:36 -07002265status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002266 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002267 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002268
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002269 if (mResultQueue.empty()) {
2270 return NOT_ENOUGH_DATA;
2271 }
2272
Jianing Weicb0652e2014-03-12 18:29:36 -07002273 if (frame == NULL) {
2274 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2275 return BAD_VALUE;
2276 }
2277
2278 CaptureResult &result = *(mResultQueue.begin());
2279 frame->mResultExtras = result.mResultExtras;
2280 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002281 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002282 mResultQueue.erase(mResultQueue.begin());
2283
2284 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002285}
2286
2287status_t Camera3Device::triggerAutofocus(uint32_t id) {
2288 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002289 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002290
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002291 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2292 // Mix-in this trigger into the next request and only the next request.
2293 RequestTrigger trigger[] = {
2294 {
2295 ANDROID_CONTROL_AF_TRIGGER,
2296 ANDROID_CONTROL_AF_TRIGGER_START
2297 },
2298 {
2299 ANDROID_CONTROL_AF_TRIGGER_ID,
2300 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002301 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002302 };
2303
2304 return mRequestThread->queueTrigger(trigger,
2305 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002306}
2307
2308status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2309 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002310 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002311
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002312 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2313 // Mix-in this trigger into the next request and only the next request.
2314 RequestTrigger trigger[] = {
2315 {
2316 ANDROID_CONTROL_AF_TRIGGER,
2317 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2318 },
2319 {
2320 ANDROID_CONTROL_AF_TRIGGER_ID,
2321 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002322 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002323 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002324
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002325 return mRequestThread->queueTrigger(trigger,
2326 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002327}
2328
2329status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2330 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002331 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002332
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002333 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2334 // Mix-in this trigger into the next request and only the next request.
2335 RequestTrigger trigger[] = {
2336 {
2337 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2338 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2339 },
2340 {
2341 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2342 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002343 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002344 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002345
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002346 return mRequestThread->queueTrigger(trigger,
2347 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002348}
2349
Jianing Weicb0652e2014-03-12 18:29:36 -07002350status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002351 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002352 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002353 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002354
Zhijun He7ef20392014-04-21 16:04:17 -07002355 {
2356 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002357
2358 // b/116514106 "disconnect()" can get called twice for the same device. The
2359 // camera device will not be initialized during the second run.
2360 if (mStatus == STATUS_UNINITIALIZED) {
2361 return OK;
2362 }
2363
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002364 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002365 }
2366
Emilian Peev08dd2452017-04-06 16:55:14 +01002367 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002368}
2369
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002370status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002371 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2372}
2373
2374status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002375 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002376 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002377 Mutex::Autolock il(mInterfaceLock);
2378 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002379
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002380 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2381 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002382 CLOGE("Stream %d does not exist", streamId);
2383 return BAD_VALUE;
2384 }
2385
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002386 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002387 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002388 return BAD_VALUE;
2389 }
2390
2391 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002392 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002393 return BAD_VALUE;
2394 }
2395
Ruben Brunkc78ac262015-08-13 17:58:46 -07002396 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002397}
2398
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002399status_t Camera3Device::tearDown(int streamId) {
2400 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002401 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002402 Mutex::Autolock il(mInterfaceLock);
2403 Mutex::Autolock l(mLock);
2404
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002405 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2406 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002407 CLOGE("Stream %d does not exist", streamId);
2408 return BAD_VALUE;
2409 }
2410
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002411 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2412 CLOGE("Stream %d is a target of a in-progress request", streamId);
2413 return BAD_VALUE;
2414 }
2415
2416 return stream->tearDown();
2417}
2418
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002419status_t Camera3Device::addBufferListenerForStream(int streamId,
2420 wp<Camera3StreamBufferListener> listener) {
2421 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002422 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002423 Mutex::Autolock il(mInterfaceLock);
2424 Mutex::Autolock l(mLock);
2425
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002426 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2427 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002428 CLOGE("Stream %d does not exist", streamId);
2429 return BAD_VALUE;
2430 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002431 stream->addBufferListener(listener);
2432
2433 return OK;
2434}
2435
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002436/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002437 * Methods called by subclasses
2438 */
2439
2440void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002441 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002442 {
2443 // Need mLock to safely update state and synchronize to current
2444 // state of methods in flight.
2445 Mutex::Autolock l(mLock);
2446 // We can get various system-idle notices from the status tracker
2447 // while starting up. Only care about them if we've actually sent
2448 // in some requests recently.
2449 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2450 return;
2451 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002452 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2453 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002454 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002455
2456 // Skip notifying listener if we're doing some user-transparent
2457 // state changes
2458 if (mPauseStateNotify) return;
2459 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002460
2461 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002462 {
2463 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002464 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002465 }
2466 if (idle && listener != NULL) {
2467 listener->notifyIdle();
2468 }
2469}
2470
Shuzhen Wang758c2152017-01-10 18:26:18 -08002471status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002472 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002473 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002474 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2475 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002476
2477 if (surfaceIds == nullptr) {
2478 return BAD_VALUE;
2479 }
2480
Zhijun He5d677d12016-05-29 16:52:39 -07002481 Mutex::Autolock il(mInterfaceLock);
2482 Mutex::Autolock l(mLock);
2483
Shuzhen Wang758c2152017-01-10 18:26:18 -08002484 if (consumers.size() == 0) {
2485 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002486 return BAD_VALUE;
2487 }
2488
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002489 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2490 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002491 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002492 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002493 }
Shuzhen Wang758c2152017-01-10 18:26:18 -08002494 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002495 if (res != OK) {
2496 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2497 return res;
2498 }
2499
Emilian Peev40ead602017-09-26 15:46:36 +01002500 for (auto &consumer : consumers) {
2501 int id = stream->getSurfaceId(consumer);
2502 if (id < 0) {
2503 CLOGE("Invalid surface id!");
2504 return BAD_VALUE;
2505 }
2506 surfaceIds->push_back(id);
2507 }
2508
Shuzhen Wang0129d522016-10-30 22:43:41 -07002509 if (stream->isConsumerConfigurationDeferred()) {
2510 if (!stream->isConfiguring()) {
2511 CLOGE("Stream %d was already fully configured.", streamId);
2512 return INVALID_OPERATION;
2513 }
Zhijun He5d677d12016-05-29 16:52:39 -07002514
Shuzhen Wang0129d522016-10-30 22:43:41 -07002515 res = stream->finishConfiguration();
2516 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002517 // If finishConfiguration fails due to abandoned surface, do not set
2518 // device to error state.
2519 bool isSurfaceAbandoned =
2520 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2521 if (!isSurfaceAbandoned) {
2522 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2523 stream->getId(), strerror(-res), res);
2524 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002525 return res;
2526 }
Zhijun He5d677d12016-05-29 16:52:39 -07002527 }
2528
2529 return OK;
2530}
2531
Emilian Peev40ead602017-09-26 15:46:36 +01002532status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2533 const std::vector<OutputStreamInfo> &outputInfo,
2534 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2535 Mutex::Autolock il(mInterfaceLock);
2536 Mutex::Autolock l(mLock);
2537
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002538 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2539 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002540 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002541 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002542 }
2543
2544 for (const auto &it : removedSurfaceIds) {
2545 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2546 CLOGE("Shared surface still part of a pending request!");
2547 return -EBUSY;
2548 }
2549 }
2550
Emilian Peev40ead602017-09-26 15:46:36 +01002551 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2552 if (res != OK) {
2553 CLOGE("Stream %d failed to update stream (error %d %s) ",
2554 streamId, res, strerror(-res));
2555 if (res == UNKNOWN_ERROR) {
2556 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2557 __FUNCTION__);
2558 }
2559 return res;
2560 }
2561
2562 return res;
2563}
2564
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002565status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2566 Mutex::Autolock il(mInterfaceLock);
2567 Mutex::Autolock l(mLock);
2568
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002569 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2570 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002571 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2572 return BAD_VALUE;
2573 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002574 return stream->dropBuffers(dropping);
2575}
2576
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002577/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002578 * Camera3Device private methods
2579 */
2580
2581sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002582 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002583 ATRACE_CALL();
2584 status_t res;
2585
2586 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002587 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002588
2589 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002590 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002591 if (inputStreams.count > 0) {
2592 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002593 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002594 CLOGE("Request references unknown input stream %d",
2595 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002596 return NULL;
2597 }
2598 // Lazy completion of stream configuration (allocation/registration)
2599 // on first use
2600 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002601 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002602 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002603 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002604 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002605 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002606 return NULL;
2607 }
2608 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002609 // Check if stream prepare is blocking requests.
2610 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002611 CLOGE("Request references an input stream that's being prepared!");
2612 return NULL;
2613 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002614
2615 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002616 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002617 }
2618
2619 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002620 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002621 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002622 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002623 return NULL;
2624 }
2625
2626 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002627 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2628 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002629 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002630 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002631 return NULL;
2632 }
Zhijun He5d677d12016-05-29 16:52:39 -07002633 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002634 auto iter = surfaceMap.find(streams.data.i32[i]);
2635 if (iter != surfaceMap.end()) {
2636 const std::vector<size_t>& surfaces = iter->second;
2637 for (const auto& surface : surfaces) {
2638 if (stream->isConsumerConfigurationDeferred(surface)) {
2639 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2640 "due to deferred consumer", stream->getId(), surface);
2641 return NULL;
2642 }
2643 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002644 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002645 }
2646
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002647 // Lazy completion of stream configuration (allocation/registration)
2648 // on first use
2649 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002650 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002651 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002652 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2653 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002654 return NULL;
2655 }
2656 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002657 // Check if stream prepare is blocking requests.
2658 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002659 CLOGE("Request references an output stream that's being prepared!");
2660 return NULL;
2661 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002662
2663 newRequest->mOutputStreams.push(stream);
2664 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002665 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002666 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002667
2668 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002669}
2670
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002671bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2672 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2673 Size size = mSupportedOpaqueInputSizes[i];
2674 if (size.width == width && size.height == height) {
2675 return true;
2676 }
2677 }
2678
2679 return false;
2680}
2681
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002682void Camera3Device::cancelStreamsConfigurationLocked() {
2683 int res = OK;
2684 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2685 res = mInputStream->cancelConfiguration();
2686 if (res != OK) {
2687 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2688 mInputStream->getId(), strerror(-res), res);
2689 }
2690 }
2691
2692 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002693 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002694 if (outputStream->isConfiguring()) {
2695 res = outputStream->cancelConfiguration();
2696 if (res != OK) {
2697 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2698 outputStream->getId(), strerror(-res), res);
2699 }
2700 }
2701 }
2702
2703 // Return state to that at start of call, so that future configures
2704 // properly clean things up
2705 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2706 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002707
2708 res = mPreparerThread->resume();
2709 if (res != OK) {
2710 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2711 }
2712}
2713
2714bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2715 ATRACE_CALL();
2716 bool ret = false;
2717
2718 Mutex::Autolock il(mInterfaceLock);
2719 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2720
2721 Mutex::Autolock l(mLock);
2722 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2723 if (rc == NO_ERROR) {
2724 mNeedConfig = true;
2725 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2726 if (rc == NO_ERROR) {
2727 ret = true;
2728 mPauseStateNotify = false;
2729 //Moving to active state while holding 'mLock' is important.
2730 //There could be pending calls to 'create-/deleteStream' which
2731 //will trigger another stream configuration while the already
2732 //present streams end up with outstanding buffers that will
2733 //not get drained.
2734 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002735 } else if (rc == DEAD_OBJECT) {
2736 // DEAD_OBJECT can be returned if either the consumer surface is
2737 // abandoned, or the HAL has died.
2738 // - If the HAL has died, configureStreamsLocked call will set
2739 // device to error state,
2740 // - If surface is abandoned, we should not set device to error
2741 // state.
2742 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002743 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002744 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002745 }
2746 } else {
2747 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2748 }
2749
2750 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002751}
2752
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002753status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002754 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002755 ATRACE_CALL();
2756 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002757
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002758 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002759 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002760 return INVALID_OPERATION;
2761 }
2762
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002763 if (operatingMode < 0) {
2764 CLOGE("Invalid operating mode: %d", operatingMode);
2765 return BAD_VALUE;
2766 }
2767
2768 bool isConstrainedHighSpeed =
2769 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2770 operatingMode;
2771
2772 if (mOperatingMode != operatingMode) {
2773 mNeedConfig = true;
2774 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2775 mOperatingMode = operatingMode;
2776 }
2777
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002778 if (!mNeedConfig) {
2779 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2780 return OK;
2781 }
2782
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002783 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2784 // adding a dummy stream instead.
2785 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2786 if (mOutputStreams.size() == 0) {
2787 addDummyStreamLocked();
2788 } else {
2789 tryRemoveDummyStreamLocked();
2790 }
2791
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002792 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002793 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002794
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002795 mPreparerThread->pause();
2796
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002797 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002798 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002799 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2800
2801 Vector<camera3_stream_t*> streams;
2802 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002803 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002804
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002805
2806 if (mInputStream != NULL) {
2807 camera3_stream_t *inputStream;
2808 inputStream = mInputStream->startConfiguration();
2809 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002810 CLOGE("Can't start input stream configuration");
2811 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002812 return INVALID_OPERATION;
2813 }
2814 streams.add(inputStream);
2815 }
2816
2817 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002818
2819 // Don't configure bidi streams twice, nor add them twice to the list
2820 if (mOutputStreams[i].get() ==
2821 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2822
2823 config.num_streams--;
2824 continue;
2825 }
2826
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002827 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002828 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002829 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002830 CLOGE("Can't start output stream configuration");
2831 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002832 return INVALID_OPERATION;
2833 }
2834 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002835
2836 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2837 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002838 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2839 // always occupy the initial entry.
2840 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002841 getJpegBufferSize(outputStream->width, outputStream->height));
2842 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002843 }
2844
2845 config.streams = streams.editArray();
2846
2847 // Do the HAL configuration; will potentially touch stream
2848 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002849
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002850 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002851 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002852 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002853
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002854 if (res == BAD_VALUE) {
2855 // HAL rejected this set of streams as unsupported, clean up config
2856 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002857 CLOGE("Set of requested inputs/outputs not supported by HAL");
2858 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002859 return BAD_VALUE;
2860 } else if (res != OK) {
2861 // Some other kind of error from configure_streams - this is not
2862 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002863 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2864 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002865 return res;
2866 }
2867
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002868 // Finish all stream configuration immediately.
2869 // TODO: Try to relax this later back to lazy completion, which should be
2870 // faster
2871
Igor Murashkin073f8572013-05-02 14:59:28 -07002872 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002873 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002874 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002875 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002876 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002877 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002878 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2879 return DEAD_OBJECT;
2880 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002881 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002882 }
2883 }
2884
2885 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002886 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002887 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002888 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002889 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002890 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002891 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002892 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002893 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2894 return DEAD_OBJECT;
2895 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002896 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002897 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002898 }
2899 }
2900
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002901 // Request thread needs to know to avoid using repeat-last-settings protocol
2902 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002903 if (notifyRequestThread) {
2904 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2905 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002906
Zhijun He90f7c372016-08-16 16:19:43 -07002907 char value[PROPERTY_VALUE_MAX];
2908 property_get("camera.fifo.disable", value, "0");
2909 int32_t disableFifo = atoi(value);
2910 if (disableFifo != 1) {
2911 // Boost priority of request thread to SCHED_FIFO.
2912 pid_t requestThreadTid = mRequestThread->getTid();
2913 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002914 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002915 if (res != OK) {
2916 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2917 strerror(-res), res);
2918 } else {
2919 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2920 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002921 }
2922
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002923 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002924 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2925 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2926 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2927 sessionParams.unlock(newSessionParams);
2928 mSessionParams.unlock(currentSessionParams);
2929 if (updateSessionParams) {
2930 mSessionParams = sessionParams;
2931 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002932
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002933 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002934
Ruben Brunk183f0562015-08-12 12:55:02 -07002935 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2936 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002937
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002938 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002939
Zhijun He0a210512014-07-24 13:45:15 -07002940 // tear down the deleted streams after configure streams.
2941 mDeletedStreams.clear();
2942
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002943 auto rc = mPreparerThread->resume();
2944 if (rc != OK) {
2945 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2946 return rc;
2947 }
2948
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002949 if (mDummyStreamId == NO_STREAM) {
2950 mRequestBufferSM.onStreamsConfigured();
2951 }
2952
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002953 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002954}
2955
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002956status_t Camera3Device::addDummyStreamLocked() {
2957 ATRACE_CALL();
2958 status_t res;
2959
2960 if (mDummyStreamId != NO_STREAM) {
2961 // Should never be adding a second dummy stream when one is already
2962 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002963 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2964 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002965 return INVALID_OPERATION;
2966 }
2967
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002968 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002969
2970 sp<Camera3OutputStreamInterface> dummyStream =
2971 new Camera3DummyStream(mNextStreamId);
2972
2973 res = mOutputStreams.add(mNextStreamId, dummyStream);
2974 if (res < 0) {
2975 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2976 return res;
2977 }
2978
2979 mDummyStreamId = mNextStreamId;
2980 mNextStreamId++;
2981
2982 return OK;
2983}
2984
2985status_t Camera3Device::tryRemoveDummyStreamLocked() {
2986 ATRACE_CALL();
2987 status_t res;
2988
2989 if (mDummyStreamId == NO_STREAM) return OK;
2990 if (mOutputStreams.size() == 1) return OK;
2991
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002992 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002993
2994 // Ok, have a dummy stream and there's at least one other output stream,
2995 // so remove the dummy
2996
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002997 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2998 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002999 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3000 return INVALID_OPERATION;
3001 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003002 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003003
3004 // Free up the stream endpoint so that it can be used by some other stream
3005 res = deletedStream->disconnect();
3006 if (res != OK) {
3007 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3008 // fall through since we want to still list the stream as deleted.
3009 }
3010 mDeletedStreams.add(deletedStream);
3011 mDummyStreamId = NO_STREAM;
3012
3013 return res;
3014}
3015
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003016void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003017 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003018 Mutex::Autolock l(mLock);
3019 va_list args;
3020 va_start(args, fmt);
3021
3022 setErrorStateLockedV(fmt, args);
3023
3024 va_end(args);
3025}
3026
3027void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003028 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003029 Mutex::Autolock l(mLock);
3030 setErrorStateLockedV(fmt, args);
3031}
3032
3033void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3034 va_list args;
3035 va_start(args, fmt);
3036
3037 setErrorStateLockedV(fmt, args);
3038
3039 va_end(args);
3040}
3041
3042void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003043 // Print out all error messages to log
3044 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003045 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003046
3047 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003048 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003049
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003050 mErrorCause = errorCause;
3051
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003052 if (mRequestThread != nullptr) {
3053 mRequestThread->setPaused(true);
3054 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003055 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003056
3057 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003058 sp<NotificationListener> listener = mListener.promote();
3059 if (listener != NULL) {
3060 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003061 CaptureResultExtras());
3062 }
3063
3064 // Save stack trace. View by dumping it later.
3065 CameraTraces::saveTrace();
3066 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003067}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003068
3069/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003070 * In-flight request management
3071 */
3072
Jianing Weicb0652e2014-03-12 18:29:36 -07003073status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003074 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003075 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003076 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003077 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003078 ATRACE_CALL();
3079 Mutex::Autolock l(mInFlightLock);
3080
3081 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003082 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003083 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3084 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003085 if (res < 0) return res;
3086
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003087 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003088 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3089 // avoid a deadlock during reprocess requests.
3090 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003091 if (mStatusTracker != nullptr) {
3092 mStatusTracker->markComponentActive(mInFlightStatusId);
3093 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003094 }
3095
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003096 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003097 return OK;
3098}
3099
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003100void Camera3Device::returnOutputBuffers(
3101 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003102 nsecs_t timestamp, bool timestampIncreasing,
3103 const SurfaceMap& outputSurfaces,
3104 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003105
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003106 for (size_t i = 0; i < numBuffers; i++)
3107 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003108 if (outputBuffers[i].buffer == nullptr) {
3109 if (!mUseHalBufManager) {
3110 // With HAL buffer management API, HAL sometimes will have to return buffers that
3111 // has not got a output buffer handle filled yet. This is though illegal if HAL
3112 // buffer management API is not being used.
3113 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3114 }
3115 continue;
3116 }
3117
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003118 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3119 int streamId = stream->getId();
3120 const auto& it = outputSurfaces.find(streamId);
3121 status_t res = OK;
3122 if (it != outputSurfaces.end()) {
3123 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003124 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3125 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003126 } else {
3127 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003128 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3129 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003130 }
3131
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003132 // Note: stream may be deallocated at this point, if this buffer was
3133 // the last reference to it.
3134 if (res != OK) {
3135 ALOGE("Can't return buffer to its stream: %s (%d)",
3136 strerror(-res), res);
3137 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003138
3139 // Long processing consumers can cause returnBuffer timeout for shared stream
3140 // If that happens, cancel the buffer and send a buffer error to client
3141 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3142 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3143 // cancel the buffer
3144 camera3_stream_buffer_t sb = outputBuffers[i];
3145 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003146 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3147 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003148
3149 // notify client buffer error
3150 sp<NotificationListener> listener;
3151 {
3152 Mutex::Autolock l(mOutputLock);
3153 listener = mListener.promote();
3154 }
3155
3156 if (listener != nullptr) {
3157 CaptureResultExtras extras = inResultExtras;
3158 extras.errorStreamId = streamId;
3159 listener->notifyError(
3160 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3161 extras);
3162 }
3163 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003164 }
3165}
3166
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003167void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003168 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003169 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003170 mInFlightMap.removeItemsAt(idx, 1);
3171
3172 // Indicate idle inFlightMap to the status tracker
3173 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003174 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003175 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3176 // avoid a deadlock during reprocess requests.
3177 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003178 if (mStatusTracker != nullptr) {
3179 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3180 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003181 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003182 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003183}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003184
3185void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3186
3187 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3188 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3189
3190 nsecs_t sensorTimestamp = request.sensorTimestamp;
3191 nsecs_t shutterTimestamp = request.shutterTimestamp;
3192
3193 // Check if it's okay to remove the request from InFlightMap:
3194 // In the case of a successful request:
3195 // all input and output buffers, all result metadata, shutter callback
3196 // arrived.
3197 // In the case of a unsuccessful request:
3198 // all input and output buffers arrived.
3199 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003200 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003201 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003202 if (request.stillCapture) {
3203 ATRACE_ASYNC_END("still capture", frameNumber);
3204 }
3205
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003206 ATRACE_ASYNC_END("frame capture", frameNumber);
3207
Shuzhen Wang403044a2017-02-26 23:29:04 -08003208 // Sanity check - if sensor timestamp matches shutter timestamp in the
3209 // case of request having callback.
3210 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003211 sensorTimestamp != shutterTimestamp) {
3212 SET_ERR("sensor timestamp (%" PRId64
3213 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3214 sensorTimestamp, frameNumber, shutterTimestamp);
3215 }
3216
3217 // for an unsuccessful request, it may have pending output buffers to
3218 // return.
3219 assert(request.requestStatus != OK ||
3220 request.pendingOutputBuffers.size() == 0);
3221 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003222 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3223 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003224
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003225 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003226 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3227 }
3228
3229 // Sanity check - if we have too many in-flight frames, something has
3230 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003231 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003232 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003233 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3234 kInFlightWarnLimitHighSpeed) {
3235 CLOGE("In-flight list too large for high speed configuration: %zu",
3236 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003237 }
3238}
3239
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003240void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003241 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003242 { // First return buffers cached in mInFlightMap
3243 Mutex::Autolock l(mInFlightLock);
3244 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3245 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3246 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003247 request.pendingOutputBuffers.size(), 0,
3248 /*timestampIncreasing*/true, request.outputSurfaces,
3249 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003250 }
3251 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003252 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003253 }
3254
3255 // Then return all inflight buffers not returned by HAL
3256 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3257 mInterface->getInflightBufferKeys(&inflightKeys);
3258
3259 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3260 for (auto& pair : inflightKeys) {
3261 int32_t frameNumber = pair.first;
3262 int32_t streamId = pair.second;
3263 buffer_handle_t* buffer;
3264 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3265 if (res != OK) {
3266 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3267 __FUNCTION__, frameNumber, streamId);
3268 continue;
3269 }
3270
3271 camera3_stream_buffer_t streamBuffer;
3272 streamBuffer.buffer = buffer;
3273 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3274 streamBuffer.acquire_fence = -1;
3275 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003276
3277 // First check if the buffer belongs to deleted stream
3278 bool streamDeleted = false;
3279 for (auto& stream : mDeletedStreams) {
3280 if (streamId == stream->getId()) {
3281 streamDeleted = true;
3282 // Return buffer to deleted stream
3283 camera3_stream* halStream = stream->asHalStream();
3284 streamBuffer.stream = halStream;
3285 switch (halStream->stream_type) {
3286 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003287 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3288 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003289 if (res != OK) {
3290 ALOGE("%s: Can't return output buffer for frame %d to"
3291 " stream %d: %s (%d)", __FUNCTION__,
3292 frameNumber, streamId, strerror(-res), res);
3293 }
3294 break;
3295 case CAMERA3_STREAM_INPUT:
3296 res = stream->returnInputBuffer(streamBuffer);
3297 if (res != OK) {
3298 ALOGE("%s: Can't return input buffer for frame %d to"
3299 " stream %d: %s (%d)", __FUNCTION__,
3300 frameNumber, streamId, strerror(-res), res);
3301 }
3302 break;
3303 default: // Bi-direcitonal stream is deprecated
3304 ALOGE("%s: stream %d has unknown stream type %d",
3305 __FUNCTION__, streamId, halStream->stream_type);
3306 break;
3307 }
3308 break;
3309 }
3310 }
3311 if (streamDeleted) {
3312 continue;
3313 }
3314
3315 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003316 if (streamId == inputStreamId) {
3317 streamBuffer.stream = mInputStream->asHalStream();
3318 res = mInputStream->returnInputBuffer(streamBuffer);
3319 if (res != OK) {
3320 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003321 " stream %d: %s (%d)", __FUNCTION__,
3322 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003323 }
3324 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003325 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3326 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003327 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3328 continue;
3329 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003330 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003331 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3332 }
3333 }
3334}
3335
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003336void Camera3Device::insertResultLocked(CaptureResult *result,
3337 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003338 if (result == nullptr) return;
3339
Emilian Peev71c73a22017-03-21 16:35:51 +00003340 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3341 result->mMetadata.getAndLock());
3342 set_camera_metadata_vendor_id(meta, mVendorTagId);
3343 result->mMetadata.unlock(meta);
3344
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003345 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3346 (int32_t*)&frameNumber, 1) != OK) {
3347 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3348 return;
3349 }
3350
3351 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3352 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3353 return;
3354 }
3355
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003356 // Valid result, insert into queue
3357 List<CaptureResult>::iterator queuedResult =
3358 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3359 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3360 ", burstId = %" PRId32, __FUNCTION__,
3361 queuedResult->mResultExtras.requestId,
3362 queuedResult->mResultExtras.frameNumber,
3363 queuedResult->mResultExtras.burstId);
3364
3365 mResultSignal.signal();
3366}
3367
3368
3369void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003370 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003371 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003372 Mutex::Autolock l(mOutputLock);
3373
3374 CaptureResult captureResult;
3375 captureResult.mResultExtras = resultExtras;
3376 captureResult.mMetadata = partialResult;
3377
Shuzhen Wang268a1362018-10-16 16:32:59 -07003378 // Fix up result metadata for monochrome camera.
3379 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3380 if (res != OK) {
3381 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3382 return;
3383 }
3384
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003385 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003386}
3387
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003388
3389void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3390 CaptureResultExtras &resultExtras,
3391 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003392 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003393 bool reprocess,
3394 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003395 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003396 if (pendingMetadata.isEmpty())
3397 return;
3398
3399 Mutex::Autolock l(mOutputLock);
3400
3401 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003402 if (reprocess) {
3403 if (frameNumber < mNextReprocessResultFrameNumber) {
3404 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003405 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003406 frameNumber, mNextReprocessResultFrameNumber);
3407 return;
3408 }
3409 mNextReprocessResultFrameNumber = frameNumber + 1;
3410 } else {
3411 if (frameNumber < mNextResultFrameNumber) {
3412 SET_ERR("Out-of-order capture result metadata submitted! "
3413 "(got frame number %d, expecting %d)",
3414 frameNumber, mNextResultFrameNumber);
3415 return;
3416 }
3417 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003418 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003419
3420 CaptureResult captureResult;
3421 captureResult.mResultExtras = resultExtras;
3422 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003423 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003424
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003425 // Append any previous partials to form a complete result
3426 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3427 captureResult.mMetadata.append(collectedPartialResult);
3428 }
3429
3430 captureResult.mMetadata.sort();
3431
3432 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003433 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3434 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003435 SET_ERR("No timestamp provided by HAL for frame %d!",
3436 frameNumber);
3437 return;
3438 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003439 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3440 camera_metadata_entry timestamp =
3441 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3442 if (timestamp.count == 0) {
3443 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3444 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3445 return;
3446 }
3447 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003448
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003449 // Fix up some result metadata to account for HAL-level distortion correction
3450 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3451 if (res != OK) {
3452 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3453 frameNumber, strerror(res), res);
3454 return;
3455 }
Shuzhen Wang268a1362018-10-16 16:32:59 -07003456 // Fix up result metadata for monochrome camera.
3457 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3458 if (res != OK) {
3459 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3460 return;
3461 }
3462 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3463 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3464 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3465 physicalMetadata.mPhysicalCameraMetadata);
3466 if (res != OK) {
3467 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3468 return;
3469 }
3470 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003471
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003472 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3473 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3474
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003475 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003476}
3477
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003478/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003479 * Camera HAL device callback methods
3480 */
3481
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003482void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003483 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003484
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003485 status_t res;
3486
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003487 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003488 if (result->result == NULL && result->num_output_buffers == 0 &&
3489 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003490 SET_ERR("No result data provided by HAL for frame %d",
3491 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003492 return;
3493 }
Zhijun He204e3292014-07-14 17:09:23 -07003494
Zhijun He204e3292014-07-14 17:09:23 -07003495 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003496 result->result != NULL &&
3497 result->partial_result != 1) {
3498 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3499 " if partial result is not supported",
3500 frameNumber, result->partial_result);
3501 return;
3502 }
3503
3504 bool isPartialResult = false;
3505 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003506 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003507
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003508 // Get shutter timestamp and resultExtras from list of in-flight requests,
3509 // where it was added by the shutter notification for this frame. If the
3510 // shutter timestamp isn't received yet, append the output buffers to the
3511 // in-flight request and they will be returned when the shutter timestamp
3512 // arrives. Update the in-flight status and remove the in-flight entry if
3513 // all result data and shutter timestamp have been received.
3514 nsecs_t shutterTimestamp = 0;
3515
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003516 {
3517 Mutex::Autolock l(mInFlightLock);
3518 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3519 if (idx == NAME_NOT_FOUND) {
3520 SET_ERR("Unknown frame number for capture result: %d",
3521 frameNumber);
3522 return;
3523 }
3524 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003525 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3526 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003527 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003528 __FUNCTION__, request.resultExtras.requestId,
3529 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003530 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003531 // Always update the partial count to the latest one if it's not 0
3532 // (buffers only). When framework aggregates adjacent partial results
3533 // into one, the latest partial count will be used.
3534 if (result->partial_result != 0)
3535 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003536
3537 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003538 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003539 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3540 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3541 " the range of [1, %d] when metadata is included in the result",
3542 frameNumber, result->partial_result, mNumPartialResults);
3543 return;
3544 }
3545 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003546 if (isPartialResult && result->num_physcam_metadata) {
3547 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3548 " physical camera result", frameNumber);
3549 return;
3550 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003551 if (isPartialResult) {
3552 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003553 }
3554
Shuzhen Wang4a472662017-02-26 23:29:04 -08003555 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003556 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003557 sendPartialCaptureResult(result->result, request.resultExtras,
3558 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003559 }
3560 }
3561
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003562 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003563 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003564
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003565 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003566 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003567 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3568 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3569 request.physicalCameraIds.size(), result->num_physcam_metadata);
3570 return;
3571 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003572 if (request.haveResultMetadata) {
3573 SET_ERR("Called multiple times with metadata for frame %d",
3574 frameNumber);
3575 return;
3576 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003577 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3578 String8 physicalId(result->physcam_ids[i]);
3579 std::set<String8>::iterator cameraIdIter =
3580 request.physicalCameraIds.find(physicalId);
3581 if (cameraIdIter != request.physicalCameraIds.end()) {
3582 request.physicalCameraIds.erase(cameraIdIter);
3583 } else {
3584 SET_ERR("Total result for frame %d has already returned for camera %s",
3585 frameNumber, physicalId.c_str());
3586 return;
3587 }
3588 }
Zhijun He204e3292014-07-14 17:09:23 -07003589 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003590 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003591 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003592 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003593 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003594 request.haveResultMetadata = true;
3595 }
3596
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003597 uint32_t numBuffersReturned = result->num_output_buffers;
3598 if (result->input_buffer != NULL) {
3599 if (hasInputBufferInRequest) {
3600 numBuffersReturned += 1;
3601 } else {
3602 ALOGW("%s: Input buffer should be NULL if there is no input"
3603 " buffer sent in the request",
3604 __FUNCTION__);
3605 }
3606 }
3607 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003608 if (request.numBuffersLeft < 0) {
3609 SET_ERR("Too many buffers returned for frame %d",
3610 frameNumber);
3611 return;
3612 }
3613
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003614 camera_metadata_ro_entry_t entry;
3615 res = find_camera_metadata_ro_entry(result->result,
3616 ANDROID_SENSOR_TIMESTAMP, &entry);
3617 if (res == OK && entry.count == 1) {
3618 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003619 }
3620
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003621 // If shutter event isn't received yet, append the output buffers to
3622 // the in-flight request. Otherwise, return the output buffers to
3623 // streams.
3624 if (shutterTimestamp == 0) {
3625 request.pendingOutputBuffers.appendArray(result->output_buffers,
3626 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003627 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003628 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003629 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003630 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3631 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003632 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003633
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003634 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003635 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3636 CameraMetadata physicalMetadata;
3637 physicalMetadata.append(result->physcam_metadata[i]);
3638 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3639 physicalMetadata});
3640 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003641 if (shutterTimestamp == 0) {
3642 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003643 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003644 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003645 CameraMetadata metadata;
3646 metadata = result->result;
3647 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003648 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003649 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003650 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003651 }
3652
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003653 removeInFlightRequestIfReadyLocked(idx);
3654 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003655
Zhijun Hef0d962a2014-06-30 10:24:11 -07003656 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003657 if (hasInputBufferInRequest) {
3658 Camera3Stream *stream =
3659 Camera3Stream::cast(result->input_buffer->stream);
3660 res = stream->returnInputBuffer(*(result->input_buffer));
3661 // Note: stream may be deallocated at this point, if this buffer was the
3662 // last reference to it.
3663 if (res != OK) {
3664 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3665 " its stream:%s (%d)", __FUNCTION__,
3666 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003667 }
3668 } else {
3669 ALOGW("%s: Input buffer should be NULL if there is no input"
3670 " buffer sent in the request, skipping input buffer return.",
3671 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003672 }
3673 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003674}
3675
3676void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003677 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003678 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003679 {
3680 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003681 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003682 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003683
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003684 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003685 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003686 return;
3687 }
3688
3689 switch (msg->type) {
3690 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003691 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003692 break;
3693 }
3694 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003695 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003696 break;
3697 }
3698 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003699 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003700 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003701 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003702}
3703
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003704void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003705 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003706 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003707 // Map camera HAL error codes to ICameraDeviceCallback error codes
3708 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003709 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003710 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003711 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003712 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003713 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003714 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003715 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003716 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003717 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003718 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003719 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003720 };
3721
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003722 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003723 ((msg.error_code >= 0) &&
3724 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3725 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003726 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003727
3728 int streamId = 0;
3729 if (msg.error_stream != NULL) {
3730 Camera3Stream *stream =
3731 Camera3Stream::cast(msg.error_stream);
3732 streamId = stream->getId();
3733 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003734 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3735 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003736 streamId, msg.error_code);
3737
3738 CaptureResultExtras resultExtras;
3739 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003740 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003741 // SET_ERR calls notifyError
3742 SET_ERR("Camera HAL reported serious device error");
3743 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003744 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3745 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3746 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003747 {
3748 Mutex::Autolock l(mInFlightLock);
3749 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3750 if (idx >= 0) {
3751 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3752 r.requestStatus = msg.error_code;
3753 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003754 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3755 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3756 errorCode) {
3757 r.skipResultMetadata = true;
3758 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003759 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3760 errorCode) {
3761 // In case of missing result check whether the buffers
3762 // returned. If they returned, then remove inflight
3763 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003764 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3765 // otherwise we are depending on HAL to send the buffers back after
3766 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003767 removeInFlightRequestIfReadyLocked(idx);
3768 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003769 } else {
3770 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003771 ALOGE("Camera %s: %s: cannot find in-flight request on "
3772 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003773 resultExtras.frameNumber);
3774 }
3775 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003776 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003777 if (listener != NULL) {
3778 listener->notifyError(errorCode, resultExtras);
3779 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003780 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003781 }
3782 break;
3783 default:
3784 // SET_ERR calls notifyError
3785 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3786 break;
3787 }
3788}
3789
3790void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003791 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003792 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003793 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003794
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003795 // Set timestamp for the request in the in-flight tracking
3796 // and get the request ID to send upstream
3797 {
3798 Mutex::Autolock l(mInFlightLock);
3799 idx = mInFlightMap.indexOfKey(msg.frame_number);
3800 if (idx >= 0) {
3801 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003802
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003803 // Verify ordering of shutter notifications
3804 {
3805 Mutex::Autolock l(mOutputLock);
3806 // TODO: need to track errors for tighter bounds on expected frame number.
3807 if (r.hasInputBuffer) {
3808 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3809 SET_ERR("Shutter notification out-of-order. Expected "
3810 "notification for frame %d, got frame %d",
3811 mNextReprocessShutterFrameNumber, msg.frame_number);
3812 return;
3813 }
3814 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3815 } else {
3816 if (msg.frame_number < mNextShutterFrameNumber) {
3817 SET_ERR("Shutter notification out-of-order. Expected "
3818 "notification for frame %d, got frame %d",
3819 mNextShutterFrameNumber, msg.frame_number);
3820 return;
3821 }
3822 mNextShutterFrameNumber = msg.frame_number + 1;
3823 }
3824 }
3825
Shuzhen Wang4a472662017-02-26 23:29:04 -08003826 r.shutterTimestamp = msg.timestamp;
3827 if (r.hasCallback) {
3828 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003829 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003830 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003831 // Call listener, if any
3832 if (listener != NULL) {
3833 listener->notifyShutter(r.resultExtras, msg.timestamp);
3834 }
3835 // send pending result and buffers
3836 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3837 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003838 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003839 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003840 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003841 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003842 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3843 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003844 r.pendingOutputBuffers.clear();
3845
3846 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003847 }
3848 }
3849 if (idx < 0) {
3850 SET_ERR("Shutter notification for non-existent frame number %d",
3851 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003852 }
3853}
3854
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003855CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003856 ALOGV("%s", __FUNCTION__);
3857
Igor Murashkin1e479c02013-09-06 16:55:14 -07003858 CameraMetadata retVal;
3859
3860 if (mRequestThread != NULL) {
3861 retVal = mRequestThread->getLatestRequest();
3862 }
3863
Igor Murashkin1e479c02013-09-06 16:55:14 -07003864 return retVal;
3865}
3866
Jianing Weicb0652e2014-03-12 18:29:36 -07003867
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003868void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3869 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3870 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3871}
3872
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003873/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003874 * HalInterface inner class methods
3875 */
3876
Yifan Hongf79b5542017-04-11 14:44:25 -07003877Camera3Device::HalInterface::HalInterface(
3878 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003879 std::shared_ptr<RequestMetadataQueue> queue,
3880 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003881 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003882 mRequestMetadataQueue(queue),
3883 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003884 // Check with hardware service manager if we can downcast these interfaces
3885 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003886 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3887 if (castResult_3_5.isOk()) {
3888 mHidlSession_3_5 = castResult_3_5;
3889 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003890 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3891 if (castResult_3_4.isOk()) {
3892 mHidlSession_3_4 = castResult_3_4;
3893 }
3894 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3895 if (castResult_3_3.isOk()) {
3896 mHidlSession_3_3 = castResult_3_3;
3897 }
3898}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003899
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003900Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003901
3902Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003903 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003904 mRequestMetadataQueue(other.mRequestMetadataQueue),
3905 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003906
3907bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003908 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003909}
3910
3911void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00003912 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003913 mHidlSession_3_4.clear();
3914 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003915 mHidlSession.clear();
3916}
3917
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003918bool Camera3Device::HalInterface::supportBatchRequest() {
3919 return mHidlSession != nullptr;
3920}
3921
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003922status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3923 camera3_request_template_t templateId,
3924 /*out*/ camera_metadata_t **requestTemplate) {
3925 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3926 if (!valid()) return INVALID_OPERATION;
3927 status_t res = OK;
3928
Emilian Peev31abd0a2017-05-11 18:37:46 +01003929 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003930
3931 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003932 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003933 status = s;
3934 if (status == common::V1_0::Status::OK) {
3935 const camera_metadata *r =
3936 reinterpret_cast<const camera_metadata_t*>(request.data());
3937 size_t expectedSize = request.size();
3938 int ret = validate_camera_metadata_structure(r, &expectedSize);
3939 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3940 *requestTemplate = clone_camera_metadata(r);
3941 if (*requestTemplate == nullptr) {
3942 ALOGE("%s: Unable to clone camera metadata received from HAL",
3943 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003944 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003945 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003946 } else {
3947 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3948 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003949 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003950 }
3951 };
3952 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003953 RequestTemplate id;
3954 switch (templateId) {
3955 case CAMERA3_TEMPLATE_PREVIEW:
3956 id = RequestTemplate::PREVIEW;
3957 break;
3958 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3959 id = RequestTemplate::STILL_CAPTURE;
3960 break;
3961 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3962 id = RequestTemplate::VIDEO_RECORD;
3963 break;
3964 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3965 id = RequestTemplate::VIDEO_SNAPSHOT;
3966 break;
3967 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3968 id = RequestTemplate::ZERO_SHUTTER_LAG;
3969 break;
3970 case CAMERA3_TEMPLATE_MANUAL:
3971 id = RequestTemplate::MANUAL;
3972 break;
3973 default:
3974 // Unknown template ID, or this HAL is too old to support it
3975 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003976 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003977 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003978
Emilian Peev31abd0a2017-05-11 18:37:46 +01003979 if (!err.isOk()) {
3980 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3981 res = DEAD_OBJECT;
3982 } else {
3983 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003984 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003985
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003986 return res;
3987}
3988
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003989status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003990 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003991 ATRACE_NAME("CameraHal::configureStreams");
3992 if (!valid()) return INVALID_OPERATION;
3993 status_t res = OK;
3994
Emilian Peev31abd0a2017-05-11 18:37:46 +01003995 // Convert stream config to HIDL
3996 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003997 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3998 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3999 requestedConfiguration3_2.streams.resize(config->num_streams);
4000 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004001 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004002 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4003 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004004 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004005
Emilian Peev31abd0a2017-05-11 18:37:46 +01004006 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4007 cam3stream->setBufferFreedListener(this);
4008 int streamId = cam3stream->getId();
4009 StreamType streamType;
4010 switch (src->stream_type) {
4011 case CAMERA3_STREAM_OUTPUT:
4012 streamType = StreamType::OUTPUT;
4013 break;
4014 case CAMERA3_STREAM_INPUT:
4015 streamType = StreamType::INPUT;
4016 break;
4017 default:
4018 ALOGE("%s: Stream %d: Unsupported stream type %d",
4019 __FUNCTION__, streamId, config->streams[i]->stream_type);
4020 return BAD_VALUE;
4021 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004022 dst3_2.id = streamId;
4023 dst3_2.streamType = streamType;
4024 dst3_2.width = src->width;
4025 dst3_2.height = src->height;
4026 dst3_2.format = mapToPixelFormat(src->format);
4027 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
4028 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4029 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
4030 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004031 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004032 if (src->physical_camera_id != nullptr) {
4033 dst3_4.physicalCameraId = src->physical_camera_id;
4034 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004035
4036 activeStreams.insert(streamId);
4037 // Create Buffer ID map if necessary
4038 if (mBufferIdMaps.count(streamId) == 0) {
4039 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4040 }
4041 }
4042 // remove BufferIdMap for deleted streams
4043 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4044 int streamId = it->first;
4045 bool active = activeStreams.count(streamId) > 0;
4046 if (!active) {
4047 it = mBufferIdMaps.erase(it);
4048 } else {
4049 ++it;
4050 }
4051 }
4052
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004053 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004054 res = mapToStreamConfigurationMode(
4055 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004056 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004057 if (res != OK) {
4058 return res;
4059 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004060 requestedConfiguration3_2.operationMode = operationMode;
4061 requestedConfiguration3_4.operationMode = operationMode;
4062 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004063 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4064 get_camera_metadata_size(sessionParams));
4065
Emilian Peev31abd0a2017-05-11 18:37:46 +01004066 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004067 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004068 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004069 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004070
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004071 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004072 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4073 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004074 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004075 };
4076
4077 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4078 (hardware::Return<void>& err) -> status_t {
4079 if (!err.isOk()) {
4080 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4081 return DEAD_OBJECT;
4082 }
4083 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4084 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4085 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4086 }
4087 return OK;
4088 };
4089
4090 // See if we have v3.4 or v3.3 HAL
4091 if (mHidlSession_3_5 != nullptr) {
4092 ALOGV("%s: v3.5 device found", __FUNCTION__);
4093 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4094 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4095 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4096 auto err = mHidlSession_3_5->configureStreams_3_5(
4097 requestedConfiguration3_5, configStream34Cb);
4098 res = postprocConfigStream34(err);
4099 if (res != OK) {
4100 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004101 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004102 } else if (mHidlSession_3_4 != nullptr) {
4103 // We do; use v3.4 for the call
4104 ALOGV("%s: v3.4 device found", __FUNCTION__);
4105 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
4106 auto err = mHidlSession_3_4->configureStreams_3_4(
4107 requestedConfiguration3_4, configStream34Cb);
4108 res = postprocConfigStream34(err);
4109 if (res != OK) {
4110 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004111 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004112 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004113 // We do; use v3.3 for the call
4114 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004115 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004116 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004117 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004118 finalConfiguration = halConfiguration;
4119 status = s;
4120 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004121 if (!err.isOk()) {
4122 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4123 return DEAD_OBJECT;
4124 }
4125 } else {
4126 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4127 ALOGV("%s: v3.2 device found", __FUNCTION__);
4128 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004129 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004130 [&status, &finalConfiguration_3_2]
4131 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4132 finalConfiguration_3_2 = halConfiguration;
4133 status = s;
4134 });
4135 if (!err.isOk()) {
4136 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4137 return DEAD_OBJECT;
4138 }
4139 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4140 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4141 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4142 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004143 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004144 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004145 }
4146
4147 if (status != common::V1_0::Status::OK ) {
4148 return CameraProviderManager::mapToStatusT(status);
4149 }
4150
4151 // And convert output stream configuration from HIDL
4152
4153 for (size_t i = 0; i < config->num_streams; i++) {
4154 camera3_stream_t *dst = config->streams[i];
4155 int streamId = Camera3Stream::cast(dst)->getId();
4156
4157 // Start scan at i, with the assumption that the stream order matches
4158 size_t realIdx = i;
4159 bool found = false;
4160 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004161 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004162 found = true;
4163 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004164 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004165 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4166 }
4167 if (!found) {
4168 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4169 __FUNCTION__, streamId);
4170 return INVALID_OPERATION;
4171 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004172 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004173
Emilian Peev710c1422017-08-30 11:19:38 +01004174 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4175 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004176 dstStream->setDataSpaceOverride(false);
4177 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4178 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4179
Emilian Peev31abd0a2017-05-11 18:37:46 +01004180 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4181 if (dst->format != overrideFormat) {
4182 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4183 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004184 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004185 if (dst->data_space != overrideDataSpace) {
4186 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4187 streamId, dst->format);
4188 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004189 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004190 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004191 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4192
Emilian Peev31abd0a2017-05-11 18:37:46 +01004193 // Override allowed with IMPLEMENTATION_DEFINED
4194 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004195 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004196 }
4197
Emilian Peev31abd0a2017-05-11 18:37:46 +01004198 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004199 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004200 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004201 __FUNCTION__, streamId);
4202 return INVALID_OPERATION;
4203 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004204 dstStream->setUsage(
4205 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004206 } else {
4207 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004208 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004209 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4210 __FUNCTION__, streamId);
4211 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004212 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004213 dstStream->setUsage(
4214 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004215 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004216 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004217 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004218
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004219 return res;
4220}
4221
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004222status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004223 /*out*/device::V3_2::CaptureRequest* captureRequest,
4224 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004225 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004226 if (captureRequest == nullptr || handlesCreated == nullptr) {
4227 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4228 __FUNCTION__, captureRequest, handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004229 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004230 }
4231
4232 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004233
4234 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004235
4236 {
4237 std::lock_guard<std::mutex> lock(mInflightLock);
4238 if (request->input_buffer != nullptr) {
4239 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4240 buffer_handle_t buf = *(request->input_buffer->buffer);
4241 auto pair = getBufferId(buf, streamId);
4242 bool isNewBuffer = pair.first;
4243 uint64_t bufferId = pair.second;
4244 captureRequest->inputBuffer.streamId = streamId;
4245 captureRequest->inputBuffer.bufferId = bufferId;
4246 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4247 captureRequest->inputBuffer.status = BufferStatus::OK;
4248 native_handle_t *acquireFence = nullptr;
4249 if (request->input_buffer->acquire_fence != -1) {
4250 acquireFence = native_handle_create(1,0);
4251 acquireFence->data[0] = request->input_buffer->acquire_fence;
4252 handlesCreated->push_back(acquireFence);
4253 }
4254 captureRequest->inputBuffer.acquireFence = acquireFence;
4255 captureRequest->inputBuffer.releaseFence = nullptr;
4256
4257 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4258 request->input_buffer->buffer,
4259 request->input_buffer->acquire_fence);
4260 } else {
4261 captureRequest->inputBuffer.streamId = -1;
4262 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4263 }
4264
4265 captureRequest->outputBuffers.resize(request->num_output_buffers);
4266 for (size_t i = 0; i < request->num_output_buffers; i++) {
4267 const camera3_stream_buffer_t *src = request->output_buffers + i;
4268 StreamBuffer &dst = captureRequest->outputBuffers[i];
4269 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004270 if (src->buffer != nullptr) {
4271 buffer_handle_t buf = *(src->buffer);
4272 auto pair = getBufferId(buf, streamId);
4273 bool isNewBuffer = pair.first;
4274 dst.bufferId = pair.second;
4275 dst.buffer = isNewBuffer ? buf : nullptr;
4276 native_handle_t *acquireFence = nullptr;
4277 if (src->acquire_fence != -1) {
4278 acquireFence = native_handle_create(1,0);
4279 acquireFence->data[0] = src->acquire_fence;
4280 handlesCreated->push_back(acquireFence);
4281 }
4282 dst.acquireFence = acquireFence;
4283 } else if (mUseHalBufManager) {
4284 // HAL buffer management path
4285 dst.bufferId = BUFFER_ID_NO_BUFFER;
4286 dst.buffer = nullptr;
4287 dst.acquireFence = nullptr;
4288 } else {
4289 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4290 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004291 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004292 dst.streamId = streamId;
4293 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004294 dst.releaseFence = nullptr;
4295
4296 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4297 src->buffer, src->acquire_fence);
4298 }
4299 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004300 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004301}
4302
4303status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4304 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4305 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4306 if (!valid()) return INVALID_OPERATION;
4307
Emilian Peevaebbe412018-01-15 13:53:24 +00004308 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4309 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4310 if (castResult_3_4.isOk()) {
4311 hidlSession_3_4 = castResult_3_4;
4312 }
4313
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004314 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004315 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004316 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004317 if (hidlSession_3_4 != nullptr) {
4318 captureRequests_3_4.resize(batchSize);
4319 } else {
4320 captureRequests.resize(batchSize);
4321 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004322 std::vector<native_handle_t*> handlesCreated;
4323
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004324 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004325 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004326 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004327 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Emilian Peevaebbe412018-01-15 13:53:24 +00004328 /*out*/&handlesCreated);
4329 } else {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004330 res = wrapAsHidlRequest(requests[i],
4331 /*out*/&captureRequests[i], /*out*/&handlesCreated);
4332 }
4333 if (res != OK) {
4334 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004335 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004336 }
4337
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004338 std::vector<device::V3_2::BufferCache> cachesToRemove;
4339 {
4340 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4341 for (auto& pair : mFreedBuffers) {
4342 // The stream might have been removed since onBufferFreed
4343 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4344 cachesToRemove.push_back({pair.first, pair.second});
4345 }
4346 }
4347 mFreedBuffers.clear();
4348 }
4349
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004350 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4351 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004352
4353 // Write metadata to FMQ.
4354 for (size_t i = 0; i < batchSize; i++) {
4355 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004356 device::V3_2::CaptureRequest* captureRequest;
4357 if (hidlSession_3_4 != nullptr) {
4358 captureRequest = &captureRequests_3_4[i].v3_2;
4359 } else {
4360 captureRequest = &captureRequests[i];
4361 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004362
4363 if (request->settings != nullptr) {
4364 size_t settingsSize = get_camera_metadata_size(request->settings);
4365 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4366 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4367 captureRequest->settings.resize(0);
4368 captureRequest->fmqSettingsSize = settingsSize;
4369 } else {
4370 if (mRequestMetadataQueue != nullptr) {
4371 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4372 }
4373 captureRequest->settings.setToExternal(
4374 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4375 get_camera_metadata_size(request->settings));
4376 captureRequest->fmqSettingsSize = 0u;
4377 }
4378 } else {
4379 // A null request settings maps to a size-0 CameraMetadata
4380 captureRequest->settings.resize(0);
4381 captureRequest->fmqSettingsSize = 0u;
4382 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004383
4384 if (hidlSession_3_4 != nullptr) {
4385 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4386 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004387 if (request->physcam_settings != nullptr) {
4388 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4389 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4390 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4391 settingsSize)) {
4392 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4393 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4394 settingsSize;
4395 } else {
4396 if (mRequestMetadataQueue != nullptr) {
4397 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4398 }
4399 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4400 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4401 request->physcam_settings[j])),
4402 get_camera_metadata_size(request->physcam_settings[j]));
4403 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004404 }
Emilian Peev00420d22018-02-05 21:33:13 +00004405 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004406 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004407 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004408 }
4409 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4410 request->physcam_id[j];
4411 }
4412 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004413 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004414
4415 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004416 auto resultCallback =
4417 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4418 status = s;
4419 *numRequestProcessed = n;
4420 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004421 if (hidlSession_3_4 != nullptr) {
4422 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004423 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004424 } else {
4425 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004426 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004427 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004428 if (!err.isOk()) {
4429 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4430 return DEAD_OBJECT;
4431 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004432 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4433 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4434 __FUNCTION__, *numRequestProcessed, batchSize);
4435 status = common::V1_0::Status::INTERNAL_ERROR;
4436 }
4437
4438 for (auto& handle : handlesCreated) {
4439 native_handle_delete(handle);
4440 }
4441 return CameraProviderManager::mapToStatusT(status);
4442}
4443
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004444status_t Camera3Device::HalInterface::processCaptureRequest(
4445 camera3_capture_request_t *request) {
4446 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004447 if (!valid()) return INVALID_OPERATION;
4448 status_t res = OK;
4449
Emilian Peev31abd0a2017-05-11 18:37:46 +01004450 uint32_t numRequestProcessed = 0;
4451 std::vector<camera3_capture_request_t*> requests(1);
4452 requests[0] = request;
4453 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4454
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004455 return res;
4456}
4457
4458status_t Camera3Device::HalInterface::flush() {
4459 ATRACE_NAME("CameraHal::flush");
4460 if (!valid()) return INVALID_OPERATION;
4461 status_t res = OK;
4462
Emilian Peev31abd0a2017-05-11 18:37:46 +01004463 auto err = mHidlSession->flush();
4464 if (!err.isOk()) {
4465 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4466 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004467 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004468 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004469 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004470
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004471 return res;
4472}
4473
Emilian Peev31abd0a2017-05-11 18:37:46 +01004474status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004475 ATRACE_NAME("CameraHal::dump");
4476 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004477
Emilian Peev31abd0a2017-05-11 18:37:46 +01004478 // Handled by CameraProviderManager::dump
4479
4480 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004481}
4482
4483status_t Camera3Device::HalInterface::close() {
4484 ATRACE_NAME("CameraHal::close()");
4485 if (!valid()) return INVALID_OPERATION;
4486 status_t res = OK;
4487
Emilian Peev31abd0a2017-05-11 18:37:46 +01004488 auto err = mHidlSession->close();
4489 // Interface will be dead shortly anyway, so don't log errors
4490 if (!err.isOk()) {
4491 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004492 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004493
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004494 return res;
4495}
4496
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004497void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4498 ATRACE_NAME("CameraHal::signalPipelineDrain");
4499 if (!valid() || mHidlSession_3_5 == nullptr) {
4500 ALOGE("%s called on invalid camera!", __FUNCTION__);
4501 return;
4502 }
4503
4504 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter);
4505 if (!err.isOk()) {
4506 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4507 return;
4508 }
4509}
4510
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004511void Camera3Device::HalInterface::getInflightBufferKeys(
4512 std::vector<std::pair<int32_t, int32_t>>* out) {
4513 std::lock_guard<std::mutex> lock(mInflightLock);
4514 out->clear();
4515 out->reserve(mInflightBufferMap.size());
4516 for (auto& pair : mInflightBufferMap) {
4517 uint64_t key = pair.first;
4518 int32_t streamId = key & 0xFFFFFFFF;
4519 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4520 out->push_back(std::make_pair(frameNumber, streamId));
4521 }
4522 return;
4523}
4524
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004525status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004526 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004527 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004528 auto pair = std::make_pair(buffer, acquireFence);
4529 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004530 return OK;
4531}
4532
4533status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004534 int32_t frameNumber, int32_t streamId,
4535 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004536 std::lock_guard<std::mutex> lock(mInflightLock);
4537
4538 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4539 auto it = mInflightBufferMap.find(key);
4540 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004541 auto pair = it->second;
4542 *buffer = pair.first;
4543 int acquireFence = pair.second;
4544 if (acquireFence > 0) {
4545 ::close(acquireFence);
4546 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004547 mInflightBufferMap.erase(it);
4548 return OK;
4549}
4550
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004551status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4552 uint64_t bufferId, buffer_handle_t* buf) {
4553 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4554 auto pair = mRequestedBuffers.insert({bufferId, buf});
4555 if (!pair.second) {
4556 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4557 __FUNCTION__, bufferId);
4558 return BAD_VALUE;
4559 }
4560 return OK;
4561}
4562
4563// Find and pop a buffer_handle_t based on bufferId
4564status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4565 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4566 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4567 auto it = mRequestedBuffers.find(bufferId);
4568 if (it == mRequestedBuffers.end()) {
4569 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4570 __FUNCTION__, bufferId);
4571 return BAD_VALUE;
4572 }
4573 *buffer = it->second;
4574 mRequestedBuffers.erase(it);
4575 return OK;
4576}
4577
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004578std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4579 const buffer_handle_t& buf, int streamId) {
4580 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4581
4582 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4583 auto it = bIdMap.find(buf);
4584 if (it == bIdMap.end()) {
4585 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004586 ALOGV("stream %d now have %zu buffer caches, buf %p",
4587 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004588 return std::make_pair(true, mNextBufferId - 1);
4589 } else {
4590 return std::make_pair(false, it->second);
4591 }
4592}
4593
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004594void Camera3Device::HalInterface::onBufferFreed(
4595 int streamId, const native_handle_t* handle) {
4596 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4597 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4598 auto mapIt = mBufferIdMaps.find(streamId);
4599 if (mapIt == mBufferIdMaps.end()) {
4600 // streamId might be from a deleted stream here
4601 ALOGI("%s: stream %d has been removed",
4602 __FUNCTION__, streamId);
4603 return;
4604 }
4605 BufferIdMap& bIdMap = mapIt->second;
4606 auto it = bIdMap.find(handle);
4607 if (it == bIdMap.end()) {
4608 ALOGW("%s: cannot find buffer %p in stream %d",
4609 __FUNCTION__, handle, streamId);
4610 return;
4611 } else {
4612 bufferId = it->second;
4613 bIdMap.erase(it);
4614 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4615 __FUNCTION__, streamId, bIdMap.size(), handle);
4616 }
4617 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4618}
4619
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004620/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004621 * RequestThread inner class methods
4622 */
4623
4624Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004625 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004626 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4627 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004628 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004629 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004630 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004631 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004632 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004633 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004634 mReconfigured(false),
4635 mDoPause(false),
4636 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004637 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004638 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004639 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004640 mCurrentAfTriggerId(0),
4641 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004642 mRepeatingLastFrameNumber(
4643 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004644 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004645 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004646 mRequestLatency(kRequestLatencyBinSize),
4647 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004648 mLatestSessionParams(sessionParamKeys.size()),
4649 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004650 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004651}
4652
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004653Camera3Device::RequestThread::~RequestThread() {}
4654
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004655void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004656 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004657 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004658 Mutex::Autolock l(mRequestLock);
4659 mListener = listener;
4660}
4661
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004662void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4663 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004664 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004665 Mutex::Autolock l(mRequestLock);
4666 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004667 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004668 // Prepare video stream for high speed recording.
4669 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004670 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004671}
4672
Jianing Wei90e59c92014-03-12 18:29:36 -07004673status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004674 List<sp<CaptureRequest> > &requests,
4675 /*out*/
4676 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004677 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004678 Mutex::Autolock l(mRequestLock);
4679 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4680 ++it) {
4681 mRequestQueue.push_back(*it);
4682 }
4683
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004684 if (lastFrameNumber != NULL) {
4685 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4686 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4687 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4688 *lastFrameNumber);
4689 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004690
Jianing Wei90e59c92014-03-12 18:29:36 -07004691 unpauseForNewRequests();
4692
4693 return OK;
4694}
4695
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004696
4697status_t Camera3Device::RequestThread::queueTrigger(
4698 RequestTrigger trigger[],
4699 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004700 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004701 Mutex::Autolock l(mTriggerMutex);
4702 status_t ret;
4703
4704 for (size_t i = 0; i < count; ++i) {
4705 ret = queueTriggerLocked(trigger[i]);
4706
4707 if (ret != OK) {
4708 return ret;
4709 }
4710 }
4711
4712 return OK;
4713}
4714
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004715const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4716 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004717 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004718 if (d != nullptr) return d->mId;
4719 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004720}
4721
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004722status_t Camera3Device::RequestThread::queueTriggerLocked(
4723 RequestTrigger trigger) {
4724
4725 uint32_t tag = trigger.metadataTag;
4726 ssize_t index = mTriggerMap.indexOfKey(tag);
4727
4728 switch (trigger.getTagType()) {
4729 case TYPE_BYTE:
4730 // fall-through
4731 case TYPE_INT32:
4732 break;
4733 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004734 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4735 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004736 return INVALID_OPERATION;
4737 }
4738
4739 /**
4740 * Collect only the latest trigger, since we only have 1 field
4741 * in the request settings per trigger tag, and can't send more than 1
4742 * trigger per request.
4743 */
4744 if (index != NAME_NOT_FOUND) {
4745 mTriggerMap.editValueAt(index) = trigger;
4746 } else {
4747 mTriggerMap.add(tag, trigger);
4748 }
4749
4750 return OK;
4751}
4752
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004753status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004754 const RequestList &requests,
4755 /*out*/
4756 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004757 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004758 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004759 if (lastFrameNumber != NULL) {
4760 *lastFrameNumber = mRepeatingLastFrameNumber;
4761 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004762 mRepeatingRequests.clear();
4763 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4764 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004765
4766 unpauseForNewRequests();
4767
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004768 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004769 return OK;
4770}
4771
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004772bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004773 if (mRepeatingRequests.empty()) {
4774 return false;
4775 }
4776 int32_t requestId = requestIn->mResultExtras.requestId;
4777 const RequestList &repeatRequests = mRepeatingRequests;
4778 // All repeating requests are guaranteed to have same id so only check first quest
4779 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4780 return (firstRequest->mResultExtras.requestId == requestId);
4781}
4782
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004783status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004784 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004785 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004786 return clearRepeatingRequestsLocked(lastFrameNumber);
4787
4788}
4789
4790status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004791 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004792 if (lastFrameNumber != NULL) {
4793 *lastFrameNumber = mRepeatingLastFrameNumber;
4794 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004795 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004796 return OK;
4797}
4798
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004799status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004800 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004801 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004802 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004803 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004804
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004805 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004806
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004807 // Send errors for all requests pending in the request queue, including
4808 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004809 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004810 if (listener != NULL) {
4811 for (RequestList::iterator it = mRequestQueue.begin();
4812 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004813 // Abort the input buffers for reprocess requests.
4814 if ((*it)->mInputStream != NULL) {
4815 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004816 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4817 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004818 if (res != OK) {
4819 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4820 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4821 } else {
4822 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4823 if (res != OK) {
4824 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4825 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4826 }
4827 }
4828 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004829 // Set the frame number this request would have had, if it
4830 // had been submitted; this frame number will not be reused.
4831 // The requestId and burstId fields were set when the request was
4832 // submitted originally (in convertMetadataListToRequestListLocked)
4833 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004834 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004835 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004836 }
4837 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004838 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004839
4840 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004841 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004842 if (lastFrameNumber != NULL) {
4843 *lastFrameNumber = mRepeatingLastFrameNumber;
4844 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004845 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004846 return OK;
4847}
4848
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004849status_t Camera3Device::RequestThread::flush() {
4850 ATRACE_CALL();
4851 Mutex::Autolock l(mFlushLock);
4852
Emilian Peev08dd2452017-04-06 16:55:14 +01004853 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004854}
4855
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004856void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004857 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004858 Mutex::Autolock l(mPauseLock);
4859 mDoPause = paused;
4860 mDoPauseSignal.signal();
4861}
4862
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004863status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4864 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004865 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004866 Mutex::Autolock l(mLatestRequestMutex);
4867 status_t res;
4868 while (mLatestRequestId != requestId) {
4869 nsecs_t startTime = systemTime();
4870
4871 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4872 if (res != OK) return res;
4873
4874 timeout -= (systemTime() - startTime);
4875 }
4876
4877 return OK;
4878}
4879
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004880void Camera3Device::RequestThread::requestExit() {
4881 // Call parent to set up shutdown
4882 Thread::requestExit();
4883 // The exit from any possible waits
4884 mDoPauseSignal.signal();
4885 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004886
4887 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4888 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004889}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004890
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004891void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004892 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004893 bool surfaceAbandoned = false;
4894 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004895 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004896 {
4897 Mutex::Autolock l(mRequestLock);
4898 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4899 // repeating requests.
4900 for (const auto& request : mRepeatingRequests) {
4901 for (const auto& s : request->mOutputStreams) {
4902 if (s->isAbandoned()) {
4903 surfaceAbandoned = true;
4904 clearRepeatingRequestsLocked(&lastFrameNumber);
4905 break;
4906 }
4907 }
4908 if (surfaceAbandoned) {
4909 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004910 }
4911 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004912 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004913 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004914
4915 if (listener != NULL && surfaceAbandoned) {
4916 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004917 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004918}
4919
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004920bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004921 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004922 status_t res;
4923 size_t batchSize = mNextRequests.size();
4924 std::vector<camera3_capture_request_t*> requests(batchSize);
4925 uint32_t numRequestProcessed = 0;
4926 for (size_t i = 0; i < batchSize; i++) {
4927 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004928 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004929 }
4930
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004931 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4932
4933 bool triggerRemoveFailed = false;
4934 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4935 for (size_t i = 0; i < numRequestProcessed; i++) {
4936 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4937 nextRequest.submitted = true;
4938
4939
4940 // Update the latest request sent to HAL
4941 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4942 Mutex::Autolock al(mLatestRequestMutex);
4943
4944 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4945 mLatestRequest.acquire(cloned);
4946
4947 sp<Camera3Device> parent = mParent.promote();
4948 if (parent != NULL) {
4949 parent->monitorMetadata(TagMonitor::REQUEST,
4950 nextRequest.halRequest.frame_number,
4951 0, mLatestRequest);
4952 }
4953 }
4954
4955 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004956 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4957 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004958 }
4959
Emilian Peevaebbe412018-01-15 13:53:24 +00004960 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4961
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004962 if (!triggerRemoveFailed) {
4963 // Remove any previously queued triggers (after unlock)
4964 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4965 if (removeTriggerRes != OK) {
4966 triggerRemoveFailed = true;
4967 triggerFailedRequest = nextRequest;
4968 }
4969 }
4970 }
4971
4972 if (triggerRemoveFailed) {
4973 SET_ERR("RequestThread: Unable to remove triggers "
4974 "(capture request %d, HAL device: %s (%d)",
4975 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4976 cleanUpFailedRequests(/*sendRequestError*/ false);
4977 return false;
4978 }
4979
4980 if (res != OK) {
4981 // Should only get a failure here for malformed requests or device-level
4982 // errors, so consider all errors fatal. Bad metadata failures should
4983 // come through notify.
4984 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4985 mNextRequests[numRequestProcessed].halRequest.frame_number,
4986 strerror(-res), res);
4987 cleanUpFailedRequests(/*sendRequestError*/ false);
4988 return false;
4989 }
4990 return true;
4991}
4992
4993bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4994 status_t res;
4995
4996 for (auto& nextRequest : mNextRequests) {
4997 // Submit request and block until ready for next one
4998 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4999 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
5000
5001 if (res != OK) {
5002 // Should only get a failure here for malformed requests or device-level
5003 // errors, so consider all errors fatal. Bad metadata failures should
5004 // come through notify.
5005 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
5006 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
5007 res);
5008 cleanUpFailedRequests(/*sendRequestError*/ false);
5009 return false;
5010 }
5011
5012 // Mark that the request has be submitted successfully.
5013 nextRequest.submitted = true;
5014
5015 // Update the latest request sent to HAL
5016 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5017 Mutex::Autolock al(mLatestRequestMutex);
5018
5019 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5020 mLatestRequest.acquire(cloned);
5021
5022 sp<Camera3Device> parent = mParent.promote();
5023 if (parent != NULL) {
5024 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
5025 0, mLatestRequest);
5026 }
5027 }
5028
5029 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005030 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5031 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005032 }
5033
Emilian Peevaebbe412018-01-15 13:53:24 +00005034 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5035
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005036 // Remove any previously queued triggers (after unlock)
5037 res = removeTriggers(mPrevRequest);
5038 if (res != OK) {
5039 SET_ERR("RequestThread: Unable to remove triggers "
5040 "(capture request %d, HAL device: %s (%d)",
5041 nextRequest.halRequest.frame_number, strerror(-res), res);
5042 cleanUpFailedRequests(/*sendRequestError*/ false);
5043 return false;
5044 }
5045 }
5046 return true;
5047}
5048
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005049nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5050 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5051 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5052 find_camera_metadata_ro_entry(request,
5053 ANDROID_CONTROL_AE_MODE,
5054 &e);
5055 if (e.count == 0) return maxExpectedDuration;
5056
5057 switch (e.data.u8[0]) {
5058 case ANDROID_CONTROL_AE_MODE_OFF:
5059 find_camera_metadata_ro_entry(request,
5060 ANDROID_SENSOR_EXPOSURE_TIME,
5061 &e);
5062 if (e.count > 0) {
5063 maxExpectedDuration = e.data.i64[0];
5064 }
5065 find_camera_metadata_ro_entry(request,
5066 ANDROID_SENSOR_FRAME_DURATION,
5067 &e);
5068 if (e.count > 0) {
5069 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5070 }
5071 break;
5072 default:
5073 find_camera_metadata_ro_entry(request,
5074 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5075 &e);
5076 if (e.count > 1) {
5077 maxExpectedDuration = 1e9 / e.data.u8[0];
5078 }
5079 break;
5080 }
5081
5082 return maxExpectedDuration;
5083}
5084
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005085bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5086 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5087 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5088 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5089 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5090 return true;
5091 }
5092
5093 return false;
5094}
5095
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005096bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5097 ATRACE_CALL();
5098 bool updatesDetected = false;
5099
5100 for (auto tag : mSessionParamKeys) {
5101 camera_metadata_ro_entry entry = settings.find(tag);
5102 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
5103
5104 if (entry.count > 0) {
5105 bool isDifferent = false;
5106 if (lastEntry.count > 0) {
5107 // Have a last value, compare to see if changed
5108 if (lastEntry.type == entry.type &&
5109 lastEntry.count == entry.count) {
5110 // Same type and count, compare values
5111 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5112 size_t entryBytes = bytesPerValue * lastEntry.count;
5113 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5114 if (cmp != 0) {
5115 isDifferent = true;
5116 }
5117 } else {
5118 // Count or type has changed
5119 isDifferent = true;
5120 }
5121 } else {
5122 // No last entry, so always consider to be different
5123 isDifferent = true;
5124 }
5125
5126 if (isDifferent) {
5127 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005128 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5129 updatesDetected = true;
5130 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005131 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005132 }
5133 } else if (lastEntry.count > 0) {
5134 // Value has been removed
5135 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
5136 mLatestSessionParams.erase(tag);
5137 updatesDetected = true;
5138 }
5139 }
5140
5141 return updatesDetected;
5142}
5143
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005144bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005145 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005146 status_t res;
5147
5148 // Handle paused state.
5149 if (waitIfPaused()) {
5150 return true;
5151 }
5152
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005153 // Wait for the next batch of requests.
5154 waitForNextRequestBatch();
5155 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005156 return true;
5157 }
5158
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005159 // Get the latest request ID, if any
5160 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005161 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005162 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005163 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005164 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005165 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005166 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5167 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005168 }
5169
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005170 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5171 // or a single request from streaming or burst. In either case the first element
5172 // should contain the latest camera settings that we need to check for any session
5173 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005174 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005175 res = OK;
5176
5177 //Input stream buffers are already acquired at this point so an input stream
5178 //will not be able to move to idle state unless we force it.
5179 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5180 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5181 if (res != OK) {
5182 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5183 cleanUpFailedRequests(/*sendRequestError*/ false);
5184 return false;
5185 }
5186 }
5187
5188 if (res == OK) {
5189 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5190 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005191 sp<Camera3Device> parent = mParent.promote();
5192 if (parent != nullptr) {
5193 parent->pauseStateNotify(true);
5194 }
5195
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005196 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5197
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005198 if (parent != nullptr) {
5199 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5200 }
5201
5202 statusTracker->markComponentActive(mStatusId);
5203 setPaused(false);
5204 }
5205
5206 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5207 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5208 if (res != OK) {
5209 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5210 cleanUpFailedRequests(/*sendRequestError*/ false);
5211 return false;
5212 }
5213 }
5214 }
5215 }
5216
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005217 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005218 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005219 if (res == TIMED_OUT) {
5220 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005221 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005222 // Check if any stream is abandoned.
5223 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005224 return true;
5225 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005226 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005227 return false;
5228 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005229
Zhijun Hecc27e112013-10-03 16:12:43 -07005230 // Inform waitUntilRequestProcessed thread of a new request ID
5231 {
5232 Mutex::Autolock al(mLatestRequestMutex);
5233
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005234 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005235 mLatestRequestSignal.signal();
5236 }
5237
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005238 // Submit a batch of requests to HAL.
5239 // Use flush lock only when submitting multilple requests in a batch.
5240 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5241 // which may take a long time to finish so synchronizing flush() and
5242 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5243 // For now, only synchronize for high speed recording and we should figure something out for
5244 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005245 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005246
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005247 if (useFlushLock) {
5248 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005249 }
5250
Zhijun Hef0645c12016-08-02 00:58:11 -07005251 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005252 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005253
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005254 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005255 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005256 if (mInterface->supportBatchRequest()) {
5257 submitRequestSuccess = sendRequestsBatch();
5258 } else {
5259 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005260 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005261 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5262 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005263
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005264 if (submitRequestSuccess) {
5265 sp<Camera3Device> parent = mParent.promote();
5266 if (parent != nullptr) {
5267 parent->mRequestBufferSM.onRequestSubmitted();
5268 }
5269 }
5270
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005271 if (useFlushLock) {
5272 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005273 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005274
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005275 // Unset as current request
5276 {
5277 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005278 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005279 }
5280
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005281 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005282}
5283
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005284status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005285 ATRACE_CALL();
5286
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005287 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005288 for (size_t i = 0; i < mNextRequests.size(); i++) {
5289 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005290 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5291 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5292 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5293
5294 // Prepare a request to HAL
5295 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5296
5297 // Insert any queued triggers (before metadata is locked)
5298 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005299 if (res < 0) {
5300 SET_ERR("RequestThread: Unable to insert triggers "
5301 "(capture request %d, HAL device: %s (%d)",
5302 halRequest->frame_number, strerror(-res), res);
5303 return INVALID_OPERATION;
5304 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005305
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005306 int triggerCount = res;
5307 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5308 mPrevTriggers = triggerCount;
5309
5310 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005311 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5312 // Request settings are all the same within one batch, so only treat the first
5313 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005314 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005315 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005316 /**
5317 * HAL workaround:
5318 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5319 */
5320 res = addDummyTriggerIds(captureRequest);
5321 if (res != OK) {
5322 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5323 "(capture request %d, HAL device: %s (%d)",
5324 halRequest->frame_number, strerror(-res), res);
5325 return INVALID_OPERATION;
5326 }
5327
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005328 {
5329 // Correct metadata regions for distortion correction if enabled
5330 sp<Camera3Device> parent = mParent.promote();
5331 if (parent != nullptr) {
5332 res = parent->mDistortionMapper.correctCaptureRequest(
5333 &(captureRequest->mSettingsList.begin()->metadata));
5334 if (res != OK) {
5335 SET_ERR("RequestThread: Unable to correct capture requests "
5336 "for lens distortion for request %d: %s (%d)",
5337 halRequest->frame_number, strerror(-res), res);
5338 return INVALID_OPERATION;
5339 }
5340 }
5341 }
5342
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005343 /**
5344 * The request should be presorted so accesses in HAL
5345 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5346 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005347 captureRequest->mSettingsList.begin()->metadata.sort();
5348 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005349 mPrevRequest = captureRequest;
5350 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5351
5352 IF_ALOGV() {
5353 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5354 find_camera_metadata_ro_entry(
5355 halRequest->settings,
5356 ANDROID_CONTROL_AF_TRIGGER,
5357 &e
5358 );
5359 if (e.count > 0) {
5360 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5361 __FUNCTION__,
5362 halRequest->frame_number,
5363 e.data.u8[0]);
5364 }
5365 }
5366 } else {
5367 // leave request.settings NULL to indicate 'reuse latest given'
5368 ALOGVV("%s: Request settings are REUSED",
5369 __FUNCTION__);
5370 }
5371
Emilian Peevaebbe412018-01-15 13:53:24 +00005372 if (captureRequest->mSettingsList.size() > 1) {
5373 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5374 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005375 if (newRequest) {
5376 halRequest->physcam_settings =
5377 new const camera_metadata* [halRequest->num_physcam_settings];
5378 } else {
5379 halRequest->physcam_settings = nullptr;
5380 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005381 auto it = ++captureRequest->mSettingsList.begin();
5382 size_t i = 0;
5383 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5384 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005385 if (newRequest) {
5386 it->metadata.sort();
5387 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5388 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005389 }
5390 }
5391
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005392 uint32_t totalNumBuffers = 0;
5393
5394 // Fill in buffers
5395 if (captureRequest->mInputStream != NULL) {
5396 halRequest->input_buffer = &captureRequest->mInputBuffer;
5397 totalNumBuffers += 1;
5398 } else {
5399 halRequest->input_buffer = NULL;
5400 }
5401
5402 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5403 captureRequest->mOutputStreams.size());
5404 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005405 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005406
5407 sp<Camera3Device> parent = mParent.promote();
5408 if (parent == NULL) {
5409 // Should not happen, and nowhere to send errors to, so just log it
5410 CLOGE("RequestThread: Parent is gone");
5411 return INVALID_OPERATION;
5412 }
5413 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5414
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005415 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005416 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005417 sp<Camera3OutputStreamInterface> outputStream =
5418 captureRequest->mOutputStreams.editItemAt(j);
5419 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005420
5421 // Prepare video buffers for high speed recording on the first video request.
5422 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5423 // Only try to prepare video stream on the first video request.
5424 mPrepareVideoStream = false;
5425
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005426 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5427 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005428 while (res == NOT_ENOUGH_DATA) {
5429 res = outputStream->prepareNextBuffer();
5430 }
5431 if (res != OK) {
5432 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5433 __FUNCTION__, strerror(-res), res);
5434 outputStream->cancelPrepare();
5435 }
5436 }
5437
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005438 std::vector<size_t> uniqueSurfaceIds;
5439 res = outputStream->getUniqueSurfaceIds(
5440 captureRequest->mOutputSurfaces[streamId],
5441 &uniqueSurfaceIds);
5442 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5443 if (res != OK && res != INVALID_OPERATION) {
5444 ALOGE("%s: failed to query stream %d unique surface IDs",
5445 __FUNCTION__, streamId);
5446 return res;
5447 }
5448 if (res == OK) {
5449 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5450 }
5451
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005452 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005453 if (outputStream->isAbandoned()) {
5454 ALOGE("%s: stream %d is abandoned.", __FUNCTION__, streamId);
5455 return TIMED_OUT;
5456 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005457 // HAL will request buffer through requestStreamBuffer API
5458 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5459 buffer.stream = outputStream->asHalStream();
5460 buffer.buffer = nullptr;
5461 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5462 buffer.acquire_fence = -1;
5463 buffer.release_fence = -1;
5464 } else {
5465 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5466 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005467 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005468 if (res != OK) {
5469 // Can't get output buffer from gralloc queue - this could be due to
5470 // abandoned queue or other consumer misbehavior, so not a fatal
5471 // error
5472 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5473 " %s (%d)", strerror(-res), res);
5474
5475 return TIMED_OUT;
5476 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005477 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005478
5479 {
5480 sp<Camera3Device> parent = mParent.promote();
5481 if (parent != nullptr) {
5482 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5483 for (const auto& settings : captureRequest->mSettingsList) {
5484 if ((streamCameraId.isEmpty() &&
5485 parent->getId() == settings.cameraId.c_str()) ||
5486 streamCameraId == settings.cameraId.c_str()) {
5487 outputStream->fireBufferRequestForFrameNumber(
5488 captureRequest->mResultExtras.frameNumber,
5489 settings.metadata);
5490 }
5491 }
5492 }
5493 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005494
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005495 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5496
5497 if (!physicalCameraId.isEmpty()) {
5498 // Physical stream isn't supported for input request.
5499 if (halRequest->input_buffer) {
5500 CLOGE("Physical stream is not supported for input request");
5501 return INVALID_OPERATION;
5502 }
5503 requestedPhysicalCameras.insert(physicalCameraId);
5504 }
5505 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005506 }
5507 totalNumBuffers += halRequest->num_output_buffers;
5508
5509 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005510 // If this request list is for constrained high speed recording (not
5511 // preview), and the current request is not the last one in the batch,
5512 // do not send callback to the app.
5513 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005514 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005515 hasCallback = false;
5516 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005517 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005518 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005519 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5520 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5521 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5522 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5523 isStillCapture = true;
5524 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5525 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005526
5527 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5528 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5529 isZslCapture = true;
5530 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005531 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005532 res = parent->registerInFlight(halRequest->frame_number,
5533 totalNumBuffers, captureRequest->mResultExtras,
5534 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005535 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005536 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005537 requestedPhysicalCameras, isStillCapture, isZslCapture,
5538 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5539 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005540 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5541 ", burstId = %" PRId32 ".",
5542 __FUNCTION__,
5543 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5544 captureRequest->mResultExtras.burstId);
5545 if (res != OK) {
5546 SET_ERR("RequestThread: Unable to register new in-flight request:"
5547 " %s (%d)", strerror(-res), res);
5548 return INVALID_OPERATION;
5549 }
5550 }
5551
5552 return OK;
5553}
5554
Igor Murashkin1e479c02013-09-06 16:55:14 -07005555CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005556 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005557 Mutex::Autolock al(mLatestRequestMutex);
5558
5559 ALOGV("RequestThread::%s", __FUNCTION__);
5560
5561 return mLatestRequest;
5562}
5563
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005564bool Camera3Device::RequestThread::isStreamPending(
5565 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005566 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005567 Mutex::Autolock l(mRequestLock);
5568
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005569 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005570 if (!nextRequest.submitted) {
5571 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5572 if (stream == s) return true;
5573 }
5574 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005575 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005576 }
5577
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005578 for (const auto& request : mRequestQueue) {
5579 for (const auto& s : request->mOutputStreams) {
5580 if (stream == s) return true;
5581 }
5582 if (stream == request->mInputStream) return true;
5583 }
5584
5585 for (const auto& request : mRepeatingRequests) {
5586 for (const auto& s : request->mOutputStreams) {
5587 if (stream == s) return true;
5588 }
5589 if (stream == request->mInputStream) return true;
5590 }
5591
5592 return false;
5593}
Jianing Weicb0652e2014-03-12 18:29:36 -07005594
Emilian Peev40ead602017-09-26 15:46:36 +01005595bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5596 ATRACE_CALL();
5597 Mutex::Autolock l(mRequestLock);
5598
5599 for (const auto& nextRequest : mNextRequests) {
5600 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5601 if (s.first == streamId) {
5602 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5603 if (it != s.second.end()) {
5604 return true;
5605 }
5606 }
5607 }
5608 }
5609
5610 for (const auto& request : mRequestQueue) {
5611 for (const auto& s : request->mOutputSurfaces) {
5612 if (s.first == streamId) {
5613 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5614 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005615 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005616 }
5617 }
5618 }
5619 }
5620
5621 for (const auto& request : mRepeatingRequests) {
5622 for (const auto& s : request->mOutputSurfaces) {
5623 if (s.first == streamId) {
5624 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5625 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005626 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005627 }
5628 }
5629 }
5630 }
5631
5632 return false;
5633}
5634
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005635void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5636 if (!mUseHalBufManager) {
5637 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5638 return;
5639 }
5640
5641 Mutex::Autolock pl(mPauseLock);
5642 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005643 mInterface->signalPipelineDrain(streamIds);
5644 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005645 }
5646 // If request thread is still busy, wait until paused then notify HAL
5647 mNotifyPipelineDrain = true;
5648 mStreamIdsToBeDrained = streamIds;
5649}
5650
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005651nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005652 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005653 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005654 return mExpectedInflightDuration > kMinInflightDuration ?
5655 mExpectedInflightDuration : kMinInflightDuration;
5656}
5657
Emilian Peevaebbe412018-01-15 13:53:24 +00005658void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5659 camera3_capture_request_t *halRequest) {
5660 if ((request == nullptr) || (halRequest == nullptr)) {
5661 ALOGE("%s: Invalid request!", __FUNCTION__);
5662 return;
5663 }
5664
5665 if (halRequest->num_physcam_settings > 0) {
5666 if (halRequest->physcam_id != nullptr) {
5667 delete [] halRequest->physcam_id;
5668 halRequest->physcam_id = nullptr;
5669 }
5670 if (halRequest->physcam_settings != nullptr) {
5671 auto it = ++(request->mSettingsList.begin());
5672 size_t i = 0;
5673 for (; it != request->mSettingsList.end(); it++, i++) {
5674 it->metadata.unlock(halRequest->physcam_settings[i]);
5675 }
5676 delete [] halRequest->physcam_settings;
5677 halRequest->physcam_settings = nullptr;
5678 }
5679 }
5680}
5681
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005682void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5683 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005684 return;
5685 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005686
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005687 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005688 // Skip the ones that have been submitted successfully.
5689 if (nextRequest.submitted) {
5690 continue;
5691 }
5692
5693 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5694 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5695 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5696
5697 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005698 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005699 }
5700
Emilian Peevaebbe412018-01-15 13:53:24 +00005701 cleanupPhysicalSettings(captureRequest, halRequest);
5702
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005703 if (captureRequest->mInputStream != NULL) {
5704 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5705 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5706 }
5707
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005708 // No output buffer can be returned when using HAL buffer manager
5709 if (!mUseHalBufManager) {
5710 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5711 //Buffers that failed processing could still have
5712 //valid acquire fence.
5713 int acquireFence = (*outputBuffers)[i].acquire_fence;
5714 if (0 <= acquireFence) {
5715 close(acquireFence);
5716 outputBuffers->editItemAt(i).acquire_fence = -1;
5717 }
5718 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5719 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5720 /*timestampIncreasing*/true, std::vector<size_t> (),
5721 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005722 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005723 }
5724
5725 if (sendRequestError) {
5726 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005727 sp<NotificationListener> listener = mListener.promote();
5728 if (listener != NULL) {
5729 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005730 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005731 captureRequest->mResultExtras);
5732 }
5733 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005734
5735 // Remove yet-to-be submitted inflight request from inflightMap
5736 {
5737 sp<Camera3Device> parent = mParent.promote();
5738 if (parent != NULL) {
5739 Mutex::Autolock l(parent->mInFlightLock);
5740 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5741 if (idx >= 0) {
5742 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5743 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5744 parent->removeInFlightMapEntryLocked(idx);
5745 }
5746 }
5747 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005748 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005749
5750 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005751 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005752}
5753
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005754void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005755 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005756 // Optimized a bit for the simple steady-state case (single repeating
5757 // request), to avoid putting that request in the queue temporarily.
5758 Mutex::Autolock l(mRequestLock);
5759
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005760 assert(mNextRequests.empty());
5761
5762 NextRequest nextRequest;
5763 nextRequest.captureRequest = waitForNextRequestLocked();
5764 if (nextRequest.captureRequest == nullptr) {
5765 return;
5766 }
5767
5768 nextRequest.halRequest = camera3_capture_request_t();
5769 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005770 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005771
5772 // Wait for additional requests
5773 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5774
5775 for (size_t i = 1; i < batchSize; i++) {
5776 NextRequest additionalRequest;
5777 additionalRequest.captureRequest = waitForNextRequestLocked();
5778 if (additionalRequest.captureRequest == nullptr) {
5779 break;
5780 }
5781
5782 additionalRequest.halRequest = camera3_capture_request_t();
5783 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005784 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005785 }
5786
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005787 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005788 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005789 mNextRequests.size(), batchSize);
5790 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005791 }
5792
5793 return;
5794}
5795
5796sp<Camera3Device::CaptureRequest>
5797 Camera3Device::RequestThread::waitForNextRequestLocked() {
5798 status_t res;
5799 sp<CaptureRequest> nextRequest;
5800
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005801 while (mRequestQueue.empty()) {
5802 if (!mRepeatingRequests.empty()) {
5803 // Always atomically enqueue all requests in a repeating request
5804 // list. Guarantees a complete in-sequence set of captures to
5805 // application.
5806 const RequestList &requests = mRepeatingRequests;
5807 RequestList::const_iterator firstRequest =
5808 requests.begin();
5809 nextRequest = *firstRequest;
5810 mRequestQueue.insert(mRequestQueue.end(),
5811 ++firstRequest,
5812 requests.end());
5813 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005814
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005815 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005816
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005817 break;
5818 }
5819
5820 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5821
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005822 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5823 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005824 Mutex::Autolock pl(mPauseLock);
5825 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005826 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005827 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005828 // Let the tracker know
5829 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5830 if (statusTracker != 0) {
5831 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5832 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005833 if (mNotifyPipelineDrain) {
5834 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5835 mNotifyPipelineDrain = false;
5836 mStreamIdsToBeDrained.clear();
5837 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005838 sp<Camera3Device> parent = mParent.promote();
5839 if (parent != nullptr) {
5840 parent->mRequestBufferSM.onRequestThreadPaused();
5841 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005842 }
5843 // Stop waiting for now and let thread management happen
5844 return NULL;
5845 }
5846 }
5847
5848 if (nextRequest == NULL) {
5849 // Don't have a repeating request already in hand, so queue
5850 // must have an entry now.
5851 RequestList::iterator firstRequest =
5852 mRequestQueue.begin();
5853 nextRequest = *firstRequest;
5854 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005855 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5856 sp<NotificationListener> listener = mListener.promote();
5857 if (listener != NULL) {
5858 listener->notifyRequestQueueEmpty();
5859 }
5860 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005861 }
5862
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005863 // In case we've been unpaused by setPaused clearing mDoPause, need to
5864 // update internal pause state (capture/setRepeatingRequest unpause
5865 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005866 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005867 if (mPaused) {
5868 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5869 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5870 if (statusTracker != 0) {
5871 statusTracker->markComponentActive(mStatusId);
5872 }
5873 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005874 mPaused = false;
5875
5876 // Check if we've reconfigured since last time, and reset the preview
5877 // request if so. Can't use 'NULL request == repeat' across configure calls.
5878 if (mReconfigured) {
5879 mPrevRequest.clear();
5880 mReconfigured = false;
5881 }
5882
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005883 if (nextRequest != NULL) {
5884 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005885 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5886 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005887
5888 // Since RequestThread::clear() removes buffers from the input stream,
5889 // get the right buffer here before unlocking mRequestLock
5890 if (nextRequest->mInputStream != NULL) {
5891 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5892 if (res != OK) {
5893 // Can't get input buffer from gralloc queue - this could be due to
5894 // disconnected queue or other producer misbehavior, so not a fatal
5895 // error
5896 ALOGE("%s: Can't get input buffer, skipping request:"
5897 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005898
5899 sp<NotificationListener> listener = mListener.promote();
5900 if (listener != NULL) {
5901 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005902 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005903 nextRequest->mResultExtras);
5904 }
5905 return NULL;
5906 }
5907 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005908 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005909
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005910 return nextRequest;
5911}
5912
5913bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005914 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005915 status_t res;
5916 Mutex::Autolock l(mPauseLock);
5917 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005918 if (mPaused == false) {
5919 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005920 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5921 // Let the tracker know
5922 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5923 if (statusTracker != 0) {
5924 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5925 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005926 if (mNotifyPipelineDrain) {
5927 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5928 mNotifyPipelineDrain = false;
5929 mStreamIdsToBeDrained.clear();
5930 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005931 sp<Camera3Device> parent = mParent.promote();
5932 if (parent != nullptr) {
5933 parent->mRequestBufferSM.onRequestThreadPaused();
5934 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005935 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005936
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005937 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005938 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005939 return true;
5940 }
5941 }
5942 // We don't set mPaused to false here, because waitForNextRequest needs
5943 // to further manage the paused state in case of starvation.
5944 return false;
5945}
5946
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005947void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005948 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005949 // With work to do, mark thread as unpaused.
5950 // If paused by request (setPaused), don't resume, to avoid
5951 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005952 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005953 Mutex::Autolock p(mPauseLock);
5954 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005955 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5956 if (mPaused) {
5957 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5958 if (statusTracker != 0) {
5959 statusTracker->markComponentActive(mStatusId);
5960 }
5961 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005962 mPaused = false;
5963 }
5964}
5965
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005966void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5967 sp<Camera3Device> parent = mParent.promote();
5968 if (parent != NULL) {
5969 va_list args;
5970 va_start(args, fmt);
5971
5972 parent->setErrorStateV(fmt, args);
5973
5974 va_end(args);
5975 }
5976}
5977
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005978status_t Camera3Device::RequestThread::insertTriggers(
5979 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005980 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005981 Mutex::Autolock al(mTriggerMutex);
5982
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005983 sp<Camera3Device> parent = mParent.promote();
5984 if (parent == NULL) {
5985 CLOGE("RequestThread: Parent is gone");
5986 return DEAD_OBJECT;
5987 }
5988
Emilian Peevaebbe412018-01-15 13:53:24 +00005989 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005990 size_t count = mTriggerMap.size();
5991
5992 for (size_t i = 0; i < count; ++i) {
5993 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005994 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005995
5996 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5997 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5998 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005999 if (isAeTrigger) {
6000 request->mResultExtras.precaptureTriggerId = triggerId;
6001 mCurrentPreCaptureTriggerId = triggerId;
6002 } else {
6003 request->mResultExtras.afTriggerId = triggerId;
6004 mCurrentAfTriggerId = triggerId;
6005 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006006 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006007 }
6008
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006009 camera_metadata_entry entry = metadata.find(tag);
6010
6011 if (entry.count > 0) {
6012 /**
6013 * Already has an entry for this trigger in the request.
6014 * Rewrite it with our requested trigger value.
6015 */
6016 RequestTrigger oldTrigger = trigger;
6017
6018 oldTrigger.entryValue = entry.data.u8[0];
6019
6020 mTriggerReplacedMap.add(tag, oldTrigger);
6021 } else {
6022 /**
6023 * More typical, no trigger entry, so we just add it
6024 */
6025 mTriggerRemovedMap.add(tag, trigger);
6026 }
6027
6028 status_t res;
6029
6030 switch (trigger.getTagType()) {
6031 case TYPE_BYTE: {
6032 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6033 res = metadata.update(tag,
6034 &entryValue,
6035 /*count*/1);
6036 break;
6037 }
6038 case TYPE_INT32:
6039 res = metadata.update(tag,
6040 &trigger.entryValue,
6041 /*count*/1);
6042 break;
6043 default:
6044 ALOGE("%s: Type not supported: 0x%x",
6045 __FUNCTION__,
6046 trigger.getTagType());
6047 return INVALID_OPERATION;
6048 }
6049
6050 if (res != OK) {
6051 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6052 ", value %d", __FUNCTION__, trigger.getTagName(),
6053 trigger.entryValue);
6054 return res;
6055 }
6056
6057 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6058 trigger.getTagName(),
6059 trigger.entryValue);
6060 }
6061
6062 mTriggerMap.clear();
6063
6064 return count;
6065}
6066
6067status_t Camera3Device::RequestThread::removeTriggers(
6068 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006069 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006070 Mutex::Autolock al(mTriggerMutex);
6071
Emilian Peevaebbe412018-01-15 13:53:24 +00006072 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006073
6074 /**
6075 * Replace all old entries with their old values.
6076 */
6077 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6078 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6079
6080 status_t res;
6081
6082 uint32_t tag = trigger.metadataTag;
6083 switch (trigger.getTagType()) {
6084 case TYPE_BYTE: {
6085 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6086 res = metadata.update(tag,
6087 &entryValue,
6088 /*count*/1);
6089 break;
6090 }
6091 case TYPE_INT32:
6092 res = metadata.update(tag,
6093 &trigger.entryValue,
6094 /*count*/1);
6095 break;
6096 default:
6097 ALOGE("%s: Type not supported: 0x%x",
6098 __FUNCTION__,
6099 trigger.getTagType());
6100 return INVALID_OPERATION;
6101 }
6102
6103 if (res != OK) {
6104 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6105 ", trigger value %d", __FUNCTION__,
6106 trigger.getTagName(), trigger.entryValue);
6107 return res;
6108 }
6109 }
6110 mTriggerReplacedMap.clear();
6111
6112 /**
6113 * Remove all new entries.
6114 */
6115 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6116 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6117 status_t res = metadata.erase(trigger.metadataTag);
6118
6119 if (res != OK) {
6120 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6121 ", trigger value %d", __FUNCTION__,
6122 trigger.getTagName(), trigger.entryValue);
6123 return res;
6124 }
6125 }
6126 mTriggerRemovedMap.clear();
6127
6128 return OK;
6129}
6130
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006131status_t Camera3Device::RequestThread::addDummyTriggerIds(
6132 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006133 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006134 static const int32_t dummyTriggerId = 1;
6135 status_t res;
6136
Emilian Peevaebbe412018-01-15 13:53:24 +00006137 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006138
6139 // If AF trigger is active, insert a dummy AF trigger ID if none already
6140 // exists
6141 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6142 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6143 if (afTrigger.count > 0 &&
6144 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6145 afId.count == 0) {
6146 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6147 if (res != OK) return res;
6148 }
6149
6150 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6151 // if none already exists
6152 camera_metadata_entry pcTrigger =
6153 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6154 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6155 if (pcTrigger.count > 0 &&
6156 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6157 pcId.count == 0) {
6158 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6159 &dummyTriggerId, 1);
6160 if (res != OK) return res;
6161 }
6162
6163 return OK;
6164}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006165
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006166/**
6167 * PreparerThread inner class methods
6168 */
6169
6170Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006171 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006172 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006173}
6174
6175Camera3Device::PreparerThread::~PreparerThread() {
6176 Thread::requestExitAndWait();
6177 if (mCurrentStream != nullptr) {
6178 mCurrentStream->cancelPrepare();
6179 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6180 mCurrentStream.clear();
6181 }
6182 clear();
6183}
6184
Ruben Brunkc78ac262015-08-13 17:58:46 -07006185status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006186 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006187 status_t res;
6188
6189 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006190 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006191
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006192 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006193 if (res == OK) {
6194 // No preparation needed, fire listener right off
6195 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006196 if (listener != NULL) {
6197 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006198 }
6199 return OK;
6200 } else if (res != NOT_ENOUGH_DATA) {
6201 return res;
6202 }
6203
6204 // Need to prepare, start up thread if necessary
6205 if (!mActive) {
6206 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6207 // isn't running
6208 Thread::requestExitAndWait();
6209 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6210 if (res != OK) {
6211 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006212 if (listener != NULL) {
6213 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006214 }
6215 return res;
6216 }
6217 mCancelNow = false;
6218 mActive = true;
6219 ALOGV("%s: Preparer stream started", __FUNCTION__);
6220 }
6221
6222 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006223 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006224 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6225
6226 return OK;
6227}
6228
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006229void Camera3Device::PreparerThread::pause() {
6230 ATRACE_CALL();
6231
6232 Mutex::Autolock l(mLock);
6233
6234 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6235 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6236 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6237 int currentMaxCount = mCurrentMaxCount;
6238 mPendingStreams.clear();
6239 mCancelNow = true;
6240 while (mActive) {
6241 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6242 if (res == TIMED_OUT) {
6243 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6244 return;
6245 } else if (res != OK) {
6246 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6247 return;
6248 }
6249 }
6250
6251 //Check whether the prepare thread was able to complete the current
6252 //stream. In case work is still pending emplace it along with the rest
6253 //of the streams in the pending list.
6254 if (currentStream != nullptr) {
6255 if (!mCurrentPrepareComplete) {
6256 pendingStreams.emplace(currentMaxCount, currentStream);
6257 }
6258 }
6259
6260 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6261 for (const auto& it : mPendingStreams) {
6262 it.second->cancelPrepare();
6263 }
6264}
6265
6266status_t Camera3Device::PreparerThread::resume() {
6267 ATRACE_CALL();
6268 status_t res;
6269
6270 Mutex::Autolock l(mLock);
6271 sp<NotificationListener> listener = mListener.promote();
6272
6273 if (mActive) {
6274 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6275 return NO_INIT;
6276 }
6277
6278 auto it = mPendingStreams.begin();
6279 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006280 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006281 if (res == OK) {
6282 if (listener != NULL) {
6283 listener->notifyPrepared(it->second->getId());
6284 }
6285 it = mPendingStreams.erase(it);
6286 } else if (res != NOT_ENOUGH_DATA) {
6287 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6288 res, strerror(-res));
6289 it = mPendingStreams.erase(it);
6290 } else {
6291 it++;
6292 }
6293 }
6294
6295 if (mPendingStreams.empty()) {
6296 return OK;
6297 }
6298
6299 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6300 if (res != OK) {
6301 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6302 __FUNCTION__, res, strerror(-res));
6303 return res;
6304 }
6305 mCancelNow = false;
6306 mActive = true;
6307 ALOGV("%s: Preparer stream started", __FUNCTION__);
6308
6309 return OK;
6310}
6311
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006312status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006313 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006314 Mutex::Autolock l(mLock);
6315
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006316 for (const auto& it : mPendingStreams) {
6317 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006318 }
6319 mPendingStreams.clear();
6320 mCancelNow = true;
6321
6322 return OK;
6323}
6324
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006325void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006326 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006327 Mutex::Autolock l(mLock);
6328 mListener = listener;
6329}
6330
6331bool Camera3Device::PreparerThread::threadLoop() {
6332 status_t res;
6333 {
6334 Mutex::Autolock l(mLock);
6335 if (mCurrentStream == nullptr) {
6336 // End thread if done with work
6337 if (mPendingStreams.empty()) {
6338 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6339 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6340 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6341 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006342 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006343 return false;
6344 }
6345
6346 // Get next stream to prepare
6347 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006348 mCurrentStream = it->second;
6349 mCurrentMaxCount = it->first;
6350 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006351 mPendingStreams.erase(it);
6352 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6353 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6354 } else if (mCancelNow) {
6355 mCurrentStream->cancelPrepare();
6356 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6357 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6358 mCurrentStream.clear();
6359 mCancelNow = false;
6360 return true;
6361 }
6362 }
6363
6364 res = mCurrentStream->prepareNextBuffer();
6365 if (res == NOT_ENOUGH_DATA) return true;
6366 if (res != OK) {
6367 // Something bad happened; try to recover by cancelling prepare and
6368 // signalling listener anyway
6369 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6370 mCurrentStream->getId(), res, strerror(-res));
6371 mCurrentStream->cancelPrepare();
6372 }
6373
6374 // This stream has finished, notify listener
6375 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006376 sp<NotificationListener> listener = mListener.promote();
6377 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006378 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6379 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006380 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006381 }
6382
6383 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6384 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006385 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006386
6387 return true;
6388}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006389
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006390status_t Camera3Device::RequestBufferStateMachine::initialize(
6391 sp<camera3::StatusTracker> statusTracker) {
6392 if (statusTracker == nullptr) {
6393 ALOGE("%s: statusTracker is null", __FUNCTION__);
6394 return BAD_VALUE;
6395 }
6396
6397 std::lock_guard<std::mutex> lock(mLock);
6398 mStatusTracker = statusTracker;
6399 mRequestBufferStatusId = statusTracker->addComponent();
6400 return OK;
6401}
6402
6403bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6404 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006405 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006406 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006407 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006408 return true;
6409 }
6410 return false;
6411}
6412
6413void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6414 std::lock_guard<std::mutex> lock(mLock);
6415 if (!mRequestBufferOngoing) {
6416 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6417 return;
6418 }
6419 mRequestBufferOngoing = false;
6420 if (mStatus == RB_STATUS_PENDING_STOP) {
6421 checkSwitchToStopLocked();
6422 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006423 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006424}
6425
6426void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6427 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006428 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006429 return;
6430}
6431
6432void Camera3Device::RequestBufferStateMachine::onRequestSubmitted() {
6433 std::lock_guard<std::mutex> lock(mLock);
6434 mRequestThreadPaused = false;
6435 mInflightMapEmpty = false;
6436 if (mStatus == RB_STATUS_STOPPED) {
6437 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006438 }
6439 return;
6440}
6441
6442void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6443 std::lock_guard<std::mutex> lock(mLock);
6444 mRequestThreadPaused = true;
6445 if (mStatus == RB_STATUS_PENDING_STOP) {
6446 checkSwitchToStopLocked();
6447 }
6448 return;
6449}
6450
6451void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6452 std::lock_guard<std::mutex> lock(mLock);
6453 mInflightMapEmpty = true;
6454 if (mStatus == RB_STATUS_PENDING_STOP) {
6455 checkSwitchToStopLocked();
6456 }
6457 return;
6458}
6459
6460void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6461 std::lock_guard<std::mutex> lock(mLock);
6462 if (!checkSwitchToStopLocked()) {
6463 mStatus = RB_STATUS_PENDING_STOP;
6464 }
6465 return;
6466}
6467
6468void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6469 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6470 if (statusTracker != nullptr) {
6471 if (active) {
6472 statusTracker->markComponentActive(mRequestBufferStatusId);
6473 } else {
6474 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6475 }
6476 }
6477}
6478
6479bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6480 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6481 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006482 return true;
6483 }
6484 return false;
6485}
6486
Shuzhen Wang268a1362018-10-16 16:32:59 -07006487status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6488 CameraMetadata& resultMetadata) {
6489 status_t res = OK;
6490 if (!mNeedFixupMonochromeTags) {
6491 return res;
6492 }
6493
6494 // Remove tags that are not applicable to monochrome camera.
6495 int32_t tagsToRemove[] = {
6496 ANDROID_SENSOR_GREEN_SPLIT,
6497 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6498 ANDROID_COLOR_CORRECTION_MODE,
6499 ANDROID_COLOR_CORRECTION_TRANSFORM,
6500 ANDROID_COLOR_CORRECTION_GAINS,
6501 };
6502 for (auto tag : tagsToRemove) {
6503 res = resultMetadata.erase(tag);
6504 if (res != OK) {
6505 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6506 return res;
6507 }
6508 }
6509
6510 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6511 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6512 for (size_t i = 1; i < blEntry.count; i++) {
6513 blEntry.data.f[i] = blEntry.data.f[0];
6514 }
6515
6516 // ANDROID_SENSOR_NOISE_PROFILE
6517 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6518 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6519 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6520 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6521 if (res != OK) {
6522 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6523 __FUNCTION__, strerror(-res), res);
6524 return res;
6525 }
6526 }
6527
6528 // ANDROID_STATISTICS_LENS_SHADING_MAP
6529 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6530 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6531 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6532 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6533 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6534 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6535 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6536 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6537 }
6538 }
6539
6540 // ANDROID_TONEMAP_CURVE_BLUE
6541 // ANDROID_TONEMAP_CURVE_GREEN
6542 // ANDROID_TONEMAP_CURVE_RED
6543 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6544 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6545 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6546 if (tcbEntry.count > 0
6547 && tcbEntry.count == tcgEntry.count
6548 && tcbEntry.count == tcrEntry.count) {
6549 for (size_t i = 0; i < tcbEntry.count; i++) {
6550 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6551 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6552 }
6553 }
6554
6555 return res;
6556}
6557
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006558}; // namespace android