blob: f982f67ebb7d0ecae52f8628dad8d97412f08e81 [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:");
178 for (auto iface : interfaceChain) {
179 ALOGV(" %s", iface.c_str());
180 }
181 });
182 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700183
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700184 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000185 std::string providerType;
186 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000187 mTagMonitor.initialize(mVendorTagId);
188 if (!monitorTags.isEmpty()) {
189 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
190 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800191
Shuzhen Wang268a1362018-10-16 16:32:59 -0700192 // Metadata tags needs fixup for monochrome camera device version less
193 // than 3.5.
194 hardware::hidl_version maxVersion{0,0};
195 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
196 if (res != OK) {
197 ALOGE("%s: Error in getting camera device version id: %s (%d)",
198 __FUNCTION__, strerror(-res), res);
199 return res;
200 }
201 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
202 maxVersion.get_major(), maxVersion.get_minor());
203
204 bool isMonochrome = false;
205 camera_metadata_entry_t entry = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
206 for (size_t i = 0; i < entry.count; i++) {
207 uint8_t capability = entry.data.u8[i];
208 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
209 isMonochrome = true;
210 }
211 }
212 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
213
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800214 return initializeCommonLocked();
215}
216
217status_t Camera3Device::initializeCommonLocked() {
218
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700219 /** Start up status tracker thread */
220 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800221 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700222 if (res != OK) {
223 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
224 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800225 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700226 mStatusTracker.clear();
227 return res;
228 }
229
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700230 /** Register in-flight map to the status tracker */
231 mInFlightStatusId = mStatusTracker->addComponent();
232
Zhijun He125684a2015-12-26 15:07:30 -0800233 /** Create buffer manager */
234 mBufferManager = new Camera3BufferManager();
235
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000236 Vector<int32_t> sessionParamKeys;
237 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
238 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
239 if (sessionKeysEntry.count > 0) {
240 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
241 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700242
243 camera_metadata_entry bufMgrMode =
244 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
245 if (bufMgrMode.count > 0) {
246 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
247 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
248 }
249
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700250 if (mUseHalBufManager) {
251 res = mRequestBufferSM.initialize(mStatusTracker);
252 if (res != OK) {
253 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
254 strerror(-res), res);
255 mInterface->close();
256 mStatusTracker.clear();
257 return res;
258 }
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 }
1110 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1111 }
1112 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001113
1114 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1115 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1116 BufferRequestStatus::FAILED_UNKNOWN,
1117 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001118 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001119 return hardware::Void();
1120}
1121
1122hardware::Return<void> Camera3Device::returnStreamBuffers(
1123 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1124 if (!mUseHalBufManager) {
1125 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1126 __FUNCTION__, mId.string());
1127 return hardware::Void();
1128 }
1129
1130 for (const auto& buf : buffers) {
1131 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1132 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1133 continue;
1134 }
1135
1136 buffer_handle_t* buffer;
1137 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1138
1139 if (res != OK) {
1140 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1141 __FUNCTION__, buf.bufferId, buf.streamId);
1142 continue;
1143 }
1144
1145 camera3_stream_buffer_t streamBuffer;
1146 streamBuffer.buffer = buffer;
1147 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1148 streamBuffer.acquire_fence = -1;
1149 streamBuffer.release_fence = -1;
1150
1151 if (buf.releaseFence == nullptr) {
1152 streamBuffer.release_fence = -1;
1153 } else if (buf.releaseFence->numFds == 1) {
1154 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1155 } else {
1156 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1157 __FUNCTION__, buf.releaseFence->numFds);
1158 continue;
1159 }
1160
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001161 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1162 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001163 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1164 continue;
1165 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001166 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001167 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1168 }
1169 return hardware::Void();
1170}
1171
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001172hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001173 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001174 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001175 // Ideally we should grab mLock, but that can lead to deadlock, and
1176 // it's not super important to get up to date value of mStatus for this
1177 // warning print, hence skipping the lock here
1178 if (mStatus == STATUS_ERROR) {
1179 // Per API contract, HAL should act as closed after device error
1180 // But mStatus can be set to error by framework as well, so just log
1181 // a warning here.
1182 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001183 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001184
1185 if (mProcessCaptureResultLock.tryLock() != OK) {
1186 // This should never happen; it indicates a wrong client implementation
1187 // that doesn't follow the contract. But, we can be tolerant here.
1188 ALOGE("%s: callback overlapped! waiting 1s...",
1189 __FUNCTION__);
1190 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1191 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1192 __FUNCTION__);
1193 // really don't know what to do, so bail out.
1194 return hardware::Void();
1195 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001196 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001197 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001198 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001199 }
1200 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001201 return hardware::Void();
1202}
1203
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001204// Only one processCaptureResult should be called at a time, so
1205// the locks won't block. The locks are present here simply to enforce this.
1206hardware::Return<void> Camera3Device::processCaptureResult(
1207 const hardware::hidl_vec<
1208 hardware::camera::device::V3_2::CaptureResult>& results) {
1209 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1210
1211 // Ideally we should grab mLock, but that can lead to deadlock, and
1212 // it's not super important to get up to date value of mStatus for this
1213 // warning print, hence skipping the lock here
1214 if (mStatus == STATUS_ERROR) {
1215 // Per API contract, HAL should act as closed after device error
1216 // But mStatus can be set to error by framework as well, so just log
1217 // a warning here.
1218 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1219 }
1220
1221 if (mProcessCaptureResultLock.tryLock() != OK) {
1222 // This should never happen; it indicates a wrong client implementation
1223 // that doesn't follow the contract. But, we can be tolerant here.
1224 ALOGE("%s: callback overlapped! waiting 1s...",
1225 __FUNCTION__);
1226 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1227 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1228 __FUNCTION__);
1229 // really don't know what to do, so bail out.
1230 return hardware::Void();
1231 }
1232 }
1233 for (const auto& result : results) {
1234 processOneCaptureResultLocked(result, noPhysMetadata);
1235 }
1236 mProcessCaptureResultLock.unlock();
1237 return hardware::Void();
1238}
1239
1240status_t Camera3Device::readOneCameraMetadataLocked(
1241 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1242 const hardware::camera::device::V3_2::CameraMetadata& result) {
1243 if (fmqResultSize > 0) {
1244 resultMetadata.resize(fmqResultSize);
1245 if (mResultMetadataQueue == nullptr) {
1246 return NO_MEMORY; // logged in initialize()
1247 }
1248 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1249 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1250 __FUNCTION__, fmqResultSize);
1251 return INVALID_OPERATION;
1252 }
1253 } else {
1254 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1255 result.size());
1256 }
1257
1258 if (resultMetadata.size() != 0) {
1259 status_t res;
1260 const camera_metadata_t* metadata =
1261 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1262 size_t expected_metadata_size = resultMetadata.size();
1263 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1264 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1265 __FUNCTION__, strerror(-res), res);
1266 return INVALID_OPERATION;
1267 }
1268 }
1269
1270 return OK;
1271}
1272
Yifan Honga640c5a2017-04-12 16:30:31 -07001273void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001274 const hardware::camera::device::V3_2::CaptureResult& result,
1275 const hardware::hidl_vec<
1276 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001277 camera3_capture_result r;
1278 status_t res;
1279 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001280
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001281 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001282 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001283 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1284 if (res != OK) {
1285 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1286 __FUNCTION__, result.frameNumber);
1287 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001288 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001289 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001290
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001291 // Read and validate physical camera metadata
1292 size_t physResultCount = physicalCameraMetadatas.size();
1293 std::vector<const char*> physCamIds(physResultCount);
1294 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1295 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1296 physResultMetadata.resize(physResultCount);
1297 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1298 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1299 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1300 if (res != OK) {
1301 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1302 __FUNCTION__, result.frameNumber,
1303 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001304 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001305 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001306 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1307 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1308 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001309 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001310 r.num_physcam_metadata = physResultCount;
1311 r.physcam_ids = physCamIds.data();
1312 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001313
1314 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1315 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1316 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1317 auto& bDst = outputBuffers[i];
1318 const StreamBuffer &bSrc = result.outputBuffers[i];
1319
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001320 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1321 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001322 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1323 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001324 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001325 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001326 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001327
1328 buffer_handle_t *buffer;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001329 if (mUseHalBufManager) {
1330 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1331 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1332 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1333 return;
1334 }
1335 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1336 } else {
1337 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1338 }
1339
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001340 if (res != OK) {
1341 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1342 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001343 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001344 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001345
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001346 bDst.buffer = buffer;
1347 bDst.status = mapHidlBufferStatus(bSrc.status);
1348 bDst.acquire_fence = -1;
1349 if (bSrc.releaseFence == nullptr) {
1350 bDst.release_fence = -1;
1351 } else if (bSrc.releaseFence->numFds == 1) {
1352 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1353 } else {
1354 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1355 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001356 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001357 }
1358 }
1359 r.num_output_buffers = outputBuffers.size();
1360 r.output_buffers = outputBuffers.data();
1361
1362 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001363 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001364 r.input_buffer = nullptr;
1365 } else {
1366 if (mInputStream->getId() != result.inputBuffer.streamId) {
1367 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1368 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001369 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001370 }
1371 inputBuffer.stream = mInputStream->asHalStream();
1372 buffer_handle_t *buffer;
1373 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1374 &buffer);
1375 if (res != OK) {
1376 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1377 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001378 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001379 }
1380 inputBuffer.buffer = buffer;
1381 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1382 inputBuffer.acquire_fence = -1;
1383 if (result.inputBuffer.releaseFence == nullptr) {
1384 inputBuffer.release_fence = -1;
1385 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1386 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1387 } else {
1388 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1389 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001390 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001391 }
1392 r.input_buffer = &inputBuffer;
1393 }
1394
1395 r.partial_result = result.partialResult;
1396
1397 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001398}
1399
1400hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001401 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001402 // Ideally we should grab mLock, but that can lead to deadlock, and
1403 // it's not super important to get up to date value of mStatus for this
1404 // warning print, hence skipping the lock here
1405 if (mStatus == STATUS_ERROR) {
1406 // Per API contract, HAL should act as closed after device error
1407 // But mStatus can be set to error by framework as well, so just log
1408 // a warning here.
1409 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001410 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001411
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001412 for (const auto& msg : msgs) {
1413 notify(msg);
1414 }
1415 return hardware::Void();
1416}
1417
1418void Camera3Device::notify(
1419 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1420
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001421 camera3_notify_msg m;
1422 switch (msg.type) {
1423 case MsgType::ERROR:
1424 m.type = CAMERA3_MSG_ERROR;
1425 m.message.error.frame_number = msg.msg.error.frameNumber;
1426 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001427 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1428 if (stream == nullptr) {
1429 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1430 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001431 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001432 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001433 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001434 } else {
1435 m.message.error.error_stream = nullptr;
1436 }
1437 switch (msg.msg.error.errorCode) {
1438 case ErrorCode::ERROR_DEVICE:
1439 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1440 break;
1441 case ErrorCode::ERROR_REQUEST:
1442 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1443 break;
1444 case ErrorCode::ERROR_RESULT:
1445 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1446 break;
1447 case ErrorCode::ERROR_BUFFER:
1448 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1449 break;
1450 }
1451 break;
1452 case MsgType::SHUTTER:
1453 m.type = CAMERA3_MSG_SHUTTER;
1454 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1455 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1456 break;
1457 }
1458 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001459}
1460
Emilian Peevaebbe412018-01-15 13:53:24 +00001461status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001462 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001463 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001464 ATRACE_CALL();
1465
Emilian Peevaebbe412018-01-15 13:53:24 +00001466 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001467}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001468
Jianing Weicb0652e2014-03-12 18:29:36 -07001469status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1470 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001471 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001472
Emilian Peevaebbe412018-01-15 13:53:24 +00001473 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001474 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001475 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001476
Emilian Peevaebbe412018-01-15 13:53:24 +00001477 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001478 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001479}
1480
Emilian Peevaebbe412018-01-15 13:53:24 +00001481status_t Camera3Device::setStreamingRequestList(
1482 const List<const PhysicalCameraSettingsList> &requestsList,
1483 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001484 ATRACE_CALL();
1485
Emilian Peevaebbe412018-01-15 13:53:24 +00001486 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001487}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001488
1489sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001490 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001491 status_t res;
1492
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001493 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001494 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1495 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001496 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1497 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001498 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001499 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001500 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001501 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001502 } else if (mStatus == STATUS_UNCONFIGURED) {
1503 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001504 CLOGE("No streams configured");
1505 return NULL;
1506 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001507 }
1508
Shuzhen Wang0129d522016-10-30 22:43:41 -07001509 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001510 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001511}
1512
Jianing Weicb0652e2014-03-12 18:29:36 -07001513status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001514 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001515 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001516 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001517
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518 switch (mStatus) {
1519 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001520 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 return INVALID_OPERATION;
1522 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001523 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001524 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001525 case STATUS_UNCONFIGURED:
1526 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001527 case STATUS_ACTIVE:
1528 // OK
1529 break;
1530 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001531 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001532 return INVALID_OPERATION;
1533 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001534 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001535
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001536 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001537}
1538
1539status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1540 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001541 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001542
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001543 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001544}
1545
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001546status_t Camera3Device::createInputStream(
1547 uint32_t width, uint32_t height, int format, int *id) {
1548 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001549 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001550 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001551 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001552 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1553 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001554
1555 status_t res;
1556 bool wasActive = false;
1557
1558 switch (mStatus) {
1559 case STATUS_ERROR:
1560 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1561 return INVALID_OPERATION;
1562 case STATUS_UNINITIALIZED:
1563 ALOGE("%s: Device not initialized", __FUNCTION__);
1564 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001565 case STATUS_UNCONFIGURED:
1566 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001567 // OK
1568 break;
1569 case STATUS_ACTIVE:
1570 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001571 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001572 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001573 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001574 return res;
1575 }
1576 wasActive = true;
1577 break;
1578 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001579 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001580 return INVALID_OPERATION;
1581 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001582 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001583
1584 if (mInputStream != 0) {
1585 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1586 return INVALID_OPERATION;
1587 }
1588
1589 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1590 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001591 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001592
1593 mInputStream = newStream;
1594
1595 *id = mNextStreamId++;
1596
1597 // Continue captures if active at start
1598 if (wasActive) {
1599 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001600 // Reuse current operating mode and session parameters for new stream config
1601 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001602 if (res != OK) {
1603 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1604 __FUNCTION__, mNextStreamId, strerror(-res), res);
1605 return res;
1606 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001607 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001608 }
1609
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001610 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001611 return OK;
1612}
1613
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001614status_t Camera3Device::StreamSet::add(
1615 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1616 if (stream == nullptr) {
1617 ALOGE("%s: cannot add null stream", __FUNCTION__);
1618 return BAD_VALUE;
1619 }
1620 std::lock_guard<std::mutex> lock(mLock);
1621 return mData.add(streamId, stream);
1622}
1623
1624ssize_t Camera3Device::StreamSet::remove(int streamId) {
1625 std::lock_guard<std::mutex> lock(mLock);
1626 return mData.removeItem(streamId);
1627}
1628
1629sp<camera3::Camera3OutputStreamInterface>
1630Camera3Device::StreamSet::get(int streamId) {
1631 std::lock_guard<std::mutex> lock(mLock);
1632 ssize_t idx = mData.indexOfKey(streamId);
1633 if (idx == NAME_NOT_FOUND) {
1634 return nullptr;
1635 }
1636 return mData.editValueAt(idx);
1637}
1638
1639sp<camera3::Camera3OutputStreamInterface>
1640Camera3Device::StreamSet::operator[] (size_t index) {
1641 std::lock_guard<std::mutex> lock(mLock);
1642 return mData.editValueAt(index);
1643}
1644
1645size_t Camera3Device::StreamSet::size() const {
1646 std::lock_guard<std::mutex> lock(mLock);
1647 return mData.size();
1648}
1649
1650void Camera3Device::StreamSet::clear() {
1651 std::lock_guard<std::mutex> lock(mLock);
1652 return mData.clear();
1653}
1654
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001655std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1656 std::lock_guard<std::mutex> lock(mLock);
1657 std::vector<int> streamIds(mData.size());
1658 for (size_t i = 0; i < mData.size(); i++) {
1659 streamIds[i] = mData.keyAt(i);
1660 }
1661 return streamIds;
1662}
1663
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001664status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001665 uint32_t width, uint32_t height, int format,
1666 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001667 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001668 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001669 ATRACE_CALL();
1670
1671 if (consumer == nullptr) {
1672 ALOGE("%s: consumer must not be null", __FUNCTION__);
1673 return BAD_VALUE;
1674 }
1675
1676 std::vector<sp<Surface>> consumers;
1677 consumers.push_back(consumer);
1678
1679 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001680 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1681 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001682}
1683
1684status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1685 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1686 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001687 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001688 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001689 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001690
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001691 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001692 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001693 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001694 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001695 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1696 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1697 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001698
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001699 status_t res;
1700 bool wasActive = false;
1701
1702 switch (mStatus) {
1703 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001704 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001705 return INVALID_OPERATION;
1706 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001707 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001708 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001709 case STATUS_UNCONFIGURED:
1710 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001711 // OK
1712 break;
1713 case STATUS_ACTIVE:
1714 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001715 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001716 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001717 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001718 return res;
1719 }
1720 wasActive = true;
1721 break;
1722 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001723 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001724 return INVALID_OPERATION;
1725 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001726 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001727
1728 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001729
Shuzhen Wang0129d522016-10-30 22:43:41 -07001730 if (consumers.size() == 0 && !hasDeferredConsumer) {
1731 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1732 return BAD_VALUE;
1733 }
Zhijun He5d677d12016-05-29 16:52:39 -07001734
Shuzhen Wang0129d522016-10-30 22:43:41 -07001735 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001736 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1737 return BAD_VALUE;
1738 }
1739
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001740 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001741 ssize_t blobBufferSize;
1742 if (dataSpace != HAL_DATASPACE_DEPTH) {
1743 blobBufferSize = getJpegBufferSize(width, height);
1744 if (blobBufferSize <= 0) {
1745 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1746 return BAD_VALUE;
1747 }
1748 } else {
1749 blobBufferSize = getPointCloudBufferSize();
1750 if (blobBufferSize <= 0) {
1751 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1752 return BAD_VALUE;
1753 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001754 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001755 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001756 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001757 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001758 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1759 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1760 if (rawOpaqueBufferSize <= 0) {
1761 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1762 return BAD_VALUE;
1763 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001764 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001765 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001766 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001767 } else if (isShared) {
1768 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1769 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001770 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001771 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001772 newStream = new Camera3OutputStream(mNextStreamId,
1773 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001774 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001775 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001776 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001777 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001778 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001779 }
Emilian Peev40ead602017-09-26 15:46:36 +01001780
1781 size_t consumerCount = consumers.size();
1782 for (size_t i = 0; i < consumerCount; i++) {
1783 int id = newStream->getSurfaceId(consumers[i]);
1784 if (id < 0) {
1785 SET_ERR_L("Invalid surface id");
1786 return BAD_VALUE;
1787 }
1788 if (surfaceIds != nullptr) {
1789 surfaceIds->push_back(id);
1790 }
1791 }
1792
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001793 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001794
Emilian Peev08dd2452017-04-06 16:55:14 +01001795 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001796
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001797 res = mOutputStreams.add(mNextStreamId, newStream);
1798 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001799 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001800 return res;
1801 }
1802
1803 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001804 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001805
1806 // Continue captures if active at start
1807 if (wasActive) {
1808 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001809 // Reuse current operating mode and session parameters for new stream config
1810 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001811 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001812 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1813 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001814 return res;
1815 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001816 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001817 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001818 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001819 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001820}
1821
Emilian Peev710c1422017-08-30 11:19:38 +01001822status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001823 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001824 if (nullptr == streamInfo) {
1825 return BAD_VALUE;
1826 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001827 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001828 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001829
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001830 switch (mStatus) {
1831 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001832 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001833 return INVALID_OPERATION;
1834 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001835 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001836 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001837 case STATUS_UNCONFIGURED:
1838 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001839 case STATUS_ACTIVE:
1840 // OK
1841 break;
1842 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001843 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001844 return INVALID_OPERATION;
1845 }
1846
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001847 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1848 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001849 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001850 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001851 }
1852
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001853 streamInfo->width = stream->getWidth();
1854 streamInfo->height = stream->getHeight();
1855 streamInfo->format = stream->getFormat();
1856 streamInfo->dataSpace = stream->getDataSpace();
1857 streamInfo->formatOverridden = stream->isFormatOverridden();
1858 streamInfo->originalFormat = stream->getOriginalFormat();
1859 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1860 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001861 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001862}
1863
1864status_t Camera3Device::setStreamTransform(int id,
1865 int transform) {
1866 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001867 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001868 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001869
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001870 switch (mStatus) {
1871 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001872 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001873 return INVALID_OPERATION;
1874 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001875 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001876 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001877 case STATUS_UNCONFIGURED:
1878 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001879 case STATUS_ACTIVE:
1880 // OK
1881 break;
1882 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001883 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001884 return INVALID_OPERATION;
1885 }
1886
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001887 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1888 if (stream == nullptr) {
1889 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001890 return BAD_VALUE;
1891 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001892 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001893}
1894
1895status_t Camera3Device::deleteStream(int id) {
1896 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001897 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001898 Mutex::Autolock l(mLock);
1899 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001900
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001901 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001902
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001903 // CameraDevice semantics require device to already be idle before
1904 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001905 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001906 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001907 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001908 }
1909
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001910 if (mStatus == STATUS_ERROR) {
1911 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1912 __FUNCTION__, mId.string());
1913 return -EBUSY;
1914 }
1915
Igor Murashkin2fba5842013-04-22 14:03:54 -07001916 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001917 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001918 if (mInputStream != NULL && id == mInputStream->getId()) {
1919 deletedStream = mInputStream;
1920 mInputStream.clear();
1921 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001922 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001923 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001924 return BAD_VALUE;
1925 }
Zhijun He5f446352014-01-22 09:49:33 -08001926 }
1927
1928 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001929 if (stream != nullptr) {
1930 deletedStream = stream;
1931 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001932 }
1933
1934 // Free up the stream endpoint so that it can be used by some other stream
1935 res = deletedStream->disconnect();
1936 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001937 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001938 // fall through since we want to still list the stream as deleted.
1939 }
1940 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001941 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001942
1943 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001944}
1945
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001946status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001947 ATRACE_CALL();
1948 ALOGV("%s: E", __FUNCTION__);
1949
1950 Mutex::Autolock il(mInterfaceLock);
1951 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001952
Emilian Peev811d2952018-05-25 11:08:40 +01001953 // In case the client doesn't include any session parameter, try a
1954 // speculative configuration using the values from the last cached
1955 // default request.
1956 if (sessionParams.isEmpty() &&
1957 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1958 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1959 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1960 mLastTemplateId);
1961 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1962 operatingMode);
1963 }
1964
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001965 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1966}
1967
1968status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1969 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001970 //Filter out any incoming session parameters
1971 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001972 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1973 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001974 CameraMetadata filteredParams(availableSessionKeys.count);
1975 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1976 filteredParams.getAndLock());
1977 set_camera_metadata_vendor_id(meta, mVendorTagId);
1978 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001979 if (availableSessionKeys.count > 0) {
1980 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1981 camera_metadata_ro_entry entry = params.find(
1982 availableSessionKeys.data.i32[i]);
1983 if (entry.count > 0) {
1984 filteredParams.update(entry);
1985 }
1986 }
1987 }
1988
1989 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001990}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001991
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001992status_t Camera3Device::getInputBufferProducer(
1993 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001994 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001995 Mutex::Autolock il(mInterfaceLock);
1996 Mutex::Autolock l(mLock);
1997
1998 if (producer == NULL) {
1999 return BAD_VALUE;
2000 } else if (mInputStream == NULL) {
2001 return INVALID_OPERATION;
2002 }
2003
2004 return mInputStream->getInputBufferProducer(producer);
2005}
2006
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002007status_t Camera3Device::createDefaultRequest(int templateId,
2008 CameraMetadata *request) {
2009 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002010 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002011
2012 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2013 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002014 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002015 return BAD_VALUE;
2016 }
2017
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002018 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002019
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002020 {
2021 Mutex::Autolock l(mLock);
2022 switch (mStatus) {
2023 case STATUS_ERROR:
2024 CLOGE("Device has encountered a serious error");
2025 return INVALID_OPERATION;
2026 case STATUS_UNINITIALIZED:
2027 CLOGE("Device is not initialized!");
2028 return INVALID_OPERATION;
2029 case STATUS_UNCONFIGURED:
2030 case STATUS_CONFIGURED:
2031 case STATUS_ACTIVE:
2032 // OK
2033 break;
2034 default:
2035 SET_ERR_L("Unexpected status: %d", mStatus);
2036 return INVALID_OPERATION;
2037 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002038
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002039 if (!mRequestTemplateCache[templateId].isEmpty()) {
2040 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002041 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002042 return OK;
2043 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002044 }
2045
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002046 camera_metadata_t *rawRequest;
2047 status_t res = mInterface->constructDefaultRequestSettings(
2048 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002049
2050 {
2051 Mutex::Autolock l(mLock);
2052 if (res == BAD_VALUE) {
2053 ALOGI("%s: template %d is not supported on this camera device",
2054 __FUNCTION__, templateId);
2055 return res;
2056 } else if (res != OK) {
2057 CLOGE("Unable to construct request template %d: %s (%d)",
2058 templateId, strerror(-res), res);
2059 return res;
2060 }
2061
2062 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2063 mRequestTemplateCache[templateId].acquire(rawRequest);
2064
2065 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002066 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002067 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002068 return OK;
2069}
2070
2071status_t Camera3Device::waitUntilDrained() {
2072 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002073 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002074 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002075 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002076
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002077 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002078}
2079
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002080status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002081 switch (mStatus) {
2082 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002083 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002084 ALOGV("%s: Already idle", __FUNCTION__);
2085 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002086 case STATUS_CONFIGURED:
2087 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002088 case STATUS_ERROR:
2089 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002090 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002091 break;
2092 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002093 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002094 return INVALID_OPERATION;
2095 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002096 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2097 maxExpectedDuration);
2098 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002099 if (res != OK) {
2100 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2101 res);
2102 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002103 return res;
2104}
2105
Ruben Brunk183f0562015-08-12 12:55:02 -07002106
2107void Camera3Device::internalUpdateStatusLocked(Status status) {
2108 mStatus = status;
2109 mRecentStatusUpdates.add(mStatus);
2110 mStatusChanged.broadcast();
2111}
2112
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002113void Camera3Device::pauseStateNotify(bool enable) {
2114 Mutex::Autolock il(mInterfaceLock);
2115 Mutex::Autolock l(mLock);
2116
2117 mPauseStateNotify = enable;
2118}
2119
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002120// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002121status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002122 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002123
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002124 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2125 maxExpectedDuration);
2126 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002127 if (res != OK) {
2128 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002129 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002130 }
2131
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002132 return res;
2133}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002134
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002135// Resume after internalPauseAndWaitLocked
2136status_t Camera3Device::internalResumeLocked() {
2137 status_t res;
2138
2139 mRequestThread->setPaused(false);
2140
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002141 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2142 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002143 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2144 if (res != OK) {
2145 SET_ERR_L("Can't transition to active in %f seconds!",
2146 kActiveTimeout/1e9);
2147 }
2148 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002149 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002150}
2151
Ruben Brunk183f0562015-08-12 12:55:02 -07002152status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002153 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002154
2155 size_t startIndex = 0;
2156 if (mStatusWaiters == 0) {
2157 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2158 // this status list
2159 mRecentStatusUpdates.clear();
2160 } else {
2161 // If other threads are waiting on updates to this status list, set the position of the
2162 // first element that this list will check rather than clearing the list.
2163 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002164 }
2165
Ruben Brunk183f0562015-08-12 12:55:02 -07002166 mStatusWaiters++;
2167
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002168 // Notify HAL to start draining. We need to notify the HalInterface layer
2169 // even when the device is already IDLE, so HalInterface can reject incoming
2170 // requestStreamBuffers call.
2171 if (!active && mUseHalBufManager) {
2172 auto streamIds = mOutputStreams.getStreamIds();
2173 mRequestThread->signalPipelineDrain(streamIds);
2174 mRequestBufferSM.onWaitUntilIdle();
2175 }
2176
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002177 bool stateSeen = false;
2178 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002179 if (active == (mStatus == STATUS_ACTIVE)) {
2180 // Desired state is current
2181 break;
2182 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002183
2184 res = mStatusChanged.waitRelative(mLock, timeout);
2185 if (res != OK) break;
2186
Ruben Brunk183f0562015-08-12 12:55:02 -07002187 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2188 // transitions.
2189 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2190 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2191 __FUNCTION__);
2192
2193 // Encountered desired state since we began waiting
2194 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002195 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2196 stateSeen = true;
2197 break;
2198 }
2199 }
2200 } while (!stateSeen);
2201
Ruben Brunk183f0562015-08-12 12:55:02 -07002202 mStatusWaiters--;
2203
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002204 return res;
2205}
2206
2207
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002208status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002209 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002210 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002211
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002212 if (listener != NULL && mListener != NULL) {
2213 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2214 }
2215 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002216 mRequestThread->setNotificationListener(listener);
2217 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002218
2219 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002220}
2221
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002222bool Camera3Device::willNotify3A() {
2223 return false;
2224}
2225
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002226status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002227 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002228 status_t res;
2229 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002230
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002231 while (mResultQueue.empty()) {
2232 res = mResultSignal.waitRelative(mOutputLock, timeout);
2233 if (res == TIMED_OUT) {
2234 return res;
2235 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002236 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2237 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002238 return res;
2239 }
2240 }
2241 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002242}
2243
Jianing Weicb0652e2014-03-12 18:29:36 -07002244status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002245 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002246 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002247
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002248 if (mResultQueue.empty()) {
2249 return NOT_ENOUGH_DATA;
2250 }
2251
Jianing Weicb0652e2014-03-12 18:29:36 -07002252 if (frame == NULL) {
2253 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2254 return BAD_VALUE;
2255 }
2256
2257 CaptureResult &result = *(mResultQueue.begin());
2258 frame->mResultExtras = result.mResultExtras;
2259 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002260 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002261 mResultQueue.erase(mResultQueue.begin());
2262
2263 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002264}
2265
2266status_t Camera3Device::triggerAutofocus(uint32_t id) {
2267 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002268 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002269
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002270 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2271 // Mix-in this trigger into the next request and only the next request.
2272 RequestTrigger trigger[] = {
2273 {
2274 ANDROID_CONTROL_AF_TRIGGER,
2275 ANDROID_CONTROL_AF_TRIGGER_START
2276 },
2277 {
2278 ANDROID_CONTROL_AF_TRIGGER_ID,
2279 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002280 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002281 };
2282
2283 return mRequestThread->queueTrigger(trigger,
2284 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002285}
2286
2287status_t Camera3Device::triggerCancelAutofocus(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 cancel 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_CANCEL
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 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002303
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002304 return mRequestThread->queueTrigger(trigger,
2305 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002306}
2307
2308status_t Camera3Device::triggerPrecaptureMetering(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 precapture metering, 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_AE_PRECAPTURE_TRIGGER,
2317 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2318 },
2319 {
2320 ANDROID_CONTROL_AE_PRECAPTURE_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
Jianing Weicb0652e2014-03-12 18:29:36 -07002329status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002330 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002331 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002332 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002333
Zhijun He7ef20392014-04-21 16:04:17 -07002334 {
2335 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002336
2337 // b/116514106 "disconnect()" can get called twice for the same device. The
2338 // camera device will not be initialized during the second run.
2339 if (mStatus == STATUS_UNINITIALIZED) {
2340 return OK;
2341 }
2342
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002343 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002344 }
2345
Emilian Peev08dd2452017-04-06 16:55:14 +01002346 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002347}
2348
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002349status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002350 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2351}
2352
2353status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002354 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002355 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002356 Mutex::Autolock il(mInterfaceLock);
2357 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002358
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002359 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2360 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002361 CLOGE("Stream %d does not exist", streamId);
2362 return BAD_VALUE;
2363 }
2364
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002365 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002366 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002367 return BAD_VALUE;
2368 }
2369
2370 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002371 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002372 return BAD_VALUE;
2373 }
2374
Ruben Brunkc78ac262015-08-13 17:58:46 -07002375 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002376}
2377
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002378status_t Camera3Device::tearDown(int streamId) {
2379 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002380 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002381 Mutex::Autolock il(mInterfaceLock);
2382 Mutex::Autolock l(mLock);
2383
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002384 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2385 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002386 CLOGE("Stream %d does not exist", streamId);
2387 return BAD_VALUE;
2388 }
2389
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002390 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2391 CLOGE("Stream %d is a target of a in-progress request", streamId);
2392 return BAD_VALUE;
2393 }
2394
2395 return stream->tearDown();
2396}
2397
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002398status_t Camera3Device::addBufferListenerForStream(int streamId,
2399 wp<Camera3StreamBufferListener> listener) {
2400 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002401 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -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) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002407 CLOGE("Stream %d does not exist", streamId);
2408 return BAD_VALUE;
2409 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002410 stream->addBufferListener(listener);
2411
2412 return OK;
2413}
2414
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002415/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002416 * Methods called by subclasses
2417 */
2418
2419void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002420 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002421 {
2422 // Need mLock to safely update state and synchronize to current
2423 // state of methods in flight.
2424 Mutex::Autolock l(mLock);
2425 // We can get various system-idle notices from the status tracker
2426 // while starting up. Only care about them if we've actually sent
2427 // in some requests recently.
2428 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2429 return;
2430 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002431 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2432 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002433 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002434
2435 // Skip notifying listener if we're doing some user-transparent
2436 // state changes
2437 if (mPauseStateNotify) return;
2438 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002439
2440 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002441 {
2442 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002443 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002444 }
2445 if (idle && listener != NULL) {
2446 listener->notifyIdle();
2447 }
2448}
2449
Shuzhen Wang758c2152017-01-10 18:26:18 -08002450status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002451 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002452 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002453 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2454 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002455
2456 if (surfaceIds == nullptr) {
2457 return BAD_VALUE;
2458 }
2459
Zhijun He5d677d12016-05-29 16:52:39 -07002460 Mutex::Autolock il(mInterfaceLock);
2461 Mutex::Autolock l(mLock);
2462
Shuzhen Wang758c2152017-01-10 18:26:18 -08002463 if (consumers.size() == 0) {
2464 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002465 return BAD_VALUE;
2466 }
2467
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002468 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2469 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002470 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002471 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002472 }
Shuzhen Wang758c2152017-01-10 18:26:18 -08002473 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002474 if (res != OK) {
2475 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2476 return res;
2477 }
2478
Emilian Peev40ead602017-09-26 15:46:36 +01002479 for (auto &consumer : consumers) {
2480 int id = stream->getSurfaceId(consumer);
2481 if (id < 0) {
2482 CLOGE("Invalid surface id!");
2483 return BAD_VALUE;
2484 }
2485 surfaceIds->push_back(id);
2486 }
2487
Shuzhen Wang0129d522016-10-30 22:43:41 -07002488 if (stream->isConsumerConfigurationDeferred()) {
2489 if (!stream->isConfiguring()) {
2490 CLOGE("Stream %d was already fully configured.", streamId);
2491 return INVALID_OPERATION;
2492 }
Zhijun He5d677d12016-05-29 16:52:39 -07002493
Shuzhen Wang0129d522016-10-30 22:43:41 -07002494 res = stream->finishConfiguration();
2495 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002496 // If finishConfiguration fails due to abandoned surface, do not set
2497 // device to error state.
2498 bool isSurfaceAbandoned =
2499 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2500 if (!isSurfaceAbandoned) {
2501 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2502 stream->getId(), strerror(-res), res);
2503 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002504 return res;
2505 }
Zhijun He5d677d12016-05-29 16:52:39 -07002506 }
2507
2508 return OK;
2509}
2510
Emilian Peev40ead602017-09-26 15:46:36 +01002511status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2512 const std::vector<OutputStreamInfo> &outputInfo,
2513 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2514 Mutex::Autolock il(mInterfaceLock);
2515 Mutex::Autolock l(mLock);
2516
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002517 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2518 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002519 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002520 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002521 }
2522
2523 for (const auto &it : removedSurfaceIds) {
2524 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2525 CLOGE("Shared surface still part of a pending request!");
2526 return -EBUSY;
2527 }
2528 }
2529
Emilian Peev40ead602017-09-26 15:46:36 +01002530 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2531 if (res != OK) {
2532 CLOGE("Stream %d failed to update stream (error %d %s) ",
2533 streamId, res, strerror(-res));
2534 if (res == UNKNOWN_ERROR) {
2535 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2536 __FUNCTION__);
2537 }
2538 return res;
2539 }
2540
2541 return res;
2542}
2543
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002544status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2545 Mutex::Autolock il(mInterfaceLock);
2546 Mutex::Autolock l(mLock);
2547
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002548 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2549 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002550 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2551 return BAD_VALUE;
2552 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002553 return stream->dropBuffers(dropping);
2554}
2555
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002556/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002557 * Camera3Device private methods
2558 */
2559
2560sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002561 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002562 ATRACE_CALL();
2563 status_t res;
2564
2565 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002566 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002567
2568 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002569 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002570 if (inputStreams.count > 0) {
2571 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002572 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002573 CLOGE("Request references unknown input stream %d",
2574 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002575 return NULL;
2576 }
2577 // Lazy completion of stream configuration (allocation/registration)
2578 // on first use
2579 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002580 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002581 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002582 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002583 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002584 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002585 return NULL;
2586 }
2587 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002588 // Check if stream prepare is blocking requests.
2589 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002590 CLOGE("Request references an input stream that's being prepared!");
2591 return NULL;
2592 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002593
2594 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002595 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002596 }
2597
2598 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002599 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002600 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002601 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002602 return NULL;
2603 }
2604
2605 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002606 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2607 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002608 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002609 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002610 return NULL;
2611 }
Zhijun He5d677d12016-05-29 16:52:39 -07002612 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002613 auto iter = surfaceMap.find(streams.data.i32[i]);
2614 if (iter != surfaceMap.end()) {
2615 const std::vector<size_t>& surfaces = iter->second;
2616 for (const auto& surface : surfaces) {
2617 if (stream->isConsumerConfigurationDeferred(surface)) {
2618 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2619 "due to deferred consumer", stream->getId(), surface);
2620 return NULL;
2621 }
2622 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002623 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002624 }
2625
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002626 // Lazy completion of stream configuration (allocation/registration)
2627 // on first use
2628 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002629 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002630 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002631 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2632 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002633 return NULL;
2634 }
2635 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002636 // Check if stream prepare is blocking requests.
2637 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002638 CLOGE("Request references an output stream that's being prepared!");
2639 return NULL;
2640 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002641
2642 newRequest->mOutputStreams.push(stream);
2643 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002644 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002645 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002646
2647 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002648}
2649
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002650bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2651 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2652 Size size = mSupportedOpaqueInputSizes[i];
2653 if (size.width == width && size.height == height) {
2654 return true;
2655 }
2656 }
2657
2658 return false;
2659}
2660
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002661void Camera3Device::cancelStreamsConfigurationLocked() {
2662 int res = OK;
2663 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2664 res = mInputStream->cancelConfiguration();
2665 if (res != OK) {
2666 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2667 mInputStream->getId(), strerror(-res), res);
2668 }
2669 }
2670
2671 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002672 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002673 if (outputStream->isConfiguring()) {
2674 res = outputStream->cancelConfiguration();
2675 if (res != OK) {
2676 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2677 outputStream->getId(), strerror(-res), res);
2678 }
2679 }
2680 }
2681
2682 // Return state to that at start of call, so that future configures
2683 // properly clean things up
2684 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2685 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002686
2687 res = mPreparerThread->resume();
2688 if (res != OK) {
2689 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2690 }
2691}
2692
2693bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2694 ATRACE_CALL();
2695 bool ret = false;
2696
2697 Mutex::Autolock il(mInterfaceLock);
2698 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2699
2700 Mutex::Autolock l(mLock);
2701 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2702 if (rc == NO_ERROR) {
2703 mNeedConfig = true;
2704 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2705 if (rc == NO_ERROR) {
2706 ret = true;
2707 mPauseStateNotify = false;
2708 //Moving to active state while holding 'mLock' is important.
2709 //There could be pending calls to 'create-/deleteStream' which
2710 //will trigger another stream configuration while the already
2711 //present streams end up with outstanding buffers that will
2712 //not get drained.
2713 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002714 } else if (rc == DEAD_OBJECT) {
2715 // DEAD_OBJECT can be returned if either the consumer surface is
2716 // abandoned, or the HAL has died.
2717 // - If the HAL has died, configureStreamsLocked call will set
2718 // device to error state,
2719 // - If surface is abandoned, we should not set device to error
2720 // state.
2721 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002722 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002723 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002724 }
2725 } else {
2726 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2727 }
2728
2729 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002730}
2731
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002732status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002733 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002734 ATRACE_CALL();
2735 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002736
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002737 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002738 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002739 return INVALID_OPERATION;
2740 }
2741
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002742 if (operatingMode < 0) {
2743 CLOGE("Invalid operating mode: %d", operatingMode);
2744 return BAD_VALUE;
2745 }
2746
2747 bool isConstrainedHighSpeed =
2748 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2749 operatingMode;
2750
2751 if (mOperatingMode != operatingMode) {
2752 mNeedConfig = true;
2753 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2754 mOperatingMode = operatingMode;
2755 }
2756
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002757 if (!mNeedConfig) {
2758 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2759 return OK;
2760 }
2761
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002762 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2763 // adding a dummy stream instead.
2764 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2765 if (mOutputStreams.size() == 0) {
2766 addDummyStreamLocked();
2767 } else {
2768 tryRemoveDummyStreamLocked();
2769 }
2770
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002771 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002772 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002773
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002774 mPreparerThread->pause();
2775
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002776 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002777 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002778 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2779
2780 Vector<camera3_stream_t*> streams;
2781 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002782 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002783
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002784
2785 if (mInputStream != NULL) {
2786 camera3_stream_t *inputStream;
2787 inputStream = mInputStream->startConfiguration();
2788 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002789 CLOGE("Can't start input stream configuration");
2790 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002791 return INVALID_OPERATION;
2792 }
2793 streams.add(inputStream);
2794 }
2795
2796 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002797
2798 // Don't configure bidi streams twice, nor add them twice to the list
2799 if (mOutputStreams[i].get() ==
2800 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2801
2802 config.num_streams--;
2803 continue;
2804 }
2805
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002806 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002807 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002808 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002809 CLOGE("Can't start output stream configuration");
2810 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002811 return INVALID_OPERATION;
2812 }
2813 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002814
2815 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2816 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002817 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2818 // always occupy the initial entry.
2819 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002820 getJpegBufferSize(outputStream->width, outputStream->height));
2821 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002822 }
2823
2824 config.streams = streams.editArray();
2825
2826 // Do the HAL configuration; will potentially touch stream
2827 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002828
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002829 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002830 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002831 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002832
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002833 if (res == BAD_VALUE) {
2834 // HAL rejected this set of streams as unsupported, clean up config
2835 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002836 CLOGE("Set of requested inputs/outputs not supported by HAL");
2837 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002838 return BAD_VALUE;
2839 } else if (res != OK) {
2840 // Some other kind of error from configure_streams - this is not
2841 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002842 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2843 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002844 return res;
2845 }
2846
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002847 // Finish all stream configuration immediately.
2848 // TODO: Try to relax this later back to lazy completion, which should be
2849 // faster
2850
Igor Murashkin073f8572013-05-02 14:59:28 -07002851 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002852 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002853 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002854 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002855 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002856 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002857 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2858 return DEAD_OBJECT;
2859 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002860 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002861 }
2862 }
2863
2864 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002865 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002866 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002867 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002868 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002869 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002870 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002871 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002872 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2873 return DEAD_OBJECT;
2874 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002875 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002876 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002877 }
2878 }
2879
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002880 // Request thread needs to know to avoid using repeat-last-settings protocol
2881 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002882 if (notifyRequestThread) {
2883 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2884 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002885
Zhijun He90f7c372016-08-16 16:19:43 -07002886 char value[PROPERTY_VALUE_MAX];
2887 property_get("camera.fifo.disable", value, "0");
2888 int32_t disableFifo = atoi(value);
2889 if (disableFifo != 1) {
2890 // Boost priority of request thread to SCHED_FIFO.
2891 pid_t requestThreadTid = mRequestThread->getTid();
2892 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002893 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002894 if (res != OK) {
2895 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2896 strerror(-res), res);
2897 } else {
2898 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2899 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002900 }
2901
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002902 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002903 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2904 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2905 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2906 sessionParams.unlock(newSessionParams);
2907 mSessionParams.unlock(currentSessionParams);
2908 if (updateSessionParams) {
2909 mSessionParams = sessionParams;
2910 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002911
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002912 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002913
Ruben Brunk183f0562015-08-12 12:55:02 -07002914 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2915 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002916
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002917 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002918
Zhijun He0a210512014-07-24 13:45:15 -07002919 // tear down the deleted streams after configure streams.
2920 mDeletedStreams.clear();
2921
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002922 auto rc = mPreparerThread->resume();
2923 if (rc != OK) {
2924 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2925 return rc;
2926 }
2927
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002928 if (mDummyStreamId == NO_STREAM) {
2929 mRequestBufferSM.onStreamsConfigured();
2930 }
2931
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002932 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002933}
2934
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002935status_t Camera3Device::addDummyStreamLocked() {
2936 ATRACE_CALL();
2937 status_t res;
2938
2939 if (mDummyStreamId != NO_STREAM) {
2940 // Should never be adding a second dummy stream when one is already
2941 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002942 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2943 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002944 return INVALID_OPERATION;
2945 }
2946
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002947 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002948
2949 sp<Camera3OutputStreamInterface> dummyStream =
2950 new Camera3DummyStream(mNextStreamId);
2951
2952 res = mOutputStreams.add(mNextStreamId, dummyStream);
2953 if (res < 0) {
2954 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2955 return res;
2956 }
2957
2958 mDummyStreamId = mNextStreamId;
2959 mNextStreamId++;
2960
2961 return OK;
2962}
2963
2964status_t Camera3Device::tryRemoveDummyStreamLocked() {
2965 ATRACE_CALL();
2966 status_t res;
2967
2968 if (mDummyStreamId == NO_STREAM) return OK;
2969 if (mOutputStreams.size() == 1) return OK;
2970
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002971 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002972
2973 // Ok, have a dummy stream and there's at least one other output stream,
2974 // so remove the dummy
2975
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002976 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2977 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002978 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2979 return INVALID_OPERATION;
2980 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002981 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002982
2983 // Free up the stream endpoint so that it can be used by some other stream
2984 res = deletedStream->disconnect();
2985 if (res != OK) {
2986 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2987 // fall through since we want to still list the stream as deleted.
2988 }
2989 mDeletedStreams.add(deletedStream);
2990 mDummyStreamId = NO_STREAM;
2991
2992 return res;
2993}
2994
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002995void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002996 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002997 Mutex::Autolock l(mLock);
2998 va_list args;
2999 va_start(args, fmt);
3000
3001 setErrorStateLockedV(fmt, args);
3002
3003 va_end(args);
3004}
3005
3006void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003007 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003008 Mutex::Autolock l(mLock);
3009 setErrorStateLockedV(fmt, args);
3010}
3011
3012void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3013 va_list args;
3014 va_start(args, fmt);
3015
3016 setErrorStateLockedV(fmt, args);
3017
3018 va_end(args);
3019}
3020
3021void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003022 // Print out all error messages to log
3023 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003024 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003025
3026 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003027 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003028
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003029 mErrorCause = errorCause;
3030
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003031 if (mRequestThread != nullptr) {
3032 mRequestThread->setPaused(true);
3033 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003034 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003035
3036 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003037 sp<NotificationListener> listener = mListener.promote();
3038 if (listener != NULL) {
3039 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003040 CaptureResultExtras());
3041 }
3042
3043 // Save stack trace. View by dumping it later.
3044 CameraTraces::saveTrace();
3045 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003046}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003047
3048/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003049 * In-flight request management
3050 */
3051
Jianing Weicb0652e2014-03-12 18:29:36 -07003052status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003053 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003054 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003055 std::set<String8>& physicalCameraIds, bool isStillCapture,
3056 bool isZslCapture) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003057 ATRACE_CALL();
3058 Mutex::Autolock l(mInFlightLock);
3059
3060 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003061 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003062 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003063 if (res < 0) return res;
3064
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003065 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003066 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3067 // avoid a deadlock during reprocess requests.
3068 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003069 if (mStatusTracker != nullptr) {
3070 mStatusTracker->markComponentActive(mInFlightStatusId);
3071 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003072 }
3073
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003074 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003075 return OK;
3076}
3077
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003078void Camera3Device::returnOutputBuffers(
3079 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003080 nsecs_t timestamp, bool timestampIncreasing) {
3081
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003082 for (size_t i = 0; i < numBuffers; i++)
3083 {
3084 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003085 status_t res = stream->returnBuffer(outputBuffers[i], timestamp, timestampIncreasing);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003086 // Note: stream may be deallocated at this point, if this buffer was
3087 // the last reference to it.
3088 if (res != OK) {
3089 ALOGE("Can't return buffer to its stream: %s (%d)",
3090 strerror(-res), res);
3091 }
3092 }
3093}
3094
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003095void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003096 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003097 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003098 mInFlightMap.removeItemsAt(idx, 1);
3099
3100 // Indicate idle inFlightMap to the status tracker
3101 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003102 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003103 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3104 // avoid a deadlock during reprocess requests.
3105 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003106 if (mStatusTracker != nullptr) {
3107 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3108 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003109 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003110 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003111}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003112
3113void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3114
3115 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3116 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3117
3118 nsecs_t sensorTimestamp = request.sensorTimestamp;
3119 nsecs_t shutterTimestamp = request.shutterTimestamp;
3120
3121 // Check if it's okay to remove the request from InFlightMap:
3122 // In the case of a successful request:
3123 // all input and output buffers, all result metadata, shutter callback
3124 // arrived.
3125 // In the case of a unsuccessful request:
3126 // all input and output buffers arrived.
3127 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003128 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003129 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003130 if (request.stillCapture) {
3131 ATRACE_ASYNC_END("still capture", frameNumber);
3132 }
3133
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003134 ATRACE_ASYNC_END("frame capture", frameNumber);
3135
Shuzhen Wang403044a2017-02-26 23:29:04 -08003136 // Sanity check - if sensor timestamp matches shutter timestamp in the
3137 // case of request having callback.
3138 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003139 sensorTimestamp != shutterTimestamp) {
3140 SET_ERR("sensor timestamp (%" PRId64
3141 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3142 sensorTimestamp, frameNumber, shutterTimestamp);
3143 }
3144
3145 // for an unsuccessful request, it may have pending output buffers to
3146 // return.
3147 assert(request.requestStatus != OK ||
3148 request.pendingOutputBuffers.size() == 0);
3149 returnOutputBuffers(request.pendingOutputBuffers.array(),
3150 request.pendingOutputBuffers.size(), 0);
3151
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003152 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003153 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3154 }
3155
3156 // Sanity check - if we have too many in-flight frames, something has
3157 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003158 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003159 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003160 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3161 kInFlightWarnLimitHighSpeed) {
3162 CLOGE("In-flight list too large for high speed configuration: %zu",
3163 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003164 }
3165}
3166
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003167void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003168 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003169 { // First return buffers cached in mInFlightMap
3170 Mutex::Autolock l(mInFlightLock);
3171 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3172 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3173 returnOutputBuffers(request.pendingOutputBuffers.array(),
3174 request.pendingOutputBuffers.size(), 0);
3175 }
3176 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003177 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003178 }
3179
3180 // Then return all inflight buffers not returned by HAL
3181 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3182 mInterface->getInflightBufferKeys(&inflightKeys);
3183
3184 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3185 for (auto& pair : inflightKeys) {
3186 int32_t frameNumber = pair.first;
3187 int32_t streamId = pair.second;
3188 buffer_handle_t* buffer;
3189 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3190 if (res != OK) {
3191 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3192 __FUNCTION__, frameNumber, streamId);
3193 continue;
3194 }
3195
3196 camera3_stream_buffer_t streamBuffer;
3197 streamBuffer.buffer = buffer;
3198 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3199 streamBuffer.acquire_fence = -1;
3200 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003201
3202 // First check if the buffer belongs to deleted stream
3203 bool streamDeleted = false;
3204 for (auto& stream : mDeletedStreams) {
3205 if (streamId == stream->getId()) {
3206 streamDeleted = true;
3207 // Return buffer to deleted stream
3208 camera3_stream* halStream = stream->asHalStream();
3209 streamBuffer.stream = halStream;
3210 switch (halStream->stream_type) {
3211 case CAMERA3_STREAM_OUTPUT:
3212 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
3213 if (res != OK) {
3214 ALOGE("%s: Can't return output buffer for frame %d to"
3215 " stream %d: %s (%d)", __FUNCTION__,
3216 frameNumber, streamId, strerror(-res), res);
3217 }
3218 break;
3219 case CAMERA3_STREAM_INPUT:
3220 res = stream->returnInputBuffer(streamBuffer);
3221 if (res != OK) {
3222 ALOGE("%s: Can't return input buffer for frame %d to"
3223 " stream %d: %s (%d)", __FUNCTION__,
3224 frameNumber, streamId, strerror(-res), res);
3225 }
3226 break;
3227 default: // Bi-direcitonal stream is deprecated
3228 ALOGE("%s: stream %d has unknown stream type %d",
3229 __FUNCTION__, streamId, halStream->stream_type);
3230 break;
3231 }
3232 break;
3233 }
3234 }
3235 if (streamDeleted) {
3236 continue;
3237 }
3238
3239 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003240 if (streamId == inputStreamId) {
3241 streamBuffer.stream = mInputStream->asHalStream();
3242 res = mInputStream->returnInputBuffer(streamBuffer);
3243 if (res != OK) {
3244 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003245 " stream %d: %s (%d)", __FUNCTION__,
3246 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003247 }
3248 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003249 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3250 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003251 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3252 continue;
3253 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003254 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003255 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3256 }
3257 }
3258}
3259
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003260void Camera3Device::insertResultLocked(CaptureResult *result,
3261 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003262 if (result == nullptr) return;
3263
Emilian Peev71c73a22017-03-21 16:35:51 +00003264 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3265 result->mMetadata.getAndLock());
3266 set_camera_metadata_vendor_id(meta, mVendorTagId);
3267 result->mMetadata.unlock(meta);
3268
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003269 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3270 (int32_t*)&frameNumber, 1) != OK) {
3271 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3272 return;
3273 }
3274
3275 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3276 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3277 return;
3278 }
3279
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003280 // Valid result, insert into queue
3281 List<CaptureResult>::iterator queuedResult =
3282 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3283 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3284 ", burstId = %" PRId32, __FUNCTION__,
3285 queuedResult->mResultExtras.requestId,
3286 queuedResult->mResultExtras.frameNumber,
3287 queuedResult->mResultExtras.burstId);
3288
3289 mResultSignal.signal();
3290}
3291
3292
3293void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003294 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003295 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003296 Mutex::Autolock l(mOutputLock);
3297
3298 CaptureResult captureResult;
3299 captureResult.mResultExtras = resultExtras;
3300 captureResult.mMetadata = partialResult;
3301
Shuzhen Wang268a1362018-10-16 16:32:59 -07003302 // Fix up result metadata for monochrome camera.
3303 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3304 if (res != OK) {
3305 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3306 return;
3307 }
3308
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003309 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003310}
3311
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003312
3313void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3314 CaptureResultExtras &resultExtras,
3315 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003316 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003317 bool reprocess,
3318 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003319 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003320 if (pendingMetadata.isEmpty())
3321 return;
3322
3323 Mutex::Autolock l(mOutputLock);
3324
3325 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003326 if (reprocess) {
3327 if (frameNumber < mNextReprocessResultFrameNumber) {
3328 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003329 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003330 frameNumber, mNextReprocessResultFrameNumber);
3331 return;
3332 }
3333 mNextReprocessResultFrameNumber = frameNumber + 1;
3334 } else {
3335 if (frameNumber < mNextResultFrameNumber) {
3336 SET_ERR("Out-of-order capture result metadata submitted! "
3337 "(got frame number %d, expecting %d)",
3338 frameNumber, mNextResultFrameNumber);
3339 return;
3340 }
3341 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003342 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003343
3344 CaptureResult captureResult;
3345 captureResult.mResultExtras = resultExtras;
3346 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003347 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003348
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003349 // Append any previous partials to form a complete result
3350 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3351 captureResult.mMetadata.append(collectedPartialResult);
3352 }
3353
3354 captureResult.mMetadata.sort();
3355
3356 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003357 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3358 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003359 SET_ERR("No timestamp provided by HAL for frame %d!",
3360 frameNumber);
3361 return;
3362 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003363 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3364 camera_metadata_entry timestamp =
3365 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3366 if (timestamp.count == 0) {
3367 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3368 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3369 return;
3370 }
3371 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003372
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003373 // Fix up some result metadata to account for HAL-level distortion correction
3374 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3375 if (res != OK) {
3376 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3377 frameNumber, strerror(res), res);
3378 return;
3379 }
Shuzhen Wang268a1362018-10-16 16:32:59 -07003380 // Fix up result metadata for monochrome camera.
3381 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3382 if (res != OK) {
3383 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3384 return;
3385 }
3386 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3387 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3388 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3389 physicalMetadata.mPhysicalCameraMetadata);
3390 if (res != OK) {
3391 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3392 return;
3393 }
3394 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003395
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003396 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3397 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3398
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003399 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003400}
3401
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003402/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003403 * Camera HAL device callback methods
3404 */
3405
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003406void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003407 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003408
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003409 status_t res;
3410
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003411 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003412 if (result->result == NULL && result->num_output_buffers == 0 &&
3413 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003414 SET_ERR("No result data provided by HAL for frame %d",
3415 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003416 return;
3417 }
Zhijun He204e3292014-07-14 17:09:23 -07003418
Zhijun He204e3292014-07-14 17:09:23 -07003419 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003420 result->result != NULL &&
3421 result->partial_result != 1) {
3422 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3423 " if partial result is not supported",
3424 frameNumber, result->partial_result);
3425 return;
3426 }
3427
3428 bool isPartialResult = false;
3429 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003430 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003431
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003432 // Get shutter timestamp and resultExtras from list of in-flight requests,
3433 // where it was added by the shutter notification for this frame. If the
3434 // shutter timestamp isn't received yet, append the output buffers to the
3435 // in-flight request and they will be returned when the shutter timestamp
3436 // arrives. Update the in-flight status and remove the in-flight entry if
3437 // all result data and shutter timestamp have been received.
3438 nsecs_t shutterTimestamp = 0;
3439
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003440 {
3441 Mutex::Autolock l(mInFlightLock);
3442 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3443 if (idx == NAME_NOT_FOUND) {
3444 SET_ERR("Unknown frame number for capture result: %d",
3445 frameNumber);
3446 return;
3447 }
3448 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003449 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3450 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003451 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003452 __FUNCTION__, request.resultExtras.requestId,
3453 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003454 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003455 // Always update the partial count to the latest one if it's not 0
3456 // (buffers only). When framework aggregates adjacent partial results
3457 // into one, the latest partial count will be used.
3458 if (result->partial_result != 0)
3459 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003460
3461 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003462 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003463 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3464 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3465 " the range of [1, %d] when metadata is included in the result",
3466 frameNumber, result->partial_result, mNumPartialResults);
3467 return;
3468 }
3469 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003470 if (isPartialResult && result->num_physcam_metadata) {
3471 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3472 " physical camera result", frameNumber);
3473 return;
3474 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003475 if (isPartialResult) {
3476 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003477 }
3478
Shuzhen Wang4a472662017-02-26 23:29:04 -08003479 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003480 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003481 sendPartialCaptureResult(result->result, request.resultExtras,
3482 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003483 }
3484 }
3485
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003486 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003487 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003488
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003489 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003490 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003491 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3492 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3493 request.physicalCameraIds.size(), result->num_physcam_metadata);
3494 return;
3495 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003496 if (request.haveResultMetadata) {
3497 SET_ERR("Called multiple times with metadata for frame %d",
3498 frameNumber);
3499 return;
3500 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003501 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3502 String8 physicalId(result->physcam_ids[i]);
3503 std::set<String8>::iterator cameraIdIter =
3504 request.physicalCameraIds.find(physicalId);
3505 if (cameraIdIter != request.physicalCameraIds.end()) {
3506 request.physicalCameraIds.erase(cameraIdIter);
3507 } else {
3508 SET_ERR("Total result for frame %d has already returned for camera %s",
3509 frameNumber, physicalId.c_str());
3510 return;
3511 }
3512 }
Zhijun He204e3292014-07-14 17:09:23 -07003513 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003514 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003515 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003516 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003517 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003518 request.haveResultMetadata = true;
3519 }
3520
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003521 uint32_t numBuffersReturned = result->num_output_buffers;
3522 if (result->input_buffer != NULL) {
3523 if (hasInputBufferInRequest) {
3524 numBuffersReturned += 1;
3525 } else {
3526 ALOGW("%s: Input buffer should be NULL if there is no input"
3527 " buffer sent in the request",
3528 __FUNCTION__);
3529 }
3530 }
3531 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003532 if (request.numBuffersLeft < 0) {
3533 SET_ERR("Too many buffers returned for frame %d",
3534 frameNumber);
3535 return;
3536 }
3537
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003538 camera_metadata_ro_entry_t entry;
3539 res = find_camera_metadata_ro_entry(result->result,
3540 ANDROID_SENSOR_TIMESTAMP, &entry);
3541 if (res == OK && entry.count == 1) {
3542 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003543 }
3544
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003545 // If shutter event isn't received yet, append the output buffers to
3546 // the in-flight request. Otherwise, return the output buffers to
3547 // streams.
3548 if (shutterTimestamp == 0) {
3549 request.pendingOutputBuffers.appendArray(result->output_buffers,
3550 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003551 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003552 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003553 returnOutputBuffers(result->output_buffers,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003554 result->num_output_buffers, shutterTimestamp, timestampIncreasing);
Igor Murashkind2c90692013-04-02 12:32:32 -07003555 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003556
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003557 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003558 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3559 CameraMetadata physicalMetadata;
3560 physicalMetadata.append(result->physcam_metadata[i]);
3561 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3562 physicalMetadata});
3563 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003564 if (shutterTimestamp == 0) {
3565 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003566 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003567 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003568 CameraMetadata metadata;
3569 metadata = result->result;
3570 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003571 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003572 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003573 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003574 }
3575
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003576 removeInFlightRequestIfReadyLocked(idx);
3577 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003578
Zhijun Hef0d962a2014-06-30 10:24:11 -07003579 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003580 if (hasInputBufferInRequest) {
3581 Camera3Stream *stream =
3582 Camera3Stream::cast(result->input_buffer->stream);
3583 res = stream->returnInputBuffer(*(result->input_buffer));
3584 // Note: stream may be deallocated at this point, if this buffer was the
3585 // last reference to it.
3586 if (res != OK) {
3587 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3588 " its stream:%s (%d)", __FUNCTION__,
3589 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003590 }
3591 } else {
3592 ALOGW("%s: Input buffer should be NULL if there is no input"
3593 " buffer sent in the request, skipping input buffer return.",
3594 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003595 }
3596 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003597}
3598
3599void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003600 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003601 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003602 {
3603 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003604 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003605 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003606
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003607 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003608 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003609 return;
3610 }
3611
3612 switch (msg->type) {
3613 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003614 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003615 break;
3616 }
3617 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003618 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003619 break;
3620 }
3621 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003622 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003623 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003624 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003625}
3626
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003627void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003628 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003629 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003630 // Map camera HAL error codes to ICameraDeviceCallback error codes
3631 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003632 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003633 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003634 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003635 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003636 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003637 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003638 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003639 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003640 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003641 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003642 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003643 };
3644
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003645 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003646 ((msg.error_code >= 0) &&
3647 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3648 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003649 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003650
3651 int streamId = 0;
3652 if (msg.error_stream != NULL) {
3653 Camera3Stream *stream =
3654 Camera3Stream::cast(msg.error_stream);
3655 streamId = stream->getId();
3656 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003657 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3658 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003659 streamId, msg.error_code);
3660
3661 CaptureResultExtras resultExtras;
3662 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003663 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003664 // SET_ERR calls notifyError
3665 SET_ERR("Camera HAL reported serious device error");
3666 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003667 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3668 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3669 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003670 {
3671 Mutex::Autolock l(mInFlightLock);
3672 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3673 if (idx >= 0) {
3674 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3675 r.requestStatus = msg.error_code;
3676 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003677 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3678 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3679 errorCode) {
3680 r.skipResultMetadata = true;
3681 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003682 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3683 errorCode) {
3684 // In case of missing result check whether the buffers
3685 // returned. If they returned, then remove inflight
3686 // request.
3687 removeInFlightRequestIfReadyLocked(idx);
3688 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003689 } else {
3690 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003691 ALOGE("Camera %s: %s: cannot find in-flight request on "
3692 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003693 resultExtras.frameNumber);
3694 }
3695 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003696 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003697 if (listener != NULL) {
3698 listener->notifyError(errorCode, resultExtras);
3699 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003700 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003701 }
3702 break;
3703 default:
3704 // SET_ERR calls notifyError
3705 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3706 break;
3707 }
3708}
3709
3710void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003711 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003712 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003713 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003714
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003715 // Set timestamp for the request in the in-flight tracking
3716 // and get the request ID to send upstream
3717 {
3718 Mutex::Autolock l(mInFlightLock);
3719 idx = mInFlightMap.indexOfKey(msg.frame_number);
3720 if (idx >= 0) {
3721 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003722
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003723 // Verify ordering of shutter notifications
3724 {
3725 Mutex::Autolock l(mOutputLock);
3726 // TODO: need to track errors for tighter bounds on expected frame number.
3727 if (r.hasInputBuffer) {
3728 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3729 SET_ERR("Shutter notification out-of-order. Expected "
3730 "notification for frame %d, got frame %d",
3731 mNextReprocessShutterFrameNumber, msg.frame_number);
3732 return;
3733 }
3734 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3735 } else {
3736 if (msg.frame_number < mNextShutterFrameNumber) {
3737 SET_ERR("Shutter notification out-of-order. Expected "
3738 "notification for frame %d, got frame %d",
3739 mNextShutterFrameNumber, msg.frame_number);
3740 return;
3741 }
3742 mNextShutterFrameNumber = msg.frame_number + 1;
3743 }
3744 }
3745
Shuzhen Wang4a472662017-02-26 23:29:04 -08003746 r.shutterTimestamp = msg.timestamp;
3747 if (r.hasCallback) {
3748 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003749 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003750 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003751 // Call listener, if any
3752 if (listener != NULL) {
3753 listener->notifyShutter(r.resultExtras, msg.timestamp);
3754 }
3755 // send pending result and buffers
3756 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3757 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003758 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003759 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003760 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003761 returnOutputBuffers(r.pendingOutputBuffers.array(),
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003762 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003763 r.pendingOutputBuffers.clear();
3764
3765 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003766 }
3767 }
3768 if (idx < 0) {
3769 SET_ERR("Shutter notification for non-existent frame number %d",
3770 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003771 }
3772}
3773
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003774CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003775 ALOGV("%s", __FUNCTION__);
3776
Igor Murashkin1e479c02013-09-06 16:55:14 -07003777 CameraMetadata retVal;
3778
3779 if (mRequestThread != NULL) {
3780 retVal = mRequestThread->getLatestRequest();
3781 }
3782
Igor Murashkin1e479c02013-09-06 16:55:14 -07003783 return retVal;
3784}
3785
Jianing Weicb0652e2014-03-12 18:29:36 -07003786
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003787void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3788 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3789 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3790}
3791
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003792/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003793 * HalInterface inner class methods
3794 */
3795
Yifan Hongf79b5542017-04-11 14:44:25 -07003796Camera3Device::HalInterface::HalInterface(
3797 sp<ICameraDeviceSession> &session,
3798 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003799 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003800 mRequestMetadataQueue(queue) {
3801 // Check with hardware service manager if we can downcast these interfaces
3802 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003803 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3804 if (castResult_3_5.isOk()) {
3805 mHidlSession_3_5 = castResult_3_5;
3806 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003807 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3808 if (castResult_3_4.isOk()) {
3809 mHidlSession_3_4 = castResult_3_4;
3810 }
3811 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3812 if (castResult_3_3.isOk()) {
3813 mHidlSession_3_3 = castResult_3_3;
3814 }
3815}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003816
Emilian Peev31abd0a2017-05-11 18:37:46 +01003817Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003818
3819Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003820 mHidlSession(other.mHidlSession),
3821 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003822
3823bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003824 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003825}
3826
3827void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003828 mHidlSession_3_4.clear();
3829 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003830 mHidlSession.clear();
3831}
3832
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003833bool Camera3Device::HalInterface::supportBatchRequest() {
3834 return mHidlSession != nullptr;
3835}
3836
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003837status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3838 camera3_request_template_t templateId,
3839 /*out*/ camera_metadata_t **requestTemplate) {
3840 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3841 if (!valid()) return INVALID_OPERATION;
3842 status_t res = OK;
3843
Emilian Peev31abd0a2017-05-11 18:37:46 +01003844 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003845
3846 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003847 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003848 status = s;
3849 if (status == common::V1_0::Status::OK) {
3850 const camera_metadata *r =
3851 reinterpret_cast<const camera_metadata_t*>(request.data());
3852 size_t expectedSize = request.size();
3853 int ret = validate_camera_metadata_structure(r, &expectedSize);
3854 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3855 *requestTemplate = clone_camera_metadata(r);
3856 if (*requestTemplate == nullptr) {
3857 ALOGE("%s: Unable to clone camera metadata received from HAL",
3858 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003859 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003860 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003861 } else {
3862 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3863 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003864 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003865 }
3866 };
3867 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003868 RequestTemplate id;
3869 switch (templateId) {
3870 case CAMERA3_TEMPLATE_PREVIEW:
3871 id = RequestTemplate::PREVIEW;
3872 break;
3873 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3874 id = RequestTemplate::STILL_CAPTURE;
3875 break;
3876 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3877 id = RequestTemplate::VIDEO_RECORD;
3878 break;
3879 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3880 id = RequestTemplate::VIDEO_SNAPSHOT;
3881 break;
3882 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3883 id = RequestTemplate::ZERO_SHUTTER_LAG;
3884 break;
3885 case CAMERA3_TEMPLATE_MANUAL:
3886 id = RequestTemplate::MANUAL;
3887 break;
3888 default:
3889 // Unknown template ID, or this HAL is too old to support it
3890 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003891 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003892 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003893
Emilian Peev31abd0a2017-05-11 18:37:46 +01003894 if (!err.isOk()) {
3895 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3896 res = DEAD_OBJECT;
3897 } else {
3898 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003899 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003900
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003901 return res;
3902}
3903
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003904status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003905 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003906 ATRACE_NAME("CameraHal::configureStreams");
3907 if (!valid()) return INVALID_OPERATION;
3908 status_t res = OK;
3909
Emilian Peev31abd0a2017-05-11 18:37:46 +01003910 // Convert stream config to HIDL
3911 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003912 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3913 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3914 requestedConfiguration3_2.streams.resize(config->num_streams);
3915 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003916 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003917 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3918 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003919 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003920
Emilian Peev31abd0a2017-05-11 18:37:46 +01003921 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3922 cam3stream->setBufferFreedListener(this);
3923 int streamId = cam3stream->getId();
3924 StreamType streamType;
3925 switch (src->stream_type) {
3926 case CAMERA3_STREAM_OUTPUT:
3927 streamType = StreamType::OUTPUT;
3928 break;
3929 case CAMERA3_STREAM_INPUT:
3930 streamType = StreamType::INPUT;
3931 break;
3932 default:
3933 ALOGE("%s: Stream %d: Unsupported stream type %d",
3934 __FUNCTION__, streamId, config->streams[i]->stream_type);
3935 return BAD_VALUE;
3936 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003937 dst3_2.id = streamId;
3938 dst3_2.streamType = streamType;
3939 dst3_2.width = src->width;
3940 dst3_2.height = src->height;
3941 dst3_2.format = mapToPixelFormat(src->format);
3942 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3943 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3944 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3945 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003946 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003947 if (src->physical_camera_id != nullptr) {
3948 dst3_4.physicalCameraId = src->physical_camera_id;
3949 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003950
3951 activeStreams.insert(streamId);
3952 // Create Buffer ID map if necessary
3953 if (mBufferIdMaps.count(streamId) == 0) {
3954 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3955 }
3956 }
3957 // remove BufferIdMap for deleted streams
3958 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3959 int streamId = it->first;
3960 bool active = activeStreams.count(streamId) > 0;
3961 if (!active) {
3962 it = mBufferIdMaps.erase(it);
3963 } else {
3964 ++it;
3965 }
3966 }
3967
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003968 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003969 res = mapToStreamConfigurationMode(
3970 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003971 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003972 if (res != OK) {
3973 return res;
3974 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003975 requestedConfiguration3_2.operationMode = operationMode;
3976 requestedConfiguration3_4.operationMode = operationMode;
3977 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003978 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3979 get_camera_metadata_size(sessionParams));
3980
Emilian Peev31abd0a2017-05-11 18:37:46 +01003981 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003982 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003983 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003984 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003985
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003986 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003987 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3988 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003989 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07003990 };
3991
3992 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
3993 (hardware::Return<void>& err) -> status_t {
3994 if (!err.isOk()) {
3995 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3996 return DEAD_OBJECT;
3997 }
3998 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3999 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4000 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4001 }
4002 return OK;
4003 };
4004
4005 // See if we have v3.4 or v3.3 HAL
4006 if (mHidlSession_3_5 != nullptr) {
4007 ALOGV("%s: v3.5 device found", __FUNCTION__);
4008 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4009 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4010 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4011 auto err = mHidlSession_3_5->configureStreams_3_5(
4012 requestedConfiguration3_5, configStream34Cb);
4013 res = postprocConfigStream34(err);
4014 if (res != OK) {
4015 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004016 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004017 } else if (mHidlSession_3_4 != nullptr) {
4018 // We do; use v3.4 for the call
4019 ALOGV("%s: v3.4 device found", __FUNCTION__);
4020 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
4021 auto err = mHidlSession_3_4->configureStreams_3_4(
4022 requestedConfiguration3_4, configStream34Cb);
4023 res = postprocConfigStream34(err);
4024 if (res != OK) {
4025 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004026 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004027 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004028 // We do; use v3.3 for the call
4029 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004030 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004031 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004032 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004033 finalConfiguration = halConfiguration;
4034 status = s;
4035 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004036 if (!err.isOk()) {
4037 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4038 return DEAD_OBJECT;
4039 }
4040 } else {
4041 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4042 ALOGV("%s: v3.2 device found", __FUNCTION__);
4043 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004044 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004045 [&status, &finalConfiguration_3_2]
4046 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4047 finalConfiguration_3_2 = halConfiguration;
4048 status = s;
4049 });
4050 if (!err.isOk()) {
4051 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4052 return DEAD_OBJECT;
4053 }
4054 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4055 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4056 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4057 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004058 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004059 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004060 }
4061
4062 if (status != common::V1_0::Status::OK ) {
4063 return CameraProviderManager::mapToStatusT(status);
4064 }
4065
4066 // And convert output stream configuration from HIDL
4067
4068 for (size_t i = 0; i < config->num_streams; i++) {
4069 camera3_stream_t *dst = config->streams[i];
4070 int streamId = Camera3Stream::cast(dst)->getId();
4071
4072 // Start scan at i, with the assumption that the stream order matches
4073 size_t realIdx = i;
4074 bool found = false;
4075 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004076 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004077 found = true;
4078 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004079 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004080 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4081 }
4082 if (!found) {
4083 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4084 __FUNCTION__, streamId);
4085 return INVALID_OPERATION;
4086 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004087 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004088
Emilian Peev710c1422017-08-30 11:19:38 +01004089 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4090 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004091 dstStream->setDataSpaceOverride(false);
4092 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4093 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4094
Emilian Peev31abd0a2017-05-11 18:37:46 +01004095 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4096 if (dst->format != overrideFormat) {
4097 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4098 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004099 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004100 if (dst->data_space != overrideDataSpace) {
4101 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4102 streamId, dst->format);
4103 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004104 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004105 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004106 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4107
Emilian Peev31abd0a2017-05-11 18:37:46 +01004108 // Override allowed with IMPLEMENTATION_DEFINED
4109 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004110 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004111 }
4112
Emilian Peev31abd0a2017-05-11 18:37:46 +01004113 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004114 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004115 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004116 __FUNCTION__, streamId);
4117 return INVALID_OPERATION;
4118 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004119 dstStream->setUsage(
4120 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004121 } else {
4122 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004123 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004124 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4125 __FUNCTION__, streamId);
4126 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004127 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004128 dstStream->setUsage(
4129 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004130 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004131 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004132 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004133
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004134 return res;
4135}
4136
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004137void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
4138 /*out*/device::V3_2::CaptureRequest* captureRequest,
4139 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004140 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004141 if (captureRequest == nullptr || handlesCreated == nullptr) {
4142 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4143 __FUNCTION__, captureRequest, handlesCreated);
4144 return;
4145 }
4146
4147 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004148
4149 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004150
4151 {
4152 std::lock_guard<std::mutex> lock(mInflightLock);
4153 if (request->input_buffer != nullptr) {
4154 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4155 buffer_handle_t buf = *(request->input_buffer->buffer);
4156 auto pair = getBufferId(buf, streamId);
4157 bool isNewBuffer = pair.first;
4158 uint64_t bufferId = pair.second;
4159 captureRequest->inputBuffer.streamId = streamId;
4160 captureRequest->inputBuffer.bufferId = bufferId;
4161 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4162 captureRequest->inputBuffer.status = BufferStatus::OK;
4163 native_handle_t *acquireFence = nullptr;
4164 if (request->input_buffer->acquire_fence != -1) {
4165 acquireFence = native_handle_create(1,0);
4166 acquireFence->data[0] = request->input_buffer->acquire_fence;
4167 handlesCreated->push_back(acquireFence);
4168 }
4169 captureRequest->inputBuffer.acquireFence = acquireFence;
4170 captureRequest->inputBuffer.releaseFence = nullptr;
4171
4172 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4173 request->input_buffer->buffer,
4174 request->input_buffer->acquire_fence);
4175 } else {
4176 captureRequest->inputBuffer.streamId = -1;
4177 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4178 }
4179
4180 captureRequest->outputBuffers.resize(request->num_output_buffers);
4181 for (size_t i = 0; i < request->num_output_buffers; i++) {
4182 const camera3_stream_buffer_t *src = request->output_buffers + i;
4183 StreamBuffer &dst = captureRequest->outputBuffers[i];
4184 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
4185 buffer_handle_t buf = *(src->buffer);
4186 auto pair = getBufferId(buf, streamId);
4187 bool isNewBuffer = pair.first;
4188 dst.streamId = streamId;
4189 dst.bufferId = pair.second;
4190 dst.buffer = isNewBuffer ? buf : nullptr;
4191 dst.status = BufferStatus::OK;
4192 native_handle_t *acquireFence = nullptr;
4193 if (src->acquire_fence != -1) {
4194 acquireFence = native_handle_create(1,0);
4195 acquireFence->data[0] = src->acquire_fence;
4196 handlesCreated->push_back(acquireFence);
4197 }
4198 dst.acquireFence = acquireFence;
4199 dst.releaseFence = nullptr;
4200
4201 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4202 src->buffer, src->acquire_fence);
4203 }
4204 }
4205}
4206
4207status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4208 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4209 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4210 if (!valid()) return INVALID_OPERATION;
4211
Emilian Peevaebbe412018-01-15 13:53:24 +00004212 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4213 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4214 if (castResult_3_4.isOk()) {
4215 hidlSession_3_4 = castResult_3_4;
4216 }
4217
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004218 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004219 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004220 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004221 if (hidlSession_3_4 != nullptr) {
4222 captureRequests_3_4.resize(batchSize);
4223 } else {
4224 captureRequests.resize(batchSize);
4225 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004226 std::vector<native_handle_t*> handlesCreated;
4227
4228 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004229 if (hidlSession_3_4 != nullptr) {
4230 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
4231 /*out*/&handlesCreated);
4232 } else {
4233 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
4234 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004235 }
4236
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004237 std::vector<device::V3_2::BufferCache> cachesToRemove;
4238 {
4239 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4240 for (auto& pair : mFreedBuffers) {
4241 // The stream might have been removed since onBufferFreed
4242 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4243 cachesToRemove.push_back({pair.first, pair.second});
4244 }
4245 }
4246 mFreedBuffers.clear();
4247 }
4248
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004249 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4250 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004251
4252 // Write metadata to FMQ.
4253 for (size_t i = 0; i < batchSize; i++) {
4254 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004255 device::V3_2::CaptureRequest* captureRequest;
4256 if (hidlSession_3_4 != nullptr) {
4257 captureRequest = &captureRequests_3_4[i].v3_2;
4258 } else {
4259 captureRequest = &captureRequests[i];
4260 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004261
4262 if (request->settings != nullptr) {
4263 size_t settingsSize = get_camera_metadata_size(request->settings);
4264 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4265 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4266 captureRequest->settings.resize(0);
4267 captureRequest->fmqSettingsSize = settingsSize;
4268 } else {
4269 if (mRequestMetadataQueue != nullptr) {
4270 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4271 }
4272 captureRequest->settings.setToExternal(
4273 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4274 get_camera_metadata_size(request->settings));
4275 captureRequest->fmqSettingsSize = 0u;
4276 }
4277 } else {
4278 // A null request settings maps to a size-0 CameraMetadata
4279 captureRequest->settings.resize(0);
4280 captureRequest->fmqSettingsSize = 0u;
4281 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004282
4283 if (hidlSession_3_4 != nullptr) {
4284 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4285 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004286 if (request->physcam_settings != nullptr) {
4287 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4288 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4289 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4290 settingsSize)) {
4291 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4292 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4293 settingsSize;
4294 } else {
4295 if (mRequestMetadataQueue != nullptr) {
4296 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4297 }
4298 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4299 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4300 request->physcam_settings[j])),
4301 get_camera_metadata_size(request->physcam_settings[j]));
4302 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004303 }
Emilian Peev00420d22018-02-05 21:33:13 +00004304 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004305 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004306 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004307 }
4308 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4309 request->physcam_id[j];
4310 }
4311 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004312 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004313
4314 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004315 auto resultCallback =
4316 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4317 status = s;
4318 *numRequestProcessed = n;
4319 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004320 if (hidlSession_3_4 != nullptr) {
4321 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004322 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004323 } else {
4324 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004325 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004326 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004327 if (!err.isOk()) {
4328 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4329 return DEAD_OBJECT;
4330 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004331 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4332 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4333 __FUNCTION__, *numRequestProcessed, batchSize);
4334 status = common::V1_0::Status::INTERNAL_ERROR;
4335 }
4336
4337 for (auto& handle : handlesCreated) {
4338 native_handle_delete(handle);
4339 }
4340 return CameraProviderManager::mapToStatusT(status);
4341}
4342
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004343status_t Camera3Device::HalInterface::processCaptureRequest(
4344 camera3_capture_request_t *request) {
4345 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004346 if (!valid()) return INVALID_OPERATION;
4347 status_t res = OK;
4348
Emilian Peev31abd0a2017-05-11 18:37:46 +01004349 uint32_t numRequestProcessed = 0;
4350 std::vector<camera3_capture_request_t*> requests(1);
4351 requests[0] = request;
4352 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4353
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004354 return res;
4355}
4356
4357status_t Camera3Device::HalInterface::flush() {
4358 ATRACE_NAME("CameraHal::flush");
4359 if (!valid()) return INVALID_OPERATION;
4360 status_t res = OK;
4361
Emilian Peev31abd0a2017-05-11 18:37:46 +01004362 auto err = mHidlSession->flush();
4363 if (!err.isOk()) {
4364 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4365 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004366 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004367 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004368 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004369
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004370 return res;
4371}
4372
Emilian Peev31abd0a2017-05-11 18:37:46 +01004373status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004374 ATRACE_NAME("CameraHal::dump");
4375 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004376
Emilian Peev31abd0a2017-05-11 18:37:46 +01004377 // Handled by CameraProviderManager::dump
4378
4379 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004380}
4381
4382status_t Camera3Device::HalInterface::close() {
4383 ATRACE_NAME("CameraHal::close()");
4384 if (!valid()) return INVALID_OPERATION;
4385 status_t res = OK;
4386
Emilian Peev31abd0a2017-05-11 18:37:46 +01004387 auto err = mHidlSession->close();
4388 // Interface will be dead shortly anyway, so don't log errors
4389 if (!err.isOk()) {
4390 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004391 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004392
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004393 return res;
4394}
4395
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004396void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4397 ATRACE_NAME("CameraHal::signalPipelineDrain");
4398 if (!valid() || mHidlSession_3_5 == nullptr) {
4399 ALOGE("%s called on invalid camera!", __FUNCTION__);
4400 return;
4401 }
4402
4403 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter);
4404 if (!err.isOk()) {
4405 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4406 return;
4407 }
4408}
4409
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004410void Camera3Device::HalInterface::getInflightBufferKeys(
4411 std::vector<std::pair<int32_t, int32_t>>* out) {
4412 std::lock_guard<std::mutex> lock(mInflightLock);
4413 out->clear();
4414 out->reserve(mInflightBufferMap.size());
4415 for (auto& pair : mInflightBufferMap) {
4416 uint64_t key = pair.first;
4417 int32_t streamId = key & 0xFFFFFFFF;
4418 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4419 out->push_back(std::make_pair(frameNumber, streamId));
4420 }
4421 return;
4422}
4423
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004424status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004425 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004426 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004427 auto pair = std::make_pair(buffer, acquireFence);
4428 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004429 return OK;
4430}
4431
4432status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004433 int32_t frameNumber, int32_t streamId,
4434 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004435 std::lock_guard<std::mutex> lock(mInflightLock);
4436
4437 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4438 auto it = mInflightBufferMap.find(key);
4439 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004440 auto pair = it->second;
4441 *buffer = pair.first;
4442 int acquireFence = pair.second;
4443 if (acquireFence > 0) {
4444 ::close(acquireFence);
4445 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004446 mInflightBufferMap.erase(it);
4447 return OK;
4448}
4449
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004450status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4451 uint64_t bufferId, buffer_handle_t* buf) {
4452 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4453 auto pair = mRequestedBuffers.insert({bufferId, buf});
4454 if (!pair.second) {
4455 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4456 __FUNCTION__, bufferId);
4457 return BAD_VALUE;
4458 }
4459 return OK;
4460}
4461
4462// Find and pop a buffer_handle_t based on bufferId
4463status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4464 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4465 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4466 auto it = mRequestedBuffers.find(bufferId);
4467 if (it == mRequestedBuffers.end()) {
4468 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4469 __FUNCTION__, bufferId);
4470 return BAD_VALUE;
4471 }
4472 *buffer = it->second;
4473 mRequestedBuffers.erase(it);
4474 return OK;
4475}
4476
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004477std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4478 const buffer_handle_t& buf, int streamId) {
4479 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4480
4481 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4482 auto it = bIdMap.find(buf);
4483 if (it == bIdMap.end()) {
4484 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004485 ALOGV("stream %d now have %zu buffer caches, buf %p",
4486 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004487 return std::make_pair(true, mNextBufferId - 1);
4488 } else {
4489 return std::make_pair(false, it->second);
4490 }
4491}
4492
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004493void Camera3Device::HalInterface::onBufferFreed(
4494 int streamId, const native_handle_t* handle) {
4495 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4496 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4497 auto mapIt = mBufferIdMaps.find(streamId);
4498 if (mapIt == mBufferIdMaps.end()) {
4499 // streamId might be from a deleted stream here
4500 ALOGI("%s: stream %d has been removed",
4501 __FUNCTION__, streamId);
4502 return;
4503 }
4504 BufferIdMap& bIdMap = mapIt->second;
4505 auto it = bIdMap.find(handle);
4506 if (it == bIdMap.end()) {
4507 ALOGW("%s: cannot find buffer %p in stream %d",
4508 __FUNCTION__, handle, streamId);
4509 return;
4510 } else {
4511 bufferId = it->second;
4512 bIdMap.erase(it);
4513 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4514 __FUNCTION__, streamId, bIdMap.size(), handle);
4515 }
4516 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4517}
4518
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004519/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004520 * RequestThread inner class methods
4521 */
4522
4523Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004524 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004525 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4526 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004527 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004528 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004529 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004530 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004531 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004532 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004533 mReconfigured(false),
4534 mDoPause(false),
4535 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004536 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004537 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004538 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004539 mCurrentAfTriggerId(0),
4540 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004541 mRepeatingLastFrameNumber(
4542 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004543 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004544 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004545 mRequestLatency(kRequestLatencyBinSize),
4546 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004547 mLatestSessionParams(sessionParamKeys.size()),
4548 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004549 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004550}
4551
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004552Camera3Device::RequestThread::~RequestThread() {}
4553
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004554void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004555 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004556 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004557 Mutex::Autolock l(mRequestLock);
4558 mListener = listener;
4559}
4560
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004561void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4562 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004563 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004564 Mutex::Autolock l(mRequestLock);
4565 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004566 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004567 // Prepare video stream for high speed recording.
4568 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004569 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004570}
4571
Jianing Wei90e59c92014-03-12 18:29:36 -07004572status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004573 List<sp<CaptureRequest> > &requests,
4574 /*out*/
4575 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004576 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004577 Mutex::Autolock l(mRequestLock);
4578 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4579 ++it) {
4580 mRequestQueue.push_back(*it);
4581 }
4582
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004583 if (lastFrameNumber != NULL) {
4584 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4585 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4586 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4587 *lastFrameNumber);
4588 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004589
Jianing Wei90e59c92014-03-12 18:29:36 -07004590 unpauseForNewRequests();
4591
4592 return OK;
4593}
4594
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004595
4596status_t Camera3Device::RequestThread::queueTrigger(
4597 RequestTrigger trigger[],
4598 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004599 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004600 Mutex::Autolock l(mTriggerMutex);
4601 status_t ret;
4602
4603 for (size_t i = 0; i < count; ++i) {
4604 ret = queueTriggerLocked(trigger[i]);
4605
4606 if (ret != OK) {
4607 return ret;
4608 }
4609 }
4610
4611 return OK;
4612}
4613
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004614const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4615 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004616 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004617 if (d != nullptr) return d->mId;
4618 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004619}
4620
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004621status_t Camera3Device::RequestThread::queueTriggerLocked(
4622 RequestTrigger trigger) {
4623
4624 uint32_t tag = trigger.metadataTag;
4625 ssize_t index = mTriggerMap.indexOfKey(tag);
4626
4627 switch (trigger.getTagType()) {
4628 case TYPE_BYTE:
4629 // fall-through
4630 case TYPE_INT32:
4631 break;
4632 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004633 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4634 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004635 return INVALID_OPERATION;
4636 }
4637
4638 /**
4639 * Collect only the latest trigger, since we only have 1 field
4640 * in the request settings per trigger tag, and can't send more than 1
4641 * trigger per request.
4642 */
4643 if (index != NAME_NOT_FOUND) {
4644 mTriggerMap.editValueAt(index) = trigger;
4645 } else {
4646 mTriggerMap.add(tag, trigger);
4647 }
4648
4649 return OK;
4650}
4651
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004652status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004653 const RequestList &requests,
4654 /*out*/
4655 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004656 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004657 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004658 if (lastFrameNumber != NULL) {
4659 *lastFrameNumber = mRepeatingLastFrameNumber;
4660 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004661 mRepeatingRequests.clear();
4662 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4663 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004664
4665 unpauseForNewRequests();
4666
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004667 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004668 return OK;
4669}
4670
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004671bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004672 if (mRepeatingRequests.empty()) {
4673 return false;
4674 }
4675 int32_t requestId = requestIn->mResultExtras.requestId;
4676 const RequestList &repeatRequests = mRepeatingRequests;
4677 // All repeating requests are guaranteed to have same id so only check first quest
4678 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4679 return (firstRequest->mResultExtras.requestId == requestId);
4680}
4681
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004682status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004683 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004684 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004685 return clearRepeatingRequestsLocked(lastFrameNumber);
4686
4687}
4688
4689status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004690 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004691 if (lastFrameNumber != NULL) {
4692 *lastFrameNumber = mRepeatingLastFrameNumber;
4693 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004694 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004695 return OK;
4696}
4697
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004698status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004699 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004700 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004701 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004702 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004703
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004704 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004705
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004706 // Send errors for all requests pending in the request queue, including
4707 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004708 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004709 if (listener != NULL) {
4710 for (RequestList::iterator it = mRequestQueue.begin();
4711 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004712 // Abort the input buffers for reprocess requests.
4713 if ((*it)->mInputStream != NULL) {
4714 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004715 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4716 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004717 if (res != OK) {
4718 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4719 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4720 } else {
4721 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4722 if (res != OK) {
4723 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4724 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4725 }
4726 }
4727 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004728 // Set the frame number this request would have had, if it
4729 // had been submitted; this frame number will not be reused.
4730 // The requestId and burstId fields were set when the request was
4731 // submitted originally (in convertMetadataListToRequestListLocked)
4732 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004733 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004734 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004735 }
4736 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004737 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004738
4739 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004740 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004741 if (lastFrameNumber != NULL) {
4742 *lastFrameNumber = mRepeatingLastFrameNumber;
4743 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004744 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004745 return OK;
4746}
4747
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004748status_t Camera3Device::RequestThread::flush() {
4749 ATRACE_CALL();
4750 Mutex::Autolock l(mFlushLock);
4751
Emilian Peev08dd2452017-04-06 16:55:14 +01004752 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004753}
4754
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004755void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004756 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004757 Mutex::Autolock l(mPauseLock);
4758 mDoPause = paused;
4759 mDoPauseSignal.signal();
4760}
4761
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004762status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4763 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004764 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004765 Mutex::Autolock l(mLatestRequestMutex);
4766 status_t res;
4767 while (mLatestRequestId != requestId) {
4768 nsecs_t startTime = systemTime();
4769
4770 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4771 if (res != OK) return res;
4772
4773 timeout -= (systemTime() - startTime);
4774 }
4775
4776 return OK;
4777}
4778
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004779void Camera3Device::RequestThread::requestExit() {
4780 // Call parent to set up shutdown
4781 Thread::requestExit();
4782 // The exit from any possible waits
4783 mDoPauseSignal.signal();
4784 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004785
4786 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4787 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004788}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004789
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004790void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004791 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004792 bool surfaceAbandoned = false;
4793 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004794 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004795 {
4796 Mutex::Autolock l(mRequestLock);
4797 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4798 // repeating requests.
4799 for (const auto& request : mRepeatingRequests) {
4800 for (const auto& s : request->mOutputStreams) {
4801 if (s->isAbandoned()) {
4802 surfaceAbandoned = true;
4803 clearRepeatingRequestsLocked(&lastFrameNumber);
4804 break;
4805 }
4806 }
4807 if (surfaceAbandoned) {
4808 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004809 }
4810 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004811 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004812 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004813
4814 if (listener != NULL && surfaceAbandoned) {
4815 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004816 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004817}
4818
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004819bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004820 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004821 status_t res;
4822 size_t batchSize = mNextRequests.size();
4823 std::vector<camera3_capture_request_t*> requests(batchSize);
4824 uint32_t numRequestProcessed = 0;
4825 for (size_t i = 0; i < batchSize; i++) {
4826 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004827 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004828 }
4829
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004830 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4831
4832 bool triggerRemoveFailed = false;
4833 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4834 for (size_t i = 0; i < numRequestProcessed; i++) {
4835 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4836 nextRequest.submitted = true;
4837
4838
4839 // Update the latest request sent to HAL
4840 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4841 Mutex::Autolock al(mLatestRequestMutex);
4842
4843 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4844 mLatestRequest.acquire(cloned);
4845
4846 sp<Camera3Device> parent = mParent.promote();
4847 if (parent != NULL) {
4848 parent->monitorMetadata(TagMonitor::REQUEST,
4849 nextRequest.halRequest.frame_number,
4850 0, mLatestRequest);
4851 }
4852 }
4853
4854 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004855 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4856 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004857 }
4858
Emilian Peevaebbe412018-01-15 13:53:24 +00004859 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4860
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004861 if (!triggerRemoveFailed) {
4862 // Remove any previously queued triggers (after unlock)
4863 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4864 if (removeTriggerRes != OK) {
4865 triggerRemoveFailed = true;
4866 triggerFailedRequest = nextRequest;
4867 }
4868 }
4869 }
4870
4871 if (triggerRemoveFailed) {
4872 SET_ERR("RequestThread: Unable to remove triggers "
4873 "(capture request %d, HAL device: %s (%d)",
4874 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4875 cleanUpFailedRequests(/*sendRequestError*/ false);
4876 return false;
4877 }
4878
4879 if (res != OK) {
4880 // Should only get a failure here for malformed requests or device-level
4881 // errors, so consider all errors fatal. Bad metadata failures should
4882 // come through notify.
4883 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4884 mNextRequests[numRequestProcessed].halRequest.frame_number,
4885 strerror(-res), res);
4886 cleanUpFailedRequests(/*sendRequestError*/ false);
4887 return false;
4888 }
4889 return true;
4890}
4891
4892bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4893 status_t res;
4894
4895 for (auto& nextRequest : mNextRequests) {
4896 // Submit request and block until ready for next one
4897 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4898 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4899
4900 if (res != OK) {
4901 // Should only get a failure here for malformed requests or device-level
4902 // errors, so consider all errors fatal. Bad metadata failures should
4903 // come through notify.
4904 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4905 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4906 res);
4907 cleanUpFailedRequests(/*sendRequestError*/ false);
4908 return false;
4909 }
4910
4911 // Mark that the request has be submitted successfully.
4912 nextRequest.submitted = true;
4913
4914 // Update the latest request sent to HAL
4915 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4916 Mutex::Autolock al(mLatestRequestMutex);
4917
4918 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4919 mLatestRequest.acquire(cloned);
4920
4921 sp<Camera3Device> parent = mParent.promote();
4922 if (parent != NULL) {
4923 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4924 0, mLatestRequest);
4925 }
4926 }
4927
4928 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004929 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4930 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004931 }
4932
Emilian Peevaebbe412018-01-15 13:53:24 +00004933 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4934
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004935 // Remove any previously queued triggers (after unlock)
4936 res = removeTriggers(mPrevRequest);
4937 if (res != OK) {
4938 SET_ERR("RequestThread: Unable to remove triggers "
4939 "(capture request %d, HAL device: %s (%d)",
4940 nextRequest.halRequest.frame_number, strerror(-res), res);
4941 cleanUpFailedRequests(/*sendRequestError*/ false);
4942 return false;
4943 }
4944 }
4945 return true;
4946}
4947
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004948nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4949 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4950 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4951 find_camera_metadata_ro_entry(request,
4952 ANDROID_CONTROL_AE_MODE,
4953 &e);
4954 if (e.count == 0) return maxExpectedDuration;
4955
4956 switch (e.data.u8[0]) {
4957 case ANDROID_CONTROL_AE_MODE_OFF:
4958 find_camera_metadata_ro_entry(request,
4959 ANDROID_SENSOR_EXPOSURE_TIME,
4960 &e);
4961 if (e.count > 0) {
4962 maxExpectedDuration = e.data.i64[0];
4963 }
4964 find_camera_metadata_ro_entry(request,
4965 ANDROID_SENSOR_FRAME_DURATION,
4966 &e);
4967 if (e.count > 0) {
4968 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4969 }
4970 break;
4971 default:
4972 find_camera_metadata_ro_entry(request,
4973 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4974 &e);
4975 if (e.count > 1) {
4976 maxExpectedDuration = 1e9 / e.data.u8[0];
4977 }
4978 break;
4979 }
4980
4981 return maxExpectedDuration;
4982}
4983
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004984bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4985 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4986 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4987 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4988 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4989 return true;
4990 }
4991
4992 return false;
4993}
4994
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004995bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4996 ATRACE_CALL();
4997 bool updatesDetected = false;
4998
4999 for (auto tag : mSessionParamKeys) {
5000 camera_metadata_ro_entry entry = settings.find(tag);
5001 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
5002
5003 if (entry.count > 0) {
5004 bool isDifferent = false;
5005 if (lastEntry.count > 0) {
5006 // Have a last value, compare to see if changed
5007 if (lastEntry.type == entry.type &&
5008 lastEntry.count == entry.count) {
5009 // Same type and count, compare values
5010 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5011 size_t entryBytes = bytesPerValue * lastEntry.count;
5012 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5013 if (cmp != 0) {
5014 isDifferent = true;
5015 }
5016 } else {
5017 // Count or type has changed
5018 isDifferent = true;
5019 }
5020 } else {
5021 // No last entry, so always consider to be different
5022 isDifferent = true;
5023 }
5024
5025 if (isDifferent) {
5026 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005027 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5028 updatesDetected = true;
5029 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005030 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005031 }
5032 } else if (lastEntry.count > 0) {
5033 // Value has been removed
5034 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
5035 mLatestSessionParams.erase(tag);
5036 updatesDetected = true;
5037 }
5038 }
5039
5040 return updatesDetected;
5041}
5042
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005043bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005044 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005045 status_t res;
5046
5047 // Handle paused state.
5048 if (waitIfPaused()) {
5049 return true;
5050 }
5051
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005052 // Wait for the next batch of requests.
5053 waitForNextRequestBatch();
5054 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005055 return true;
5056 }
5057
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005058 // Get the latest request ID, if any
5059 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005060 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005061 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005062 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005063 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005064 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005065 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5066 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005067 }
5068
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005069 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5070 // or a single request from streaming or burst. In either case the first element
5071 // should contain the latest camera settings that we need to check for any session
5072 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005073 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005074 res = OK;
5075
5076 //Input stream buffers are already acquired at this point so an input stream
5077 //will not be able to move to idle state unless we force it.
5078 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5079 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5080 if (res != OK) {
5081 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5082 cleanUpFailedRequests(/*sendRequestError*/ false);
5083 return false;
5084 }
5085 }
5086
5087 if (res == OK) {
5088 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5089 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005090 sp<Camera3Device> parent = mParent.promote();
5091 if (parent != nullptr) {
5092 parent->pauseStateNotify(true);
5093 }
5094
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005095 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5096
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005097 if (parent != nullptr) {
5098 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5099 }
5100
5101 statusTracker->markComponentActive(mStatusId);
5102 setPaused(false);
5103 }
5104
5105 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5106 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5107 if (res != OK) {
5108 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5109 cleanUpFailedRequests(/*sendRequestError*/ false);
5110 return false;
5111 }
5112 }
5113 }
5114 }
5115
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005116 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005117 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005118 if (res == TIMED_OUT) {
5119 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005120 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005121 // Check if any stream is abandoned.
5122 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005123 return true;
5124 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005125 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005126 return false;
5127 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005128
Zhijun Hecc27e112013-10-03 16:12:43 -07005129 // Inform waitUntilRequestProcessed thread of a new request ID
5130 {
5131 Mutex::Autolock al(mLatestRequestMutex);
5132
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005133 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005134 mLatestRequestSignal.signal();
5135 }
5136
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005137 // Submit a batch of requests to HAL.
5138 // Use flush lock only when submitting multilple requests in a batch.
5139 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5140 // which may take a long time to finish so synchronizing flush() and
5141 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5142 // For now, only synchronize for high speed recording and we should figure something out for
5143 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005144 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005145
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005146 if (useFlushLock) {
5147 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005148 }
5149
Zhijun Hef0645c12016-08-02 00:58:11 -07005150 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005151 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005152
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005153 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005154 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005155 if (mInterface->supportBatchRequest()) {
5156 submitRequestSuccess = sendRequestsBatch();
5157 } else {
5158 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005159 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005160 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5161 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005162
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005163 if (submitRequestSuccess) {
5164 sp<Camera3Device> parent = mParent.promote();
5165 if (parent != nullptr) {
5166 parent->mRequestBufferSM.onRequestSubmitted();
5167 }
5168 }
5169
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005170 if (useFlushLock) {
5171 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005172 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005173
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005174 // Unset as current request
5175 {
5176 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005177 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005178 }
5179
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005180 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005181}
5182
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005183status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005184 ATRACE_CALL();
5185
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005186 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005187 for (size_t i = 0; i < mNextRequests.size(); i++) {
5188 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005189 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5190 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5191 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5192
5193 // Prepare a request to HAL
5194 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5195
5196 // Insert any queued triggers (before metadata is locked)
5197 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005198 if (res < 0) {
5199 SET_ERR("RequestThread: Unable to insert triggers "
5200 "(capture request %d, HAL device: %s (%d)",
5201 halRequest->frame_number, strerror(-res), res);
5202 return INVALID_OPERATION;
5203 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005204
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005205 int triggerCount = res;
5206 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5207 mPrevTriggers = triggerCount;
5208
5209 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005210 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5211 // Request settings are all the same within one batch, so only treat the first
5212 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005213 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005214 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005215 /**
5216 * HAL workaround:
5217 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5218 */
5219 res = addDummyTriggerIds(captureRequest);
5220 if (res != OK) {
5221 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5222 "(capture request %d, HAL device: %s (%d)",
5223 halRequest->frame_number, strerror(-res), res);
5224 return INVALID_OPERATION;
5225 }
5226
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005227 {
5228 // Correct metadata regions for distortion correction if enabled
5229 sp<Camera3Device> parent = mParent.promote();
5230 if (parent != nullptr) {
5231 res = parent->mDistortionMapper.correctCaptureRequest(
5232 &(captureRequest->mSettingsList.begin()->metadata));
5233 if (res != OK) {
5234 SET_ERR("RequestThread: Unable to correct capture requests "
5235 "for lens distortion for request %d: %s (%d)",
5236 halRequest->frame_number, strerror(-res), res);
5237 return INVALID_OPERATION;
5238 }
5239 }
5240 }
5241
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005242 /**
5243 * The request should be presorted so accesses in HAL
5244 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5245 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005246 captureRequest->mSettingsList.begin()->metadata.sort();
5247 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005248 mPrevRequest = captureRequest;
5249 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5250
5251 IF_ALOGV() {
5252 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5253 find_camera_metadata_ro_entry(
5254 halRequest->settings,
5255 ANDROID_CONTROL_AF_TRIGGER,
5256 &e
5257 );
5258 if (e.count > 0) {
5259 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5260 __FUNCTION__,
5261 halRequest->frame_number,
5262 e.data.u8[0]);
5263 }
5264 }
5265 } else {
5266 // leave request.settings NULL to indicate 'reuse latest given'
5267 ALOGVV("%s: Request settings are REUSED",
5268 __FUNCTION__);
5269 }
5270
Emilian Peevaebbe412018-01-15 13:53:24 +00005271 if (captureRequest->mSettingsList.size() > 1) {
5272 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5273 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005274 if (newRequest) {
5275 halRequest->physcam_settings =
5276 new const camera_metadata* [halRequest->num_physcam_settings];
5277 } else {
5278 halRequest->physcam_settings = nullptr;
5279 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005280 auto it = ++captureRequest->mSettingsList.begin();
5281 size_t i = 0;
5282 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5283 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005284 if (newRequest) {
5285 it->metadata.sort();
5286 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5287 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005288 }
5289 }
5290
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005291 uint32_t totalNumBuffers = 0;
5292
5293 // Fill in buffers
5294 if (captureRequest->mInputStream != NULL) {
5295 halRequest->input_buffer = &captureRequest->mInputBuffer;
5296 totalNumBuffers += 1;
5297 } else {
5298 halRequest->input_buffer = NULL;
5299 }
5300
5301 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5302 captureRequest->mOutputStreams.size());
5303 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005304 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005305
5306 sp<Camera3Device> parent = mParent.promote();
5307 if (parent == NULL) {
5308 // Should not happen, and nowhere to send errors to, so just log it
5309 CLOGE("RequestThread: Parent is gone");
5310 return INVALID_OPERATION;
5311 }
5312 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5313
Shuzhen Wang4a472662017-02-26 23:29:04 -08005314 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
5315 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005316
5317 // Prepare video buffers for high speed recording on the first video request.
5318 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5319 // Only try to prepare video stream on the first video request.
5320 mPrepareVideoStream = false;
5321
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005322 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5323 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005324 while (res == NOT_ENOUGH_DATA) {
5325 res = outputStream->prepareNextBuffer();
5326 }
5327 if (res != OK) {
5328 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5329 __FUNCTION__, strerror(-res), res);
5330 outputStream->cancelPrepare();
5331 }
5332 }
5333
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005334 if (mUseHalBufManager) {
5335 // HAL will request buffer through requestStreamBuffer API
5336 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5337 buffer.stream = outputStream->asHalStream();
5338 buffer.buffer = nullptr;
5339 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5340 buffer.acquire_fence = -1;
5341 buffer.release_fence = -1;
5342 } else {
5343 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5344 waitDuration,
5345 captureRequest->mOutputSurfaces[outputStream->getId()]);
5346 if (res != OK) {
5347 // Can't get output buffer from gralloc queue - this could be due to
5348 // abandoned queue or other consumer misbehavior, so not a fatal
5349 // error
5350 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5351 " %s (%d)", strerror(-res), res);
5352
5353 return TIMED_OUT;
5354 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005355 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005356
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005357 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5358
5359 if (!physicalCameraId.isEmpty()) {
5360 // Physical stream isn't supported for input request.
5361 if (halRequest->input_buffer) {
5362 CLOGE("Physical stream is not supported for input request");
5363 return INVALID_OPERATION;
5364 }
5365 requestedPhysicalCameras.insert(physicalCameraId);
5366 }
5367 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005368 }
5369 totalNumBuffers += halRequest->num_output_buffers;
5370
5371 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005372 // If this request list is for constrained high speed recording (not
5373 // preview), and the current request is not the last one in the batch,
5374 // do not send callback to the app.
5375 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005376 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005377 hasCallback = false;
5378 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005379 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005380 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005381 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5382 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5383 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5384 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5385 isStillCapture = true;
5386 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5387 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005388
5389 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5390 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5391 isZslCapture = true;
5392 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005393 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005394 res = parent->registerInFlight(halRequest->frame_number,
5395 totalNumBuffers, captureRequest->mResultExtras,
5396 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005397 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005398 calculateMaxExpectedDuration(halRequest->settings),
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005399 requestedPhysicalCameras, isStillCapture, isZslCapture);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005400 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5401 ", burstId = %" PRId32 ".",
5402 __FUNCTION__,
5403 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5404 captureRequest->mResultExtras.burstId);
5405 if (res != OK) {
5406 SET_ERR("RequestThread: Unable to register new in-flight request:"
5407 " %s (%d)", strerror(-res), res);
5408 return INVALID_OPERATION;
5409 }
5410 }
5411
5412 return OK;
5413}
5414
Igor Murashkin1e479c02013-09-06 16:55:14 -07005415CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005416 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005417 Mutex::Autolock al(mLatestRequestMutex);
5418
5419 ALOGV("RequestThread::%s", __FUNCTION__);
5420
5421 return mLatestRequest;
5422}
5423
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005424bool Camera3Device::RequestThread::isStreamPending(
5425 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005426 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005427 Mutex::Autolock l(mRequestLock);
5428
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005429 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005430 if (!nextRequest.submitted) {
5431 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5432 if (stream == s) return true;
5433 }
5434 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005435 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005436 }
5437
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005438 for (const auto& request : mRequestQueue) {
5439 for (const auto& s : request->mOutputStreams) {
5440 if (stream == s) return true;
5441 }
5442 if (stream == request->mInputStream) return true;
5443 }
5444
5445 for (const auto& request : mRepeatingRequests) {
5446 for (const auto& s : request->mOutputStreams) {
5447 if (stream == s) return true;
5448 }
5449 if (stream == request->mInputStream) return true;
5450 }
5451
5452 return false;
5453}
Jianing Weicb0652e2014-03-12 18:29:36 -07005454
Emilian Peev40ead602017-09-26 15:46:36 +01005455bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5456 ATRACE_CALL();
5457 Mutex::Autolock l(mRequestLock);
5458
5459 for (const auto& nextRequest : mNextRequests) {
5460 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5461 if (s.first == streamId) {
5462 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5463 if (it != s.second.end()) {
5464 return true;
5465 }
5466 }
5467 }
5468 }
5469
5470 for (const auto& request : mRequestQueue) {
5471 for (const auto& s : request->mOutputSurfaces) {
5472 if (s.first == streamId) {
5473 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5474 if (it != s.second.end()) {
5475 return true;
5476 }
5477 }
5478 }
5479 }
5480
5481 for (const auto& request : mRepeatingRequests) {
5482 for (const auto& s : request->mOutputSurfaces) {
5483 if (s.first == streamId) {
5484 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5485 if (it != s.second.end()) {
5486 return true;
5487 }
5488 }
5489 }
5490 }
5491
5492 return false;
5493}
5494
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005495void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5496 if (!mUseHalBufManager) {
5497 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5498 return;
5499 }
5500
5501 Mutex::Autolock pl(mPauseLock);
5502 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005503 mInterface->signalPipelineDrain(streamIds);
5504 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005505 }
5506 // If request thread is still busy, wait until paused then notify HAL
5507 mNotifyPipelineDrain = true;
5508 mStreamIdsToBeDrained = streamIds;
5509}
5510
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005511nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005512 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005513 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005514 return mExpectedInflightDuration > kMinInflightDuration ?
5515 mExpectedInflightDuration : kMinInflightDuration;
5516}
5517
Emilian Peevaebbe412018-01-15 13:53:24 +00005518void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5519 camera3_capture_request_t *halRequest) {
5520 if ((request == nullptr) || (halRequest == nullptr)) {
5521 ALOGE("%s: Invalid request!", __FUNCTION__);
5522 return;
5523 }
5524
5525 if (halRequest->num_physcam_settings > 0) {
5526 if (halRequest->physcam_id != nullptr) {
5527 delete [] halRequest->physcam_id;
5528 halRequest->physcam_id = nullptr;
5529 }
5530 if (halRequest->physcam_settings != nullptr) {
5531 auto it = ++(request->mSettingsList.begin());
5532 size_t i = 0;
5533 for (; it != request->mSettingsList.end(); it++, i++) {
5534 it->metadata.unlock(halRequest->physcam_settings[i]);
5535 }
5536 delete [] halRequest->physcam_settings;
5537 halRequest->physcam_settings = nullptr;
5538 }
5539 }
5540}
5541
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005542void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5543 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005544 return;
5545 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005546
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005547 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005548 // Skip the ones that have been submitted successfully.
5549 if (nextRequest.submitted) {
5550 continue;
5551 }
5552
5553 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5554 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5555 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5556
5557 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005558 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005559 }
5560
Emilian Peevaebbe412018-01-15 13:53:24 +00005561 cleanupPhysicalSettings(captureRequest, halRequest);
5562
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005563 if (captureRequest->mInputStream != NULL) {
5564 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5565 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5566 }
5567
5568 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005569 //Buffers that failed processing could still have
5570 //valid acquire fence.
5571 int acquireFence = (*outputBuffers)[i].acquire_fence;
5572 if (0 <= acquireFence) {
5573 close(acquireFence);
5574 outputBuffers->editItemAt(i).acquire_fence = -1;
5575 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005576 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5577 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5578 }
5579
5580 if (sendRequestError) {
5581 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005582 sp<NotificationListener> listener = mListener.promote();
5583 if (listener != NULL) {
5584 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005585 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005586 captureRequest->mResultExtras);
5587 }
5588 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005589
5590 // Remove yet-to-be submitted inflight request from inflightMap
5591 {
5592 sp<Camera3Device> parent = mParent.promote();
5593 if (parent != NULL) {
5594 Mutex::Autolock l(parent->mInFlightLock);
5595 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5596 if (idx >= 0) {
5597 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5598 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5599 parent->removeInFlightMapEntryLocked(idx);
5600 }
5601 }
5602 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005603 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005604
5605 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005606 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005607}
5608
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005609void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005610 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005611 // Optimized a bit for the simple steady-state case (single repeating
5612 // request), to avoid putting that request in the queue temporarily.
5613 Mutex::Autolock l(mRequestLock);
5614
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005615 assert(mNextRequests.empty());
5616
5617 NextRequest nextRequest;
5618 nextRequest.captureRequest = waitForNextRequestLocked();
5619 if (nextRequest.captureRequest == nullptr) {
5620 return;
5621 }
5622
5623 nextRequest.halRequest = camera3_capture_request_t();
5624 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005625 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005626
5627 // Wait for additional requests
5628 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5629
5630 for (size_t i = 1; i < batchSize; i++) {
5631 NextRequest additionalRequest;
5632 additionalRequest.captureRequest = waitForNextRequestLocked();
5633 if (additionalRequest.captureRequest == nullptr) {
5634 break;
5635 }
5636
5637 additionalRequest.halRequest = camera3_capture_request_t();
5638 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005639 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005640 }
5641
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005642 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005643 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005644 mNextRequests.size(), batchSize);
5645 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005646 }
5647
5648 return;
5649}
5650
5651sp<Camera3Device::CaptureRequest>
5652 Camera3Device::RequestThread::waitForNextRequestLocked() {
5653 status_t res;
5654 sp<CaptureRequest> nextRequest;
5655
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005656 while (mRequestQueue.empty()) {
5657 if (!mRepeatingRequests.empty()) {
5658 // Always atomically enqueue all requests in a repeating request
5659 // list. Guarantees a complete in-sequence set of captures to
5660 // application.
5661 const RequestList &requests = mRepeatingRequests;
5662 RequestList::const_iterator firstRequest =
5663 requests.begin();
5664 nextRequest = *firstRequest;
5665 mRequestQueue.insert(mRequestQueue.end(),
5666 ++firstRequest,
5667 requests.end());
5668 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005669
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005670 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005671
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005672 break;
5673 }
5674
5675 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5676
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005677 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5678 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005679 Mutex::Autolock pl(mPauseLock);
5680 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005681 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005682 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005683 // Let the tracker know
5684 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5685 if (statusTracker != 0) {
5686 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5687 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005688 if (mNotifyPipelineDrain) {
5689 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5690 mNotifyPipelineDrain = false;
5691 mStreamIdsToBeDrained.clear();
5692 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005693 sp<Camera3Device> parent = mParent.promote();
5694 if (parent != nullptr) {
5695 parent->mRequestBufferSM.onRequestThreadPaused();
5696 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005697 }
5698 // Stop waiting for now and let thread management happen
5699 return NULL;
5700 }
5701 }
5702
5703 if (nextRequest == NULL) {
5704 // Don't have a repeating request already in hand, so queue
5705 // must have an entry now.
5706 RequestList::iterator firstRequest =
5707 mRequestQueue.begin();
5708 nextRequest = *firstRequest;
5709 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005710 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5711 sp<NotificationListener> listener = mListener.promote();
5712 if (listener != NULL) {
5713 listener->notifyRequestQueueEmpty();
5714 }
5715 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005716 }
5717
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005718 // In case we've been unpaused by setPaused clearing mDoPause, need to
5719 // update internal pause state (capture/setRepeatingRequest unpause
5720 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005721 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005722 if (mPaused) {
5723 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5724 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5725 if (statusTracker != 0) {
5726 statusTracker->markComponentActive(mStatusId);
5727 }
5728 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005729 mPaused = false;
5730
5731 // Check if we've reconfigured since last time, and reset the preview
5732 // request if so. Can't use 'NULL request == repeat' across configure calls.
5733 if (mReconfigured) {
5734 mPrevRequest.clear();
5735 mReconfigured = false;
5736 }
5737
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005738 if (nextRequest != NULL) {
5739 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005740 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5741 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005742
5743 // Since RequestThread::clear() removes buffers from the input stream,
5744 // get the right buffer here before unlocking mRequestLock
5745 if (nextRequest->mInputStream != NULL) {
5746 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5747 if (res != OK) {
5748 // Can't get input buffer from gralloc queue - this could be due to
5749 // disconnected queue or other producer misbehavior, so not a fatal
5750 // error
5751 ALOGE("%s: Can't get input buffer, skipping request:"
5752 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005753
5754 sp<NotificationListener> listener = mListener.promote();
5755 if (listener != NULL) {
5756 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005757 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005758 nextRequest->mResultExtras);
5759 }
5760 return NULL;
5761 }
5762 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005763 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005764
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005765 return nextRequest;
5766}
5767
5768bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005769 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005770 status_t res;
5771 Mutex::Autolock l(mPauseLock);
5772 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005773 if (mPaused == false) {
5774 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005775 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5776 // Let the tracker know
5777 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5778 if (statusTracker != 0) {
5779 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5780 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005781 if (mNotifyPipelineDrain) {
5782 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5783 mNotifyPipelineDrain = false;
5784 mStreamIdsToBeDrained.clear();
5785 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005786 sp<Camera3Device> parent = mParent.promote();
5787 if (parent != nullptr) {
5788 parent->mRequestBufferSM.onRequestThreadPaused();
5789 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005790 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005791
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005792 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005793 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005794 return true;
5795 }
5796 }
5797 // We don't set mPaused to false here, because waitForNextRequest needs
5798 // to further manage the paused state in case of starvation.
5799 return false;
5800}
5801
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005802void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005803 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005804 // With work to do, mark thread as unpaused.
5805 // If paused by request (setPaused), don't resume, to avoid
5806 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005807 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005808 Mutex::Autolock p(mPauseLock);
5809 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005810 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5811 if (mPaused) {
5812 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5813 if (statusTracker != 0) {
5814 statusTracker->markComponentActive(mStatusId);
5815 }
5816 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005817 mPaused = false;
5818 }
5819}
5820
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005821void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5822 sp<Camera3Device> parent = mParent.promote();
5823 if (parent != NULL) {
5824 va_list args;
5825 va_start(args, fmt);
5826
5827 parent->setErrorStateV(fmt, args);
5828
5829 va_end(args);
5830 }
5831}
5832
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005833status_t Camera3Device::RequestThread::insertTriggers(
5834 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005835 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005836 Mutex::Autolock al(mTriggerMutex);
5837
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005838 sp<Camera3Device> parent = mParent.promote();
5839 if (parent == NULL) {
5840 CLOGE("RequestThread: Parent is gone");
5841 return DEAD_OBJECT;
5842 }
5843
Emilian Peevaebbe412018-01-15 13:53:24 +00005844 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005845 size_t count = mTriggerMap.size();
5846
5847 for (size_t i = 0; i < count; ++i) {
5848 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005849 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005850
5851 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5852 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5853 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005854 if (isAeTrigger) {
5855 request->mResultExtras.precaptureTriggerId = triggerId;
5856 mCurrentPreCaptureTriggerId = triggerId;
5857 } else {
5858 request->mResultExtras.afTriggerId = triggerId;
5859 mCurrentAfTriggerId = triggerId;
5860 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005861 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005862 }
5863
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005864 camera_metadata_entry entry = metadata.find(tag);
5865
5866 if (entry.count > 0) {
5867 /**
5868 * Already has an entry for this trigger in the request.
5869 * Rewrite it with our requested trigger value.
5870 */
5871 RequestTrigger oldTrigger = trigger;
5872
5873 oldTrigger.entryValue = entry.data.u8[0];
5874
5875 mTriggerReplacedMap.add(tag, oldTrigger);
5876 } else {
5877 /**
5878 * More typical, no trigger entry, so we just add it
5879 */
5880 mTriggerRemovedMap.add(tag, trigger);
5881 }
5882
5883 status_t res;
5884
5885 switch (trigger.getTagType()) {
5886 case TYPE_BYTE: {
5887 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5888 res = metadata.update(tag,
5889 &entryValue,
5890 /*count*/1);
5891 break;
5892 }
5893 case TYPE_INT32:
5894 res = metadata.update(tag,
5895 &trigger.entryValue,
5896 /*count*/1);
5897 break;
5898 default:
5899 ALOGE("%s: Type not supported: 0x%x",
5900 __FUNCTION__,
5901 trigger.getTagType());
5902 return INVALID_OPERATION;
5903 }
5904
5905 if (res != OK) {
5906 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5907 ", value %d", __FUNCTION__, trigger.getTagName(),
5908 trigger.entryValue);
5909 return res;
5910 }
5911
5912 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5913 trigger.getTagName(),
5914 trigger.entryValue);
5915 }
5916
5917 mTriggerMap.clear();
5918
5919 return count;
5920}
5921
5922status_t Camera3Device::RequestThread::removeTriggers(
5923 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005924 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005925 Mutex::Autolock al(mTriggerMutex);
5926
Emilian Peevaebbe412018-01-15 13:53:24 +00005927 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005928
5929 /**
5930 * Replace all old entries with their old values.
5931 */
5932 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5933 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5934
5935 status_t res;
5936
5937 uint32_t tag = trigger.metadataTag;
5938 switch (trigger.getTagType()) {
5939 case TYPE_BYTE: {
5940 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5941 res = metadata.update(tag,
5942 &entryValue,
5943 /*count*/1);
5944 break;
5945 }
5946 case TYPE_INT32:
5947 res = metadata.update(tag,
5948 &trigger.entryValue,
5949 /*count*/1);
5950 break;
5951 default:
5952 ALOGE("%s: Type not supported: 0x%x",
5953 __FUNCTION__,
5954 trigger.getTagType());
5955 return INVALID_OPERATION;
5956 }
5957
5958 if (res != OK) {
5959 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5960 ", trigger value %d", __FUNCTION__,
5961 trigger.getTagName(), trigger.entryValue);
5962 return res;
5963 }
5964 }
5965 mTriggerReplacedMap.clear();
5966
5967 /**
5968 * Remove all new entries.
5969 */
5970 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5971 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5972 status_t res = metadata.erase(trigger.metadataTag);
5973
5974 if (res != OK) {
5975 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5976 ", trigger value %d", __FUNCTION__,
5977 trigger.getTagName(), trigger.entryValue);
5978 return res;
5979 }
5980 }
5981 mTriggerRemovedMap.clear();
5982
5983 return OK;
5984}
5985
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005986status_t Camera3Device::RequestThread::addDummyTriggerIds(
5987 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005988 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005989 static const int32_t dummyTriggerId = 1;
5990 status_t res;
5991
Emilian Peevaebbe412018-01-15 13:53:24 +00005992 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005993
5994 // If AF trigger is active, insert a dummy AF trigger ID if none already
5995 // exists
5996 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5997 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5998 if (afTrigger.count > 0 &&
5999 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6000 afId.count == 0) {
6001 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6002 if (res != OK) return res;
6003 }
6004
6005 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6006 // if none already exists
6007 camera_metadata_entry pcTrigger =
6008 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6009 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6010 if (pcTrigger.count > 0 &&
6011 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6012 pcId.count == 0) {
6013 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6014 &dummyTriggerId, 1);
6015 if (res != OK) return res;
6016 }
6017
6018 return OK;
6019}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006020
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006021/**
6022 * PreparerThread inner class methods
6023 */
6024
6025Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006026 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006027 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006028}
6029
6030Camera3Device::PreparerThread::~PreparerThread() {
6031 Thread::requestExitAndWait();
6032 if (mCurrentStream != nullptr) {
6033 mCurrentStream->cancelPrepare();
6034 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6035 mCurrentStream.clear();
6036 }
6037 clear();
6038}
6039
Ruben Brunkc78ac262015-08-13 17:58:46 -07006040status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006041 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006042 status_t res;
6043
6044 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006045 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006046
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006047 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006048 if (res == OK) {
6049 // No preparation needed, fire listener right off
6050 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006051 if (listener != NULL) {
6052 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006053 }
6054 return OK;
6055 } else if (res != NOT_ENOUGH_DATA) {
6056 return res;
6057 }
6058
6059 // Need to prepare, start up thread if necessary
6060 if (!mActive) {
6061 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6062 // isn't running
6063 Thread::requestExitAndWait();
6064 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6065 if (res != OK) {
6066 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006067 if (listener != NULL) {
6068 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006069 }
6070 return res;
6071 }
6072 mCancelNow = false;
6073 mActive = true;
6074 ALOGV("%s: Preparer stream started", __FUNCTION__);
6075 }
6076
6077 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006078 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006079 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6080
6081 return OK;
6082}
6083
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006084void Camera3Device::PreparerThread::pause() {
6085 ATRACE_CALL();
6086
6087 Mutex::Autolock l(mLock);
6088
6089 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6090 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6091 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6092 int currentMaxCount = mCurrentMaxCount;
6093 mPendingStreams.clear();
6094 mCancelNow = true;
6095 while (mActive) {
6096 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6097 if (res == TIMED_OUT) {
6098 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6099 return;
6100 } else if (res != OK) {
6101 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6102 return;
6103 }
6104 }
6105
6106 //Check whether the prepare thread was able to complete the current
6107 //stream. In case work is still pending emplace it along with the rest
6108 //of the streams in the pending list.
6109 if (currentStream != nullptr) {
6110 if (!mCurrentPrepareComplete) {
6111 pendingStreams.emplace(currentMaxCount, currentStream);
6112 }
6113 }
6114
6115 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6116 for (const auto& it : mPendingStreams) {
6117 it.second->cancelPrepare();
6118 }
6119}
6120
6121status_t Camera3Device::PreparerThread::resume() {
6122 ATRACE_CALL();
6123 status_t res;
6124
6125 Mutex::Autolock l(mLock);
6126 sp<NotificationListener> listener = mListener.promote();
6127
6128 if (mActive) {
6129 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6130 return NO_INIT;
6131 }
6132
6133 auto it = mPendingStreams.begin();
6134 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006135 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006136 if (res == OK) {
6137 if (listener != NULL) {
6138 listener->notifyPrepared(it->second->getId());
6139 }
6140 it = mPendingStreams.erase(it);
6141 } else if (res != NOT_ENOUGH_DATA) {
6142 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6143 res, strerror(-res));
6144 it = mPendingStreams.erase(it);
6145 } else {
6146 it++;
6147 }
6148 }
6149
6150 if (mPendingStreams.empty()) {
6151 return OK;
6152 }
6153
6154 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6155 if (res != OK) {
6156 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6157 __FUNCTION__, res, strerror(-res));
6158 return res;
6159 }
6160 mCancelNow = false;
6161 mActive = true;
6162 ALOGV("%s: Preparer stream started", __FUNCTION__);
6163
6164 return OK;
6165}
6166
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006167status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006168 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006169 Mutex::Autolock l(mLock);
6170
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006171 for (const auto& it : mPendingStreams) {
6172 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006173 }
6174 mPendingStreams.clear();
6175 mCancelNow = true;
6176
6177 return OK;
6178}
6179
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006180void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006181 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006182 Mutex::Autolock l(mLock);
6183 mListener = listener;
6184}
6185
6186bool Camera3Device::PreparerThread::threadLoop() {
6187 status_t res;
6188 {
6189 Mutex::Autolock l(mLock);
6190 if (mCurrentStream == nullptr) {
6191 // End thread if done with work
6192 if (mPendingStreams.empty()) {
6193 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6194 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6195 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6196 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006197 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006198 return false;
6199 }
6200
6201 // Get next stream to prepare
6202 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006203 mCurrentStream = it->second;
6204 mCurrentMaxCount = it->first;
6205 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006206 mPendingStreams.erase(it);
6207 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6208 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6209 } else if (mCancelNow) {
6210 mCurrentStream->cancelPrepare();
6211 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6212 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6213 mCurrentStream.clear();
6214 mCancelNow = false;
6215 return true;
6216 }
6217 }
6218
6219 res = mCurrentStream->prepareNextBuffer();
6220 if (res == NOT_ENOUGH_DATA) return true;
6221 if (res != OK) {
6222 // Something bad happened; try to recover by cancelling prepare and
6223 // signalling listener anyway
6224 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6225 mCurrentStream->getId(), res, strerror(-res));
6226 mCurrentStream->cancelPrepare();
6227 }
6228
6229 // This stream has finished, notify listener
6230 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006231 sp<NotificationListener> listener = mListener.promote();
6232 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006233 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6234 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006235 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006236 }
6237
6238 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6239 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006240 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006241
6242 return true;
6243}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006244
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006245status_t Camera3Device::RequestBufferStateMachine::initialize(
6246 sp<camera3::StatusTracker> statusTracker) {
6247 if (statusTracker == nullptr) {
6248 ALOGE("%s: statusTracker is null", __FUNCTION__);
6249 return BAD_VALUE;
6250 }
6251
6252 std::lock_guard<std::mutex> lock(mLock);
6253 mStatusTracker = statusTracker;
6254 mRequestBufferStatusId = statusTracker->addComponent();
6255 return OK;
6256}
6257
6258bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6259 std::lock_guard<std::mutex> lock(mLock);
6260 if (mStatus == RB_STATUS_READY) {
6261 mRequestBufferOngoing = true;
6262 return true;
6263 }
6264 return false;
6265}
6266
6267void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6268 std::lock_guard<std::mutex> lock(mLock);
6269 if (!mRequestBufferOngoing) {
6270 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6271 return;
6272 }
6273 mRequestBufferOngoing = false;
6274 if (mStatus == RB_STATUS_PENDING_STOP) {
6275 checkSwitchToStopLocked();
6276 }
6277}
6278
6279void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6280 std::lock_guard<std::mutex> lock(mLock);
6281 RequestBufferState oldStatus = mStatus;
6282 mStatus = RB_STATUS_READY;
6283 if (oldStatus != RB_STATUS_READY) {
6284 notifyTrackerLocked(/*active*/true);
6285 }
6286 return;
6287}
6288
6289void Camera3Device::RequestBufferStateMachine::onRequestSubmitted() {
6290 std::lock_guard<std::mutex> lock(mLock);
6291 mRequestThreadPaused = false;
6292 mInflightMapEmpty = false;
6293 if (mStatus == RB_STATUS_STOPPED) {
6294 mStatus = RB_STATUS_READY;
6295 notifyTrackerLocked(/*active*/true);
6296 }
6297 return;
6298}
6299
6300void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6301 std::lock_guard<std::mutex> lock(mLock);
6302 mRequestThreadPaused = true;
6303 if (mStatus == RB_STATUS_PENDING_STOP) {
6304 checkSwitchToStopLocked();
6305 }
6306 return;
6307}
6308
6309void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6310 std::lock_guard<std::mutex> lock(mLock);
6311 mInflightMapEmpty = true;
6312 if (mStatus == RB_STATUS_PENDING_STOP) {
6313 checkSwitchToStopLocked();
6314 }
6315 return;
6316}
6317
6318void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6319 std::lock_guard<std::mutex> lock(mLock);
6320 if (!checkSwitchToStopLocked()) {
6321 mStatus = RB_STATUS_PENDING_STOP;
6322 }
6323 return;
6324}
6325
6326void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6327 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6328 if (statusTracker != nullptr) {
6329 if (active) {
6330 statusTracker->markComponentActive(mRequestBufferStatusId);
6331 } else {
6332 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6333 }
6334 }
6335}
6336
6337bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6338 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6339 mStatus = RB_STATUS_STOPPED;
6340 notifyTrackerLocked(/*active*/false);
6341 return true;
6342 }
6343 return false;
6344}
6345
Shuzhen Wang268a1362018-10-16 16:32:59 -07006346status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6347 CameraMetadata& resultMetadata) {
6348 status_t res = OK;
6349 if (!mNeedFixupMonochromeTags) {
6350 return res;
6351 }
6352
6353 // Remove tags that are not applicable to monochrome camera.
6354 int32_t tagsToRemove[] = {
6355 ANDROID_SENSOR_GREEN_SPLIT,
6356 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6357 ANDROID_COLOR_CORRECTION_MODE,
6358 ANDROID_COLOR_CORRECTION_TRANSFORM,
6359 ANDROID_COLOR_CORRECTION_GAINS,
6360 };
6361 for (auto tag : tagsToRemove) {
6362 res = resultMetadata.erase(tag);
6363 if (res != OK) {
6364 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6365 return res;
6366 }
6367 }
6368
6369 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6370 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6371 for (size_t i = 1; i < blEntry.count; i++) {
6372 blEntry.data.f[i] = blEntry.data.f[0];
6373 }
6374
6375 // ANDROID_SENSOR_NOISE_PROFILE
6376 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6377 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6378 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6379 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6380 if (res != OK) {
6381 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6382 __FUNCTION__, strerror(-res), res);
6383 return res;
6384 }
6385 }
6386
6387 // ANDROID_STATISTICS_LENS_SHADING_MAP
6388 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6389 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6390 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6391 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6392 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6393 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6394 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6395 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6396 }
6397 }
6398
6399 // ANDROID_TONEMAP_CURVE_BLUE
6400 // ANDROID_TONEMAP_CURVE_GREEN
6401 // ANDROID_TONEMAP_CURVE_RED
6402 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6403 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6404 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6405 if (tcbEntry.count > 0
6406 && tcbEntry.count == tcgEntry.count
6407 && tcbEntry.count == tcrEntry.count) {
6408 for (size_t i = 0; i < tcbEntry.count; i++) {
6409 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6410 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6411 }
6412 }
6413
6414 return res;
6415}
6416
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006417}; // namespace android