blob: 58471b9752f6a6fa1b19601c47aeb62d970230a4 [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 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001110 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1111 camera3_stream_buffer_t& sb = streamBuffers[b];
1112 sb.acquire_fence = -1;
1113 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1114 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001115 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1116 }
1117 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001118
1119 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1120 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1121 BufferRequestStatus::FAILED_UNKNOWN,
1122 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001123 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001124 return hardware::Void();
1125}
1126
1127hardware::Return<void> Camera3Device::returnStreamBuffers(
1128 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1129 if (!mUseHalBufManager) {
1130 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1131 __FUNCTION__, mId.string());
1132 return hardware::Void();
1133 }
1134
1135 for (const auto& buf : buffers) {
1136 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1137 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1138 continue;
1139 }
1140
1141 buffer_handle_t* buffer;
1142 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1143
1144 if (res != OK) {
1145 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1146 __FUNCTION__, buf.bufferId, buf.streamId);
1147 continue;
1148 }
1149
1150 camera3_stream_buffer_t streamBuffer;
1151 streamBuffer.buffer = buffer;
1152 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1153 streamBuffer.acquire_fence = -1;
1154 streamBuffer.release_fence = -1;
1155
1156 if (buf.releaseFence == nullptr) {
1157 streamBuffer.release_fence = -1;
1158 } else if (buf.releaseFence->numFds == 1) {
1159 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1160 } else {
1161 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1162 __FUNCTION__, buf.releaseFence->numFds);
1163 continue;
1164 }
1165
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001166 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1167 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001168 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1169 continue;
1170 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001171 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001172 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1173 }
1174 return hardware::Void();
1175}
1176
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001177hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001178 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001179 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001180 // Ideally we should grab mLock, but that can lead to deadlock, and
1181 // it's not super important to get up to date value of mStatus for this
1182 // warning print, hence skipping the lock here
1183 if (mStatus == STATUS_ERROR) {
1184 // Per API contract, HAL should act as closed after device error
1185 // But mStatus can be set to error by framework as well, so just log
1186 // a warning here.
1187 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001188 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001189
1190 if (mProcessCaptureResultLock.tryLock() != OK) {
1191 // This should never happen; it indicates a wrong client implementation
1192 // that doesn't follow the contract. But, we can be tolerant here.
1193 ALOGE("%s: callback overlapped! waiting 1s...",
1194 __FUNCTION__);
1195 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1196 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1197 __FUNCTION__);
1198 // really don't know what to do, so bail out.
1199 return hardware::Void();
1200 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001201 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001202 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001203 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001204 }
1205 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001206 return hardware::Void();
1207}
1208
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001209// Only one processCaptureResult should be called at a time, so
1210// the locks won't block. The locks are present here simply to enforce this.
1211hardware::Return<void> Camera3Device::processCaptureResult(
1212 const hardware::hidl_vec<
1213 hardware::camera::device::V3_2::CaptureResult>& results) {
1214 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1215
1216 // Ideally we should grab mLock, but that can lead to deadlock, and
1217 // it's not super important to get up to date value of mStatus for this
1218 // warning print, hence skipping the lock here
1219 if (mStatus == STATUS_ERROR) {
1220 // Per API contract, HAL should act as closed after device error
1221 // But mStatus can be set to error by framework as well, so just log
1222 // a warning here.
1223 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1224 }
1225
1226 if (mProcessCaptureResultLock.tryLock() != OK) {
1227 // This should never happen; it indicates a wrong client implementation
1228 // that doesn't follow the contract. But, we can be tolerant here.
1229 ALOGE("%s: callback overlapped! waiting 1s...",
1230 __FUNCTION__);
1231 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1232 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1233 __FUNCTION__);
1234 // really don't know what to do, so bail out.
1235 return hardware::Void();
1236 }
1237 }
1238 for (const auto& result : results) {
1239 processOneCaptureResultLocked(result, noPhysMetadata);
1240 }
1241 mProcessCaptureResultLock.unlock();
1242 return hardware::Void();
1243}
1244
1245status_t Camera3Device::readOneCameraMetadataLocked(
1246 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1247 const hardware::camera::device::V3_2::CameraMetadata& result) {
1248 if (fmqResultSize > 0) {
1249 resultMetadata.resize(fmqResultSize);
1250 if (mResultMetadataQueue == nullptr) {
1251 return NO_MEMORY; // logged in initialize()
1252 }
1253 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1254 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1255 __FUNCTION__, fmqResultSize);
1256 return INVALID_OPERATION;
1257 }
1258 } else {
1259 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1260 result.size());
1261 }
1262
1263 if (resultMetadata.size() != 0) {
1264 status_t res;
1265 const camera_metadata_t* metadata =
1266 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1267 size_t expected_metadata_size = resultMetadata.size();
1268 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1269 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1270 __FUNCTION__, strerror(-res), res);
1271 return INVALID_OPERATION;
1272 }
1273 }
1274
1275 return OK;
1276}
1277
Yifan Honga640c5a2017-04-12 16:30:31 -07001278void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001279 const hardware::camera::device::V3_2::CaptureResult& result,
1280 const hardware::hidl_vec<
1281 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001282 camera3_capture_result r;
1283 status_t res;
1284 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001285
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001286 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001287 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001288 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1289 if (res != OK) {
1290 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1291 __FUNCTION__, result.frameNumber);
1292 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001293 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001294 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001295
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001296 // Read and validate physical camera metadata
1297 size_t physResultCount = physicalCameraMetadatas.size();
1298 std::vector<const char*> physCamIds(physResultCount);
1299 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1300 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1301 physResultMetadata.resize(physResultCount);
1302 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1303 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1304 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1305 if (res != OK) {
1306 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1307 __FUNCTION__, result.frameNumber,
1308 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001309 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001310 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001311 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1312 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1313 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001314 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001315 r.num_physcam_metadata = physResultCount;
1316 r.physcam_ids = physCamIds.data();
1317 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001318
1319 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1320 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1321 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1322 auto& bDst = outputBuffers[i];
1323 const StreamBuffer &bSrc = result.outputBuffers[i];
1324
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001325 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1326 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001327 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1328 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001329 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001330 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001331 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001332
1333 buffer_handle_t *buffer;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001334 if (mUseHalBufManager) {
1335 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1336 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1337 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1338 return;
1339 }
1340 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1341 } else {
1342 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1343 }
1344
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001345 if (res != OK) {
1346 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1347 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001348 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001349 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001350
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001351 bDst.buffer = buffer;
1352 bDst.status = mapHidlBufferStatus(bSrc.status);
1353 bDst.acquire_fence = -1;
1354 if (bSrc.releaseFence == nullptr) {
1355 bDst.release_fence = -1;
1356 } else if (bSrc.releaseFence->numFds == 1) {
1357 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1358 } else {
1359 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1360 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001361 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001362 }
1363 }
1364 r.num_output_buffers = outputBuffers.size();
1365 r.output_buffers = outputBuffers.data();
1366
1367 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001368 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001369 r.input_buffer = nullptr;
1370 } else {
1371 if (mInputStream->getId() != result.inputBuffer.streamId) {
1372 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1373 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001374 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001375 }
1376 inputBuffer.stream = mInputStream->asHalStream();
1377 buffer_handle_t *buffer;
1378 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1379 &buffer);
1380 if (res != OK) {
1381 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1382 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001383 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001384 }
1385 inputBuffer.buffer = buffer;
1386 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1387 inputBuffer.acquire_fence = -1;
1388 if (result.inputBuffer.releaseFence == nullptr) {
1389 inputBuffer.release_fence = -1;
1390 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1391 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1392 } else {
1393 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1394 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001395 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001396 }
1397 r.input_buffer = &inputBuffer;
1398 }
1399
1400 r.partial_result = result.partialResult;
1401
1402 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001403}
1404
1405hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001406 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001407 // Ideally we should grab mLock, but that can lead to deadlock, and
1408 // it's not super important to get up to date value of mStatus for this
1409 // warning print, hence skipping the lock here
1410 if (mStatus == STATUS_ERROR) {
1411 // Per API contract, HAL should act as closed after device error
1412 // But mStatus can be set to error by framework as well, so just log
1413 // a warning here.
1414 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001415 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001416
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001417 for (const auto& msg : msgs) {
1418 notify(msg);
1419 }
1420 return hardware::Void();
1421}
1422
1423void Camera3Device::notify(
1424 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1425
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001426 camera3_notify_msg m;
1427 switch (msg.type) {
1428 case MsgType::ERROR:
1429 m.type = CAMERA3_MSG_ERROR;
1430 m.message.error.frame_number = msg.msg.error.frameNumber;
1431 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001432 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1433 if (stream == nullptr) {
1434 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1435 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001436 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001437 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001438 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001439 } else {
1440 m.message.error.error_stream = nullptr;
1441 }
1442 switch (msg.msg.error.errorCode) {
1443 case ErrorCode::ERROR_DEVICE:
1444 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1445 break;
1446 case ErrorCode::ERROR_REQUEST:
1447 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1448 break;
1449 case ErrorCode::ERROR_RESULT:
1450 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1451 break;
1452 case ErrorCode::ERROR_BUFFER:
1453 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1454 break;
1455 }
1456 break;
1457 case MsgType::SHUTTER:
1458 m.type = CAMERA3_MSG_SHUTTER;
1459 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1460 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1461 break;
1462 }
1463 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001464}
1465
Emilian Peevaebbe412018-01-15 13:53:24 +00001466status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001467 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001468 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001469 ATRACE_CALL();
1470
Emilian Peevaebbe412018-01-15 13:53:24 +00001471 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001472}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001473
Jianing Weicb0652e2014-03-12 18:29:36 -07001474status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1475 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001476 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001477
Emilian Peevaebbe412018-01-15 13:53:24 +00001478 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001479 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001480 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001481
Emilian Peevaebbe412018-01-15 13:53:24 +00001482 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001483 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484}
1485
Emilian Peevaebbe412018-01-15 13:53:24 +00001486status_t Camera3Device::setStreamingRequestList(
1487 const List<const PhysicalCameraSettingsList> &requestsList,
1488 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001489 ATRACE_CALL();
1490
Emilian Peevaebbe412018-01-15 13:53:24 +00001491 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001492}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001493
1494sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001495 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001496 status_t res;
1497
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001498 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001499 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1500 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001501 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1502 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001503 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001504 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001505 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001507 } else if (mStatus == STATUS_UNCONFIGURED) {
1508 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001509 CLOGE("No streams configured");
1510 return NULL;
1511 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001512 }
1513
Shuzhen Wang0129d522016-10-30 22:43:41 -07001514 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001515 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001516}
1517
Jianing Weicb0652e2014-03-12 18:29:36 -07001518status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001519 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001520 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001522
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 switch (mStatus) {
1524 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001525 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001526 return INVALID_OPERATION;
1527 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001528 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001529 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001530 case STATUS_UNCONFIGURED:
1531 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001532 case STATUS_ACTIVE:
1533 // OK
1534 break;
1535 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001536 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001537 return INVALID_OPERATION;
1538 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001539 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001540
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001541 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001542}
1543
1544status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1545 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001546 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001547
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001548 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001549}
1550
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001551status_t Camera3Device::createInputStream(
1552 uint32_t width, uint32_t height, int format, int *id) {
1553 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001554 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001555 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001556 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001557 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1558 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001559
1560 status_t res;
1561 bool wasActive = false;
1562
1563 switch (mStatus) {
1564 case STATUS_ERROR:
1565 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1566 return INVALID_OPERATION;
1567 case STATUS_UNINITIALIZED:
1568 ALOGE("%s: Device not initialized", __FUNCTION__);
1569 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001570 case STATUS_UNCONFIGURED:
1571 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001572 // OK
1573 break;
1574 case STATUS_ACTIVE:
1575 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001576 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001577 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001578 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001579 return res;
1580 }
1581 wasActive = true;
1582 break;
1583 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001584 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001585 return INVALID_OPERATION;
1586 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001587 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001588
1589 if (mInputStream != 0) {
1590 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1591 return INVALID_OPERATION;
1592 }
1593
1594 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1595 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001596 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001597
1598 mInputStream = newStream;
1599
1600 *id = mNextStreamId++;
1601
1602 // Continue captures if active at start
1603 if (wasActive) {
1604 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001605 // Reuse current operating mode and session parameters for new stream config
1606 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001607 if (res != OK) {
1608 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1609 __FUNCTION__, mNextStreamId, strerror(-res), res);
1610 return res;
1611 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001612 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001613 }
1614
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001615 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001616 return OK;
1617}
1618
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001619status_t Camera3Device::StreamSet::add(
1620 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1621 if (stream == nullptr) {
1622 ALOGE("%s: cannot add null stream", __FUNCTION__);
1623 return BAD_VALUE;
1624 }
1625 std::lock_guard<std::mutex> lock(mLock);
1626 return mData.add(streamId, stream);
1627}
1628
1629ssize_t Camera3Device::StreamSet::remove(int streamId) {
1630 std::lock_guard<std::mutex> lock(mLock);
1631 return mData.removeItem(streamId);
1632}
1633
1634sp<camera3::Camera3OutputStreamInterface>
1635Camera3Device::StreamSet::get(int streamId) {
1636 std::lock_guard<std::mutex> lock(mLock);
1637 ssize_t idx = mData.indexOfKey(streamId);
1638 if (idx == NAME_NOT_FOUND) {
1639 return nullptr;
1640 }
1641 return mData.editValueAt(idx);
1642}
1643
1644sp<camera3::Camera3OutputStreamInterface>
1645Camera3Device::StreamSet::operator[] (size_t index) {
1646 std::lock_guard<std::mutex> lock(mLock);
1647 return mData.editValueAt(index);
1648}
1649
1650size_t Camera3Device::StreamSet::size() const {
1651 std::lock_guard<std::mutex> lock(mLock);
1652 return mData.size();
1653}
1654
1655void Camera3Device::StreamSet::clear() {
1656 std::lock_guard<std::mutex> lock(mLock);
1657 return mData.clear();
1658}
1659
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001660std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1661 std::lock_guard<std::mutex> lock(mLock);
1662 std::vector<int> streamIds(mData.size());
1663 for (size_t i = 0; i < mData.size(); i++) {
1664 streamIds[i] = mData.keyAt(i);
1665 }
1666 return streamIds;
1667}
1668
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001669status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001670 uint32_t width, uint32_t height, int format,
1671 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001672 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001673 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001674 ATRACE_CALL();
1675
1676 if (consumer == nullptr) {
1677 ALOGE("%s: consumer must not be null", __FUNCTION__);
1678 return BAD_VALUE;
1679 }
1680
1681 std::vector<sp<Surface>> consumers;
1682 consumers.push_back(consumer);
1683
1684 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001685 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1686 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001687}
1688
1689status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1690 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1691 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001692 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001693 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001694 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001695
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001696 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001697 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001698 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001699 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001700 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1701 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1702 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001703
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001704 status_t res;
1705 bool wasActive = false;
1706
1707 switch (mStatus) {
1708 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001709 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001710 return INVALID_OPERATION;
1711 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001712 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001713 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001714 case STATUS_UNCONFIGURED:
1715 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001716 // OK
1717 break;
1718 case STATUS_ACTIVE:
1719 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001720 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001721 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001722 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001723 return res;
1724 }
1725 wasActive = true;
1726 break;
1727 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001728 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001729 return INVALID_OPERATION;
1730 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001731 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001732
1733 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001734
Shuzhen Wang0129d522016-10-30 22:43:41 -07001735 if (consumers.size() == 0 && !hasDeferredConsumer) {
1736 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1737 return BAD_VALUE;
1738 }
Zhijun He5d677d12016-05-29 16:52:39 -07001739
Shuzhen Wang0129d522016-10-30 22:43:41 -07001740 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001741 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1742 return BAD_VALUE;
1743 }
1744
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001745 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001746 ssize_t blobBufferSize;
1747 if (dataSpace != HAL_DATASPACE_DEPTH) {
1748 blobBufferSize = getJpegBufferSize(width, height);
1749 if (blobBufferSize <= 0) {
1750 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1751 return BAD_VALUE;
1752 }
1753 } else {
1754 blobBufferSize = getPointCloudBufferSize();
1755 if (blobBufferSize <= 0) {
1756 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1757 return BAD_VALUE;
1758 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001759 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001760 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001761 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001762 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001763 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1764 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1765 if (rawOpaqueBufferSize <= 0) {
1766 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1767 return BAD_VALUE;
1768 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001769 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001770 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001771 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001772 } else if (isShared) {
1773 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1774 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001775 mTimestampOffset, physicalCameraId, streamSetId,
1776 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001777 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001778 newStream = new Camera3OutputStream(mNextStreamId,
1779 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001780 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001781 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001782 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001783 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001784 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001785 }
Emilian Peev40ead602017-09-26 15:46:36 +01001786
1787 size_t consumerCount = consumers.size();
1788 for (size_t i = 0; i < consumerCount; i++) {
1789 int id = newStream->getSurfaceId(consumers[i]);
1790 if (id < 0) {
1791 SET_ERR_L("Invalid surface id");
1792 return BAD_VALUE;
1793 }
1794 if (surfaceIds != nullptr) {
1795 surfaceIds->push_back(id);
1796 }
1797 }
1798
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001799 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001800
Emilian Peev08dd2452017-04-06 16:55:14 +01001801 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001802
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001803 res = mOutputStreams.add(mNextStreamId, newStream);
1804 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001805 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001806 return res;
1807 }
1808
1809 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001810 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001811
1812 // Continue captures if active at start
1813 if (wasActive) {
1814 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001815 // Reuse current operating mode and session parameters for new stream config
1816 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001817 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001818 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1819 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001820 return res;
1821 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001822 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001823 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001824 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001825 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001826}
1827
Emilian Peev710c1422017-08-30 11:19:38 +01001828status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001829 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001830 if (nullptr == streamInfo) {
1831 return BAD_VALUE;
1832 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001833 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001834 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001835
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001836 switch (mStatus) {
1837 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001838 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001839 return INVALID_OPERATION;
1840 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001841 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001842 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001843 case STATUS_UNCONFIGURED:
1844 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001845 case STATUS_ACTIVE:
1846 // OK
1847 break;
1848 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001849 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001850 return INVALID_OPERATION;
1851 }
1852
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001853 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1854 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001855 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001856 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001857 }
1858
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001859 streamInfo->width = stream->getWidth();
1860 streamInfo->height = stream->getHeight();
1861 streamInfo->format = stream->getFormat();
1862 streamInfo->dataSpace = stream->getDataSpace();
1863 streamInfo->formatOverridden = stream->isFormatOverridden();
1864 streamInfo->originalFormat = stream->getOriginalFormat();
1865 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1866 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001867 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001868}
1869
1870status_t Camera3Device::setStreamTransform(int id,
1871 int transform) {
1872 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001873 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001874 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001875
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001876 switch (mStatus) {
1877 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001878 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001879 return INVALID_OPERATION;
1880 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001881 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001882 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001883 case STATUS_UNCONFIGURED:
1884 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001885 case STATUS_ACTIVE:
1886 // OK
1887 break;
1888 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001889 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001890 return INVALID_OPERATION;
1891 }
1892
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001893 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1894 if (stream == nullptr) {
1895 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001896 return BAD_VALUE;
1897 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001898 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001899}
1900
1901status_t Camera3Device::deleteStream(int id) {
1902 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001903 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001904 Mutex::Autolock l(mLock);
1905 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001906
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001907 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001908
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001909 // CameraDevice semantics require device to already be idle before
1910 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001911 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001912 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001913 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001914 }
1915
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001916 if (mStatus == STATUS_ERROR) {
1917 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1918 __FUNCTION__, mId.string());
1919 return -EBUSY;
1920 }
1921
Igor Murashkin2fba5842013-04-22 14:03:54 -07001922 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001923 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001924 if (mInputStream != NULL && id == mInputStream->getId()) {
1925 deletedStream = mInputStream;
1926 mInputStream.clear();
1927 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001928 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001929 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001930 return BAD_VALUE;
1931 }
Zhijun He5f446352014-01-22 09:49:33 -08001932 }
1933
1934 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001935 if (stream != nullptr) {
1936 deletedStream = stream;
1937 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001938 }
1939
1940 // Free up the stream endpoint so that it can be used by some other stream
1941 res = deletedStream->disconnect();
1942 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001943 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001944 // fall through since we want to still list the stream as deleted.
1945 }
1946 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001947 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001948
1949 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001950}
1951
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001952status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001953 ATRACE_CALL();
1954 ALOGV("%s: E", __FUNCTION__);
1955
1956 Mutex::Autolock il(mInterfaceLock);
1957 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001958
Emilian Peev811d2952018-05-25 11:08:40 +01001959 // In case the client doesn't include any session parameter, try a
1960 // speculative configuration using the values from the last cached
1961 // default request.
1962 if (sessionParams.isEmpty() &&
1963 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1964 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1965 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1966 mLastTemplateId);
1967 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1968 operatingMode);
1969 }
1970
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001971 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1972}
1973
1974status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1975 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001976 //Filter out any incoming session parameters
1977 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001978 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1979 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001980 CameraMetadata filteredParams(availableSessionKeys.count);
1981 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1982 filteredParams.getAndLock());
1983 set_camera_metadata_vendor_id(meta, mVendorTagId);
1984 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001985 if (availableSessionKeys.count > 0) {
1986 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1987 camera_metadata_ro_entry entry = params.find(
1988 availableSessionKeys.data.i32[i]);
1989 if (entry.count > 0) {
1990 filteredParams.update(entry);
1991 }
1992 }
1993 }
1994
1995 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001996}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001997
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001998status_t Camera3Device::getInputBufferProducer(
1999 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002000 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002001 Mutex::Autolock il(mInterfaceLock);
2002 Mutex::Autolock l(mLock);
2003
2004 if (producer == NULL) {
2005 return BAD_VALUE;
2006 } else if (mInputStream == NULL) {
2007 return INVALID_OPERATION;
2008 }
2009
2010 return mInputStream->getInputBufferProducer(producer);
2011}
2012
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002013status_t Camera3Device::createDefaultRequest(int templateId,
2014 CameraMetadata *request) {
2015 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002016 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002017
2018 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2019 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002020 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002021 return BAD_VALUE;
2022 }
2023
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002024 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002025
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002026 {
2027 Mutex::Autolock l(mLock);
2028 switch (mStatus) {
2029 case STATUS_ERROR:
2030 CLOGE("Device has encountered a serious error");
2031 return INVALID_OPERATION;
2032 case STATUS_UNINITIALIZED:
2033 CLOGE("Device is not initialized!");
2034 return INVALID_OPERATION;
2035 case STATUS_UNCONFIGURED:
2036 case STATUS_CONFIGURED:
2037 case STATUS_ACTIVE:
2038 // OK
2039 break;
2040 default:
2041 SET_ERR_L("Unexpected status: %d", mStatus);
2042 return INVALID_OPERATION;
2043 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002044
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002045 if (!mRequestTemplateCache[templateId].isEmpty()) {
2046 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002047 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002048 return OK;
2049 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002050 }
2051
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002052 camera_metadata_t *rawRequest;
2053 status_t res = mInterface->constructDefaultRequestSettings(
2054 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002055
2056 {
2057 Mutex::Autolock l(mLock);
2058 if (res == BAD_VALUE) {
2059 ALOGI("%s: template %d is not supported on this camera device",
2060 __FUNCTION__, templateId);
2061 return res;
2062 } else if (res != OK) {
2063 CLOGE("Unable to construct request template %d: %s (%d)",
2064 templateId, strerror(-res), res);
2065 return res;
2066 }
2067
2068 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2069 mRequestTemplateCache[templateId].acquire(rawRequest);
2070
2071 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002072 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002073 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002074 return OK;
2075}
2076
2077status_t Camera3Device::waitUntilDrained() {
2078 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002079 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002080 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002081 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002082
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002083 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002084}
2085
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002086status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002087 switch (mStatus) {
2088 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002089 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002090 ALOGV("%s: Already idle", __FUNCTION__);
2091 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002092 case STATUS_CONFIGURED:
2093 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002094 case STATUS_ERROR:
2095 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002096 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002097 break;
2098 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002099 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002100 return INVALID_OPERATION;
2101 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002102 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2103 maxExpectedDuration);
2104 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002105 if (res != OK) {
2106 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2107 res);
2108 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002109 return res;
2110}
2111
Ruben Brunk183f0562015-08-12 12:55:02 -07002112
2113void Camera3Device::internalUpdateStatusLocked(Status status) {
2114 mStatus = status;
2115 mRecentStatusUpdates.add(mStatus);
2116 mStatusChanged.broadcast();
2117}
2118
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002119void Camera3Device::pauseStateNotify(bool enable) {
2120 Mutex::Autolock il(mInterfaceLock);
2121 Mutex::Autolock l(mLock);
2122
2123 mPauseStateNotify = enable;
2124}
2125
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002126// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002127status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002128 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002129
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002130 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2131 maxExpectedDuration);
2132 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002133 if (res != OK) {
2134 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002135 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002136 }
2137
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002138 return res;
2139}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002140
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002141// Resume after internalPauseAndWaitLocked
2142status_t Camera3Device::internalResumeLocked() {
2143 status_t res;
2144
2145 mRequestThread->setPaused(false);
2146
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002147 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2148 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002149 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2150 if (res != OK) {
2151 SET_ERR_L("Can't transition to active in %f seconds!",
2152 kActiveTimeout/1e9);
2153 }
2154 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002155 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002156}
2157
Ruben Brunk183f0562015-08-12 12:55:02 -07002158status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002159 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002160
2161 size_t startIndex = 0;
2162 if (mStatusWaiters == 0) {
2163 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2164 // this status list
2165 mRecentStatusUpdates.clear();
2166 } else {
2167 // If other threads are waiting on updates to this status list, set the position of the
2168 // first element that this list will check rather than clearing the list.
2169 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002170 }
2171
Ruben Brunk183f0562015-08-12 12:55:02 -07002172 mStatusWaiters++;
2173
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002174 // Notify HAL to start draining. We need to notify the HalInterface layer
2175 // even when the device is already IDLE, so HalInterface can reject incoming
2176 // requestStreamBuffers call.
2177 if (!active && mUseHalBufManager) {
2178 auto streamIds = mOutputStreams.getStreamIds();
2179 mRequestThread->signalPipelineDrain(streamIds);
2180 mRequestBufferSM.onWaitUntilIdle();
2181 }
2182
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002183 bool stateSeen = false;
2184 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002185 if (active == (mStatus == STATUS_ACTIVE)) {
2186 // Desired state is current
2187 break;
2188 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002189
2190 res = mStatusChanged.waitRelative(mLock, timeout);
2191 if (res != OK) break;
2192
Ruben Brunk183f0562015-08-12 12:55:02 -07002193 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2194 // transitions.
2195 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2196 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2197 __FUNCTION__);
2198
2199 // Encountered desired state since we began waiting
2200 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002201 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2202 stateSeen = true;
2203 break;
2204 }
2205 }
2206 } while (!stateSeen);
2207
Ruben Brunk183f0562015-08-12 12:55:02 -07002208 mStatusWaiters--;
2209
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002210 return res;
2211}
2212
2213
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002214status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002215 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002216 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002217
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002218 if (listener != NULL && mListener != NULL) {
2219 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2220 }
2221 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002222 mRequestThread->setNotificationListener(listener);
2223 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002224
2225 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002226}
2227
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002228bool Camera3Device::willNotify3A() {
2229 return false;
2230}
2231
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002232status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002233 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002234 status_t res;
2235 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002236
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002237 while (mResultQueue.empty()) {
2238 res = mResultSignal.waitRelative(mOutputLock, timeout);
2239 if (res == TIMED_OUT) {
2240 return res;
2241 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002242 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2243 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002244 return res;
2245 }
2246 }
2247 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002248}
2249
Jianing Weicb0652e2014-03-12 18:29:36 -07002250status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002251 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002252 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002253
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002254 if (mResultQueue.empty()) {
2255 return NOT_ENOUGH_DATA;
2256 }
2257
Jianing Weicb0652e2014-03-12 18:29:36 -07002258 if (frame == NULL) {
2259 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2260 return BAD_VALUE;
2261 }
2262
2263 CaptureResult &result = *(mResultQueue.begin());
2264 frame->mResultExtras = result.mResultExtras;
2265 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002266 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002267 mResultQueue.erase(mResultQueue.begin());
2268
2269 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002270}
2271
2272status_t Camera3Device::triggerAutofocus(uint32_t id) {
2273 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002274 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002275
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002276 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2277 // Mix-in this trigger into the next request and only the next request.
2278 RequestTrigger trigger[] = {
2279 {
2280 ANDROID_CONTROL_AF_TRIGGER,
2281 ANDROID_CONTROL_AF_TRIGGER_START
2282 },
2283 {
2284 ANDROID_CONTROL_AF_TRIGGER_ID,
2285 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002286 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002287 };
2288
2289 return mRequestThread->queueTrigger(trigger,
2290 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002291}
2292
2293status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2294 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002295 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002296
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002297 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2298 // Mix-in this trigger into the next request and only the next request.
2299 RequestTrigger trigger[] = {
2300 {
2301 ANDROID_CONTROL_AF_TRIGGER,
2302 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2303 },
2304 {
2305 ANDROID_CONTROL_AF_TRIGGER_ID,
2306 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002307 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002308 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002309
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002310 return mRequestThread->queueTrigger(trigger,
2311 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002312}
2313
2314status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2315 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002316 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002317
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002318 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2319 // Mix-in this trigger into the next request and only the next request.
2320 RequestTrigger trigger[] = {
2321 {
2322 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2323 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2324 },
2325 {
2326 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2327 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002328 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002329 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002330
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002331 return mRequestThread->queueTrigger(trigger,
2332 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002333}
2334
Jianing Weicb0652e2014-03-12 18:29:36 -07002335status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002336 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002337 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002338 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002339
Zhijun He7ef20392014-04-21 16:04:17 -07002340 {
2341 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002342
2343 // b/116514106 "disconnect()" can get called twice for the same device. The
2344 // camera device will not be initialized during the second run.
2345 if (mStatus == STATUS_UNINITIALIZED) {
2346 return OK;
2347 }
2348
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002349 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002350 }
2351
Emilian Peev08dd2452017-04-06 16:55:14 +01002352 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002353}
2354
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002355status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002356 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2357}
2358
2359status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002360 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002361 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002362 Mutex::Autolock il(mInterfaceLock);
2363 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002364
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002365 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2366 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002367 CLOGE("Stream %d does not exist", streamId);
2368 return BAD_VALUE;
2369 }
2370
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002371 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002372 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002373 return BAD_VALUE;
2374 }
2375
2376 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002377 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002378 return BAD_VALUE;
2379 }
2380
Ruben Brunkc78ac262015-08-13 17:58:46 -07002381 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002382}
2383
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002384status_t Camera3Device::tearDown(int streamId) {
2385 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002386 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002387 Mutex::Autolock il(mInterfaceLock);
2388 Mutex::Autolock l(mLock);
2389
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002390 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2391 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002392 CLOGE("Stream %d does not exist", streamId);
2393 return BAD_VALUE;
2394 }
2395
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002396 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2397 CLOGE("Stream %d is a target of a in-progress request", streamId);
2398 return BAD_VALUE;
2399 }
2400
2401 return stream->tearDown();
2402}
2403
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002404status_t Camera3Device::addBufferListenerForStream(int streamId,
2405 wp<Camera3StreamBufferListener> listener) {
2406 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002407 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002408 Mutex::Autolock il(mInterfaceLock);
2409 Mutex::Autolock l(mLock);
2410
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002411 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2412 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002413 CLOGE("Stream %d does not exist", streamId);
2414 return BAD_VALUE;
2415 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002416 stream->addBufferListener(listener);
2417
2418 return OK;
2419}
2420
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002421/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002422 * Methods called by subclasses
2423 */
2424
2425void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002426 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002427 {
2428 // Need mLock to safely update state and synchronize to current
2429 // state of methods in flight.
2430 Mutex::Autolock l(mLock);
2431 // We can get various system-idle notices from the status tracker
2432 // while starting up. Only care about them if we've actually sent
2433 // in some requests recently.
2434 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2435 return;
2436 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002437 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2438 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002439 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002440
2441 // Skip notifying listener if we're doing some user-transparent
2442 // state changes
2443 if (mPauseStateNotify) return;
2444 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002445
2446 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002447 {
2448 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002449 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002450 }
2451 if (idle && listener != NULL) {
2452 listener->notifyIdle();
2453 }
2454}
2455
Shuzhen Wang758c2152017-01-10 18:26:18 -08002456status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002457 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002458 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002459 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2460 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002461
2462 if (surfaceIds == nullptr) {
2463 return BAD_VALUE;
2464 }
2465
Zhijun He5d677d12016-05-29 16:52:39 -07002466 Mutex::Autolock il(mInterfaceLock);
2467 Mutex::Autolock l(mLock);
2468
Shuzhen Wang758c2152017-01-10 18:26:18 -08002469 if (consumers.size() == 0) {
2470 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002471 return BAD_VALUE;
2472 }
2473
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002474 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2475 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002476 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002477 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002478 }
Shuzhen Wang758c2152017-01-10 18:26:18 -08002479 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002480 if (res != OK) {
2481 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2482 return res;
2483 }
2484
Emilian Peev40ead602017-09-26 15:46:36 +01002485 for (auto &consumer : consumers) {
2486 int id = stream->getSurfaceId(consumer);
2487 if (id < 0) {
2488 CLOGE("Invalid surface id!");
2489 return BAD_VALUE;
2490 }
2491 surfaceIds->push_back(id);
2492 }
2493
Shuzhen Wang0129d522016-10-30 22:43:41 -07002494 if (stream->isConsumerConfigurationDeferred()) {
2495 if (!stream->isConfiguring()) {
2496 CLOGE("Stream %d was already fully configured.", streamId);
2497 return INVALID_OPERATION;
2498 }
Zhijun He5d677d12016-05-29 16:52:39 -07002499
Shuzhen Wang0129d522016-10-30 22:43:41 -07002500 res = stream->finishConfiguration();
2501 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002502 // If finishConfiguration fails due to abandoned surface, do not set
2503 // device to error state.
2504 bool isSurfaceAbandoned =
2505 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2506 if (!isSurfaceAbandoned) {
2507 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2508 stream->getId(), strerror(-res), res);
2509 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002510 return res;
2511 }
Zhijun He5d677d12016-05-29 16:52:39 -07002512 }
2513
2514 return OK;
2515}
2516
Emilian Peev40ead602017-09-26 15:46:36 +01002517status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2518 const std::vector<OutputStreamInfo> &outputInfo,
2519 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2520 Mutex::Autolock il(mInterfaceLock);
2521 Mutex::Autolock l(mLock);
2522
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002523 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2524 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002525 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002526 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002527 }
2528
2529 for (const auto &it : removedSurfaceIds) {
2530 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2531 CLOGE("Shared surface still part of a pending request!");
2532 return -EBUSY;
2533 }
2534 }
2535
Emilian Peev40ead602017-09-26 15:46:36 +01002536 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2537 if (res != OK) {
2538 CLOGE("Stream %d failed to update stream (error %d %s) ",
2539 streamId, res, strerror(-res));
2540 if (res == UNKNOWN_ERROR) {
2541 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2542 __FUNCTION__);
2543 }
2544 return res;
2545 }
2546
2547 return res;
2548}
2549
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002550status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2551 Mutex::Autolock il(mInterfaceLock);
2552 Mutex::Autolock l(mLock);
2553
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002554 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2555 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002556 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2557 return BAD_VALUE;
2558 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002559 return stream->dropBuffers(dropping);
2560}
2561
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002562/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002563 * Camera3Device private methods
2564 */
2565
2566sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002567 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002568 ATRACE_CALL();
2569 status_t res;
2570
2571 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002572 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002573
2574 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002575 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002576 if (inputStreams.count > 0) {
2577 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002578 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002579 CLOGE("Request references unknown input stream %d",
2580 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002581 return NULL;
2582 }
2583 // Lazy completion of stream configuration (allocation/registration)
2584 // on first use
2585 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002586 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002587 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002588 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002589 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002590 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002591 return NULL;
2592 }
2593 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002594 // Check if stream prepare is blocking requests.
2595 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002596 CLOGE("Request references an input stream that's being prepared!");
2597 return NULL;
2598 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002599
2600 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002601 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002602 }
2603
2604 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002605 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002606 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002607 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002608 return NULL;
2609 }
2610
2611 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002612 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2613 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002614 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002615 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002616 return NULL;
2617 }
Zhijun He5d677d12016-05-29 16:52:39 -07002618 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002619 auto iter = surfaceMap.find(streams.data.i32[i]);
2620 if (iter != surfaceMap.end()) {
2621 const std::vector<size_t>& surfaces = iter->second;
2622 for (const auto& surface : surfaces) {
2623 if (stream->isConsumerConfigurationDeferred(surface)) {
2624 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2625 "due to deferred consumer", stream->getId(), surface);
2626 return NULL;
2627 }
2628 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002629 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002630 }
2631
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002632 // Lazy completion of stream configuration (allocation/registration)
2633 // on first use
2634 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002635 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002636 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002637 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2638 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002639 return NULL;
2640 }
2641 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002642 // Check if stream prepare is blocking requests.
2643 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002644 CLOGE("Request references an output stream that's being prepared!");
2645 return NULL;
2646 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002647
2648 newRequest->mOutputStreams.push(stream);
2649 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002650 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002651 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002652
2653 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002654}
2655
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002656bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2657 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2658 Size size = mSupportedOpaqueInputSizes[i];
2659 if (size.width == width && size.height == height) {
2660 return true;
2661 }
2662 }
2663
2664 return false;
2665}
2666
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002667void Camera3Device::cancelStreamsConfigurationLocked() {
2668 int res = OK;
2669 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2670 res = mInputStream->cancelConfiguration();
2671 if (res != OK) {
2672 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2673 mInputStream->getId(), strerror(-res), res);
2674 }
2675 }
2676
2677 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002678 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002679 if (outputStream->isConfiguring()) {
2680 res = outputStream->cancelConfiguration();
2681 if (res != OK) {
2682 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2683 outputStream->getId(), strerror(-res), res);
2684 }
2685 }
2686 }
2687
2688 // Return state to that at start of call, so that future configures
2689 // properly clean things up
2690 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2691 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002692
2693 res = mPreparerThread->resume();
2694 if (res != OK) {
2695 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2696 }
2697}
2698
2699bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2700 ATRACE_CALL();
2701 bool ret = false;
2702
2703 Mutex::Autolock il(mInterfaceLock);
2704 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2705
2706 Mutex::Autolock l(mLock);
2707 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2708 if (rc == NO_ERROR) {
2709 mNeedConfig = true;
2710 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2711 if (rc == NO_ERROR) {
2712 ret = true;
2713 mPauseStateNotify = false;
2714 //Moving to active state while holding 'mLock' is important.
2715 //There could be pending calls to 'create-/deleteStream' which
2716 //will trigger another stream configuration while the already
2717 //present streams end up with outstanding buffers that will
2718 //not get drained.
2719 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002720 } else if (rc == DEAD_OBJECT) {
2721 // DEAD_OBJECT can be returned if either the consumer surface is
2722 // abandoned, or the HAL has died.
2723 // - If the HAL has died, configureStreamsLocked call will set
2724 // device to error state,
2725 // - If surface is abandoned, we should not set device to error
2726 // state.
2727 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002728 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002729 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002730 }
2731 } else {
2732 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2733 }
2734
2735 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002736}
2737
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002738status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002739 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002740 ATRACE_CALL();
2741 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002742
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002743 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002744 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002745 return INVALID_OPERATION;
2746 }
2747
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002748 if (operatingMode < 0) {
2749 CLOGE("Invalid operating mode: %d", operatingMode);
2750 return BAD_VALUE;
2751 }
2752
2753 bool isConstrainedHighSpeed =
2754 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2755 operatingMode;
2756
2757 if (mOperatingMode != operatingMode) {
2758 mNeedConfig = true;
2759 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2760 mOperatingMode = operatingMode;
2761 }
2762
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002763 if (!mNeedConfig) {
2764 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2765 return OK;
2766 }
2767
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002768 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2769 // adding a dummy stream instead.
2770 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2771 if (mOutputStreams.size() == 0) {
2772 addDummyStreamLocked();
2773 } else {
2774 tryRemoveDummyStreamLocked();
2775 }
2776
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002777 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002778 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002779
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002780 mPreparerThread->pause();
2781
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002782 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002783 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002784 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2785
2786 Vector<camera3_stream_t*> streams;
2787 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002788 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002789
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002790
2791 if (mInputStream != NULL) {
2792 camera3_stream_t *inputStream;
2793 inputStream = mInputStream->startConfiguration();
2794 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002795 CLOGE("Can't start input stream configuration");
2796 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002797 return INVALID_OPERATION;
2798 }
2799 streams.add(inputStream);
2800 }
2801
2802 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002803
2804 // Don't configure bidi streams twice, nor add them twice to the list
2805 if (mOutputStreams[i].get() ==
2806 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2807
2808 config.num_streams--;
2809 continue;
2810 }
2811
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002812 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002813 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002814 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002815 CLOGE("Can't start output stream configuration");
2816 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002817 return INVALID_OPERATION;
2818 }
2819 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002820
2821 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2822 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002823 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2824 // always occupy the initial entry.
2825 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002826 getJpegBufferSize(outputStream->width, outputStream->height));
2827 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002828 }
2829
2830 config.streams = streams.editArray();
2831
2832 // Do the HAL configuration; will potentially touch stream
2833 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002834
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002835 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002836 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002837 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002838
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002839 if (res == BAD_VALUE) {
2840 // HAL rejected this set of streams as unsupported, clean up config
2841 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002842 CLOGE("Set of requested inputs/outputs not supported by HAL");
2843 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002844 return BAD_VALUE;
2845 } else if (res != OK) {
2846 // Some other kind of error from configure_streams - this is not
2847 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002848 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2849 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002850 return res;
2851 }
2852
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002853 // Finish all stream configuration immediately.
2854 // TODO: Try to relax this later back to lazy completion, which should be
2855 // faster
2856
Igor Murashkin073f8572013-05-02 14:59:28 -07002857 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002858 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002859 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002860 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002861 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002862 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002863 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2864 return DEAD_OBJECT;
2865 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002866 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002867 }
2868 }
2869
2870 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002871 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002872 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002873 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002874 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002875 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002876 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002877 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002878 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2879 return DEAD_OBJECT;
2880 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002881 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002882 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002883 }
2884 }
2885
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002886 // Request thread needs to know to avoid using repeat-last-settings protocol
2887 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002888 if (notifyRequestThread) {
2889 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2890 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002891
Zhijun He90f7c372016-08-16 16:19:43 -07002892 char value[PROPERTY_VALUE_MAX];
2893 property_get("camera.fifo.disable", value, "0");
2894 int32_t disableFifo = atoi(value);
2895 if (disableFifo != 1) {
2896 // Boost priority of request thread to SCHED_FIFO.
2897 pid_t requestThreadTid = mRequestThread->getTid();
2898 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002899 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002900 if (res != OK) {
2901 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2902 strerror(-res), res);
2903 } else {
2904 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2905 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002906 }
2907
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002908 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002909 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2910 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2911 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2912 sessionParams.unlock(newSessionParams);
2913 mSessionParams.unlock(currentSessionParams);
2914 if (updateSessionParams) {
2915 mSessionParams = sessionParams;
2916 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002917
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002918 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002919
Ruben Brunk183f0562015-08-12 12:55:02 -07002920 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2921 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002922
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002923 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002924
Zhijun He0a210512014-07-24 13:45:15 -07002925 // tear down the deleted streams after configure streams.
2926 mDeletedStreams.clear();
2927
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002928 auto rc = mPreparerThread->resume();
2929 if (rc != OK) {
2930 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2931 return rc;
2932 }
2933
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002934 if (mDummyStreamId == NO_STREAM) {
2935 mRequestBufferSM.onStreamsConfigured();
2936 }
2937
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002938 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002939}
2940
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002941status_t Camera3Device::addDummyStreamLocked() {
2942 ATRACE_CALL();
2943 status_t res;
2944
2945 if (mDummyStreamId != NO_STREAM) {
2946 // Should never be adding a second dummy stream when one is already
2947 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002948 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2949 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002950 return INVALID_OPERATION;
2951 }
2952
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002953 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002954
2955 sp<Camera3OutputStreamInterface> dummyStream =
2956 new Camera3DummyStream(mNextStreamId);
2957
2958 res = mOutputStreams.add(mNextStreamId, dummyStream);
2959 if (res < 0) {
2960 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2961 return res;
2962 }
2963
2964 mDummyStreamId = mNextStreamId;
2965 mNextStreamId++;
2966
2967 return OK;
2968}
2969
2970status_t Camera3Device::tryRemoveDummyStreamLocked() {
2971 ATRACE_CALL();
2972 status_t res;
2973
2974 if (mDummyStreamId == NO_STREAM) return OK;
2975 if (mOutputStreams.size() == 1) return OK;
2976
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002977 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002978
2979 // Ok, have a dummy stream and there's at least one other output stream,
2980 // so remove the dummy
2981
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002982 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2983 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002984 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2985 return INVALID_OPERATION;
2986 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002987 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002988
2989 // Free up the stream endpoint so that it can be used by some other stream
2990 res = deletedStream->disconnect();
2991 if (res != OK) {
2992 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2993 // fall through since we want to still list the stream as deleted.
2994 }
2995 mDeletedStreams.add(deletedStream);
2996 mDummyStreamId = NO_STREAM;
2997
2998 return res;
2999}
3000
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003001void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003002 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003003 Mutex::Autolock l(mLock);
3004 va_list args;
3005 va_start(args, fmt);
3006
3007 setErrorStateLockedV(fmt, args);
3008
3009 va_end(args);
3010}
3011
3012void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003013 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003014 Mutex::Autolock l(mLock);
3015 setErrorStateLockedV(fmt, args);
3016}
3017
3018void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3019 va_list args;
3020 va_start(args, fmt);
3021
3022 setErrorStateLockedV(fmt, args);
3023
3024 va_end(args);
3025}
3026
3027void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003028 // Print out all error messages to log
3029 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003030 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003031
3032 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003033 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003034
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003035 mErrorCause = errorCause;
3036
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003037 if (mRequestThread != nullptr) {
3038 mRequestThread->setPaused(true);
3039 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003040 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003041
3042 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003043 sp<NotificationListener> listener = mListener.promote();
3044 if (listener != NULL) {
3045 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003046 CaptureResultExtras());
3047 }
3048
3049 // Save stack trace. View by dumping it later.
3050 CameraTraces::saveTrace();
3051 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003052}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003053
3054/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003055 * In-flight request management
3056 */
3057
Jianing Weicb0652e2014-03-12 18:29:36 -07003058status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003059 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003060 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003061 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003062 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003063 ATRACE_CALL();
3064 Mutex::Autolock l(mInFlightLock);
3065
3066 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003067 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003068 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3069 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003070 if (res < 0) return res;
3071
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003072 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003073 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3074 // avoid a deadlock during reprocess requests.
3075 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003076 if (mStatusTracker != nullptr) {
3077 mStatusTracker->markComponentActive(mInFlightStatusId);
3078 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003079 }
3080
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003081 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003082 return OK;
3083}
3084
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003085void Camera3Device::returnOutputBuffers(
3086 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003087 nsecs_t timestamp, bool timestampIncreasing,
3088 const SurfaceMap& outputSurfaces,
3089 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003090
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003091 for (size_t i = 0; i < numBuffers; i++)
3092 {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003093 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3094 int streamId = stream->getId();
3095 const auto& it = outputSurfaces.find(streamId);
3096 status_t res = OK;
3097 if (it != outputSurfaces.end()) {
3098 res = stream->returnBuffer(
3099 outputBuffers[i], timestamp, timestampIncreasing, it->second);
3100 } else {
3101 res = stream->returnBuffer(
3102 outputBuffers[i], timestamp, timestampIncreasing);
3103 }
3104
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003105 // Note: stream may be deallocated at this point, if this buffer was
3106 // the last reference to it.
3107 if (res != OK) {
3108 ALOGE("Can't return buffer to its stream: %s (%d)",
3109 strerror(-res), res);
3110 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003111
3112 // Long processing consumers can cause returnBuffer timeout for shared stream
3113 // If that happens, cancel the buffer and send a buffer error to client
3114 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3115 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3116 // cancel the buffer
3117 camera3_stream_buffer_t sb = outputBuffers[i];
3118 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
3119 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing);
3120
3121 // notify client buffer error
3122 sp<NotificationListener> listener;
3123 {
3124 Mutex::Autolock l(mOutputLock);
3125 listener = mListener.promote();
3126 }
3127
3128 if (listener != nullptr) {
3129 CaptureResultExtras extras = inResultExtras;
3130 extras.errorStreamId = streamId;
3131 listener->notifyError(
3132 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3133 extras);
3134 }
3135 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003136 }
3137}
3138
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003139void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003140 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003141 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003142 mInFlightMap.removeItemsAt(idx, 1);
3143
3144 // Indicate idle inFlightMap to the status tracker
3145 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003146 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003147 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3148 // avoid a deadlock during reprocess requests.
3149 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003150 if (mStatusTracker != nullptr) {
3151 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3152 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003153 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003154 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003155}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003156
3157void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3158
3159 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3160 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3161
3162 nsecs_t sensorTimestamp = request.sensorTimestamp;
3163 nsecs_t shutterTimestamp = request.shutterTimestamp;
3164
3165 // Check if it's okay to remove the request from InFlightMap:
3166 // In the case of a successful request:
3167 // all input and output buffers, all result metadata, shutter callback
3168 // arrived.
3169 // In the case of a unsuccessful request:
3170 // all input and output buffers arrived.
3171 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003172 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003173 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003174 if (request.stillCapture) {
3175 ATRACE_ASYNC_END("still capture", frameNumber);
3176 }
3177
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003178 ATRACE_ASYNC_END("frame capture", frameNumber);
3179
Shuzhen Wang403044a2017-02-26 23:29:04 -08003180 // Sanity check - if sensor timestamp matches shutter timestamp in the
3181 // case of request having callback.
3182 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003183 sensorTimestamp != shutterTimestamp) {
3184 SET_ERR("sensor timestamp (%" PRId64
3185 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3186 sensorTimestamp, frameNumber, shutterTimestamp);
3187 }
3188
3189 // for an unsuccessful request, it may have pending output buffers to
3190 // return.
3191 assert(request.requestStatus != OK ||
3192 request.pendingOutputBuffers.size() == 0);
3193 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003194 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3195 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003196
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003197 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003198 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3199 }
3200
3201 // Sanity check - if we have too many in-flight frames, something has
3202 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003203 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003204 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003205 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3206 kInFlightWarnLimitHighSpeed) {
3207 CLOGE("In-flight list too large for high speed configuration: %zu",
3208 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003209 }
3210}
3211
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003212void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003213 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003214 { // First return buffers cached in mInFlightMap
3215 Mutex::Autolock l(mInFlightLock);
3216 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3217 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3218 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003219 request.pendingOutputBuffers.size(), 0,
3220 /*timestampIncreasing*/true, request.outputSurfaces,
3221 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003222 }
3223 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003224 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003225 }
3226
3227 // Then return all inflight buffers not returned by HAL
3228 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3229 mInterface->getInflightBufferKeys(&inflightKeys);
3230
3231 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3232 for (auto& pair : inflightKeys) {
3233 int32_t frameNumber = pair.first;
3234 int32_t streamId = pair.second;
3235 buffer_handle_t* buffer;
3236 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3237 if (res != OK) {
3238 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3239 __FUNCTION__, frameNumber, streamId);
3240 continue;
3241 }
3242
3243 camera3_stream_buffer_t streamBuffer;
3244 streamBuffer.buffer = buffer;
3245 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3246 streamBuffer.acquire_fence = -1;
3247 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003248
3249 // First check if the buffer belongs to deleted stream
3250 bool streamDeleted = false;
3251 for (auto& stream : mDeletedStreams) {
3252 if (streamId == stream->getId()) {
3253 streamDeleted = true;
3254 // Return buffer to deleted stream
3255 camera3_stream* halStream = stream->asHalStream();
3256 streamBuffer.stream = halStream;
3257 switch (halStream->stream_type) {
3258 case CAMERA3_STREAM_OUTPUT:
3259 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
3260 if (res != OK) {
3261 ALOGE("%s: Can't return output buffer for frame %d to"
3262 " stream %d: %s (%d)", __FUNCTION__,
3263 frameNumber, streamId, strerror(-res), res);
3264 }
3265 break;
3266 case CAMERA3_STREAM_INPUT:
3267 res = stream->returnInputBuffer(streamBuffer);
3268 if (res != OK) {
3269 ALOGE("%s: Can't return input buffer for frame %d to"
3270 " stream %d: %s (%d)", __FUNCTION__,
3271 frameNumber, streamId, strerror(-res), res);
3272 }
3273 break;
3274 default: // Bi-direcitonal stream is deprecated
3275 ALOGE("%s: stream %d has unknown stream type %d",
3276 __FUNCTION__, streamId, halStream->stream_type);
3277 break;
3278 }
3279 break;
3280 }
3281 }
3282 if (streamDeleted) {
3283 continue;
3284 }
3285
3286 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003287 if (streamId == inputStreamId) {
3288 streamBuffer.stream = mInputStream->asHalStream();
3289 res = mInputStream->returnInputBuffer(streamBuffer);
3290 if (res != OK) {
3291 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003292 " stream %d: %s (%d)", __FUNCTION__,
3293 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003294 }
3295 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003296 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3297 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003298 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3299 continue;
3300 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003301 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003302 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3303 }
3304 }
3305}
3306
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003307void Camera3Device::insertResultLocked(CaptureResult *result,
3308 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003309 if (result == nullptr) return;
3310
Emilian Peev71c73a22017-03-21 16:35:51 +00003311 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3312 result->mMetadata.getAndLock());
3313 set_camera_metadata_vendor_id(meta, mVendorTagId);
3314 result->mMetadata.unlock(meta);
3315
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003316 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3317 (int32_t*)&frameNumber, 1) != OK) {
3318 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3319 return;
3320 }
3321
3322 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3323 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3324 return;
3325 }
3326
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003327 // Valid result, insert into queue
3328 List<CaptureResult>::iterator queuedResult =
3329 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3330 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3331 ", burstId = %" PRId32, __FUNCTION__,
3332 queuedResult->mResultExtras.requestId,
3333 queuedResult->mResultExtras.frameNumber,
3334 queuedResult->mResultExtras.burstId);
3335
3336 mResultSignal.signal();
3337}
3338
3339
3340void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003341 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003342 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003343 Mutex::Autolock l(mOutputLock);
3344
3345 CaptureResult captureResult;
3346 captureResult.mResultExtras = resultExtras;
3347 captureResult.mMetadata = partialResult;
3348
Shuzhen Wang268a1362018-10-16 16:32:59 -07003349 // Fix up result metadata for monochrome camera.
3350 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3351 if (res != OK) {
3352 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3353 return;
3354 }
3355
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003356 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003357}
3358
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003359
3360void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3361 CaptureResultExtras &resultExtras,
3362 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003363 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003364 bool reprocess,
3365 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003366 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003367 if (pendingMetadata.isEmpty())
3368 return;
3369
3370 Mutex::Autolock l(mOutputLock);
3371
3372 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003373 if (reprocess) {
3374 if (frameNumber < mNextReprocessResultFrameNumber) {
3375 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003376 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003377 frameNumber, mNextReprocessResultFrameNumber);
3378 return;
3379 }
3380 mNextReprocessResultFrameNumber = frameNumber + 1;
3381 } else {
3382 if (frameNumber < mNextResultFrameNumber) {
3383 SET_ERR("Out-of-order capture result metadata submitted! "
3384 "(got frame number %d, expecting %d)",
3385 frameNumber, mNextResultFrameNumber);
3386 return;
3387 }
3388 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003389 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003390
3391 CaptureResult captureResult;
3392 captureResult.mResultExtras = resultExtras;
3393 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003394 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003395
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003396 // Append any previous partials to form a complete result
3397 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3398 captureResult.mMetadata.append(collectedPartialResult);
3399 }
3400
3401 captureResult.mMetadata.sort();
3402
3403 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003404 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3405 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003406 SET_ERR("No timestamp provided by HAL for frame %d!",
3407 frameNumber);
3408 return;
3409 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003410 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3411 camera_metadata_entry timestamp =
3412 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3413 if (timestamp.count == 0) {
3414 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3415 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3416 return;
3417 }
3418 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003419
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003420 // Fix up some result metadata to account for HAL-level distortion correction
3421 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3422 if (res != OK) {
3423 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3424 frameNumber, strerror(res), res);
3425 return;
3426 }
Shuzhen Wang268a1362018-10-16 16:32:59 -07003427 // Fix up result metadata for monochrome camera.
3428 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3429 if (res != OK) {
3430 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3431 return;
3432 }
3433 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3434 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3435 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3436 physicalMetadata.mPhysicalCameraMetadata);
3437 if (res != OK) {
3438 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3439 return;
3440 }
3441 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003442
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003443 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3444 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3445
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003446 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003447}
3448
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003449/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003450 * Camera HAL device callback methods
3451 */
3452
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003453void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003454 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003455
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003456 status_t res;
3457
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003458 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003459 if (result->result == NULL && result->num_output_buffers == 0 &&
3460 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003461 SET_ERR("No result data provided by HAL for frame %d",
3462 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003463 return;
3464 }
Zhijun He204e3292014-07-14 17:09:23 -07003465
Zhijun He204e3292014-07-14 17:09:23 -07003466 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003467 result->result != NULL &&
3468 result->partial_result != 1) {
3469 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3470 " if partial result is not supported",
3471 frameNumber, result->partial_result);
3472 return;
3473 }
3474
3475 bool isPartialResult = false;
3476 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003477 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003478
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003479 // Get shutter timestamp and resultExtras from list of in-flight requests,
3480 // where it was added by the shutter notification for this frame. If the
3481 // shutter timestamp isn't received yet, append the output buffers to the
3482 // in-flight request and they will be returned when the shutter timestamp
3483 // arrives. Update the in-flight status and remove the in-flight entry if
3484 // all result data and shutter timestamp have been received.
3485 nsecs_t shutterTimestamp = 0;
3486
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003487 {
3488 Mutex::Autolock l(mInFlightLock);
3489 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3490 if (idx == NAME_NOT_FOUND) {
3491 SET_ERR("Unknown frame number for capture result: %d",
3492 frameNumber);
3493 return;
3494 }
3495 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003496 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3497 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003498 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003499 __FUNCTION__, request.resultExtras.requestId,
3500 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003501 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003502 // Always update the partial count to the latest one if it's not 0
3503 // (buffers only). When framework aggregates adjacent partial results
3504 // into one, the latest partial count will be used.
3505 if (result->partial_result != 0)
3506 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003507
3508 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003509 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003510 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3511 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3512 " the range of [1, %d] when metadata is included in the result",
3513 frameNumber, result->partial_result, mNumPartialResults);
3514 return;
3515 }
3516 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003517 if (isPartialResult && result->num_physcam_metadata) {
3518 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3519 " physical camera result", frameNumber);
3520 return;
3521 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003522 if (isPartialResult) {
3523 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003524 }
3525
Shuzhen Wang4a472662017-02-26 23:29:04 -08003526 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003527 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003528 sendPartialCaptureResult(result->result, request.resultExtras,
3529 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003530 }
3531 }
3532
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003533 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003534 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003535
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003536 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003537 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003538 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3539 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3540 request.physicalCameraIds.size(), result->num_physcam_metadata);
3541 return;
3542 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003543 if (request.haveResultMetadata) {
3544 SET_ERR("Called multiple times with metadata for frame %d",
3545 frameNumber);
3546 return;
3547 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003548 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3549 String8 physicalId(result->physcam_ids[i]);
3550 std::set<String8>::iterator cameraIdIter =
3551 request.physicalCameraIds.find(physicalId);
3552 if (cameraIdIter != request.physicalCameraIds.end()) {
3553 request.physicalCameraIds.erase(cameraIdIter);
3554 } else {
3555 SET_ERR("Total result for frame %d has already returned for camera %s",
3556 frameNumber, physicalId.c_str());
3557 return;
3558 }
3559 }
Zhijun He204e3292014-07-14 17:09:23 -07003560 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003561 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003562 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003563 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003564 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003565 request.haveResultMetadata = true;
3566 }
3567
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003568 uint32_t numBuffersReturned = result->num_output_buffers;
3569 if (result->input_buffer != NULL) {
3570 if (hasInputBufferInRequest) {
3571 numBuffersReturned += 1;
3572 } else {
3573 ALOGW("%s: Input buffer should be NULL if there is no input"
3574 " buffer sent in the request",
3575 __FUNCTION__);
3576 }
3577 }
3578 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003579 if (request.numBuffersLeft < 0) {
3580 SET_ERR("Too many buffers returned for frame %d",
3581 frameNumber);
3582 return;
3583 }
3584
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003585 camera_metadata_ro_entry_t entry;
3586 res = find_camera_metadata_ro_entry(result->result,
3587 ANDROID_SENSOR_TIMESTAMP, &entry);
3588 if (res == OK && entry.count == 1) {
3589 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003590 }
3591
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003592 // If shutter event isn't received yet, append the output buffers to
3593 // the in-flight request. Otherwise, return the output buffers to
3594 // streams.
3595 if (shutterTimestamp == 0) {
3596 request.pendingOutputBuffers.appendArray(result->output_buffers,
3597 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003598 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003599 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003600 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003601 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3602 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003603 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003604
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003605 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003606 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3607 CameraMetadata physicalMetadata;
3608 physicalMetadata.append(result->physcam_metadata[i]);
3609 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3610 physicalMetadata});
3611 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003612 if (shutterTimestamp == 0) {
3613 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003614 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003615 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003616 CameraMetadata metadata;
3617 metadata = result->result;
3618 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003619 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003620 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003621 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003622 }
3623
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003624 removeInFlightRequestIfReadyLocked(idx);
3625 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003626
Zhijun Hef0d962a2014-06-30 10:24:11 -07003627 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003628 if (hasInputBufferInRequest) {
3629 Camera3Stream *stream =
3630 Camera3Stream::cast(result->input_buffer->stream);
3631 res = stream->returnInputBuffer(*(result->input_buffer));
3632 // Note: stream may be deallocated at this point, if this buffer was the
3633 // last reference to it.
3634 if (res != OK) {
3635 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3636 " its stream:%s (%d)", __FUNCTION__,
3637 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003638 }
3639 } else {
3640 ALOGW("%s: Input buffer should be NULL if there is no input"
3641 " buffer sent in the request, skipping input buffer return.",
3642 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003643 }
3644 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003645}
3646
3647void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003648 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003649 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003650 {
3651 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003652 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003653 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003654
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003655 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003656 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003657 return;
3658 }
3659
3660 switch (msg->type) {
3661 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003662 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003663 break;
3664 }
3665 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003666 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003667 break;
3668 }
3669 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003670 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003671 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003672 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003673}
3674
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003675void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003676 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003677 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003678 // Map camera HAL error codes to ICameraDeviceCallback error codes
3679 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003680 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003681 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003682 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003683 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003684 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003685 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003686 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003687 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003688 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003689 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003690 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003691 };
3692
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003693 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003694 ((msg.error_code >= 0) &&
3695 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3696 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003697 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003698
3699 int streamId = 0;
3700 if (msg.error_stream != NULL) {
3701 Camera3Stream *stream =
3702 Camera3Stream::cast(msg.error_stream);
3703 streamId = stream->getId();
3704 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003705 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3706 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003707 streamId, msg.error_code);
3708
3709 CaptureResultExtras resultExtras;
3710 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003711 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003712 // SET_ERR calls notifyError
3713 SET_ERR("Camera HAL reported serious device error");
3714 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003715 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3716 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3717 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003718 {
3719 Mutex::Autolock l(mInFlightLock);
3720 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3721 if (idx >= 0) {
3722 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3723 r.requestStatus = msg.error_code;
3724 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003725 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3726 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3727 errorCode) {
3728 r.skipResultMetadata = true;
3729 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003730 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3731 errorCode) {
3732 // In case of missing result check whether the buffers
3733 // returned. If they returned, then remove inflight
3734 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003735 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3736 // otherwise we are depending on HAL to send the buffers back after
3737 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003738 removeInFlightRequestIfReadyLocked(idx);
3739 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003740 } else {
3741 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003742 ALOGE("Camera %s: %s: cannot find in-flight request on "
3743 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003744 resultExtras.frameNumber);
3745 }
3746 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003747 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003748 if (listener != NULL) {
3749 listener->notifyError(errorCode, resultExtras);
3750 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003751 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003752 }
3753 break;
3754 default:
3755 // SET_ERR calls notifyError
3756 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3757 break;
3758 }
3759}
3760
3761void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003762 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003763 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003764 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003765
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003766 // Set timestamp for the request in the in-flight tracking
3767 // and get the request ID to send upstream
3768 {
3769 Mutex::Autolock l(mInFlightLock);
3770 idx = mInFlightMap.indexOfKey(msg.frame_number);
3771 if (idx >= 0) {
3772 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003773
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003774 // Verify ordering of shutter notifications
3775 {
3776 Mutex::Autolock l(mOutputLock);
3777 // TODO: need to track errors for tighter bounds on expected frame number.
3778 if (r.hasInputBuffer) {
3779 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3780 SET_ERR("Shutter notification out-of-order. Expected "
3781 "notification for frame %d, got frame %d",
3782 mNextReprocessShutterFrameNumber, msg.frame_number);
3783 return;
3784 }
3785 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3786 } else {
3787 if (msg.frame_number < mNextShutterFrameNumber) {
3788 SET_ERR("Shutter notification out-of-order. Expected "
3789 "notification for frame %d, got frame %d",
3790 mNextShutterFrameNumber, msg.frame_number);
3791 return;
3792 }
3793 mNextShutterFrameNumber = msg.frame_number + 1;
3794 }
3795 }
3796
Shuzhen Wang4a472662017-02-26 23:29:04 -08003797 r.shutterTimestamp = msg.timestamp;
3798 if (r.hasCallback) {
3799 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003800 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003801 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003802 // Call listener, if any
3803 if (listener != NULL) {
3804 listener->notifyShutter(r.resultExtras, msg.timestamp);
3805 }
3806 // send pending result and buffers
3807 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3808 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003809 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003810 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003811 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003812 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003813 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3814 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003815 r.pendingOutputBuffers.clear();
3816
3817 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003818 }
3819 }
3820 if (idx < 0) {
3821 SET_ERR("Shutter notification for non-existent frame number %d",
3822 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003823 }
3824}
3825
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003826CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003827 ALOGV("%s", __FUNCTION__);
3828
Igor Murashkin1e479c02013-09-06 16:55:14 -07003829 CameraMetadata retVal;
3830
3831 if (mRequestThread != NULL) {
3832 retVal = mRequestThread->getLatestRequest();
3833 }
3834
Igor Murashkin1e479c02013-09-06 16:55:14 -07003835 return retVal;
3836}
3837
Jianing Weicb0652e2014-03-12 18:29:36 -07003838
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003839void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3840 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3841 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3842}
3843
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003844/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003845 * HalInterface inner class methods
3846 */
3847
Yifan Hongf79b5542017-04-11 14:44:25 -07003848Camera3Device::HalInterface::HalInterface(
3849 sp<ICameraDeviceSession> &session,
3850 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003851 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003852 mRequestMetadataQueue(queue) {
3853 // Check with hardware service manager if we can downcast these interfaces
3854 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003855 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3856 if (castResult_3_5.isOk()) {
3857 mHidlSession_3_5 = castResult_3_5;
3858 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003859 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3860 if (castResult_3_4.isOk()) {
3861 mHidlSession_3_4 = castResult_3_4;
3862 }
3863 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3864 if (castResult_3_3.isOk()) {
3865 mHidlSession_3_3 = castResult_3_3;
3866 }
3867}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003868
Emilian Peev31abd0a2017-05-11 18:37:46 +01003869Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003870
3871Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003872 mHidlSession(other.mHidlSession),
3873 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003874
3875bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003876 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003877}
3878
3879void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003880 mHidlSession_3_4.clear();
3881 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003882 mHidlSession.clear();
3883}
3884
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003885bool Camera3Device::HalInterface::supportBatchRequest() {
3886 return mHidlSession != nullptr;
3887}
3888
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003889status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3890 camera3_request_template_t templateId,
3891 /*out*/ camera_metadata_t **requestTemplate) {
3892 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3893 if (!valid()) return INVALID_OPERATION;
3894 status_t res = OK;
3895
Emilian Peev31abd0a2017-05-11 18:37:46 +01003896 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003897
3898 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003899 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003900 status = s;
3901 if (status == common::V1_0::Status::OK) {
3902 const camera_metadata *r =
3903 reinterpret_cast<const camera_metadata_t*>(request.data());
3904 size_t expectedSize = request.size();
3905 int ret = validate_camera_metadata_structure(r, &expectedSize);
3906 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3907 *requestTemplate = clone_camera_metadata(r);
3908 if (*requestTemplate == nullptr) {
3909 ALOGE("%s: Unable to clone camera metadata received from HAL",
3910 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003911 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003912 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003913 } else {
3914 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3915 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003916 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003917 }
3918 };
3919 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003920 RequestTemplate id;
3921 switch (templateId) {
3922 case CAMERA3_TEMPLATE_PREVIEW:
3923 id = RequestTemplate::PREVIEW;
3924 break;
3925 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3926 id = RequestTemplate::STILL_CAPTURE;
3927 break;
3928 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3929 id = RequestTemplate::VIDEO_RECORD;
3930 break;
3931 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3932 id = RequestTemplate::VIDEO_SNAPSHOT;
3933 break;
3934 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3935 id = RequestTemplate::ZERO_SHUTTER_LAG;
3936 break;
3937 case CAMERA3_TEMPLATE_MANUAL:
3938 id = RequestTemplate::MANUAL;
3939 break;
3940 default:
3941 // Unknown template ID, or this HAL is too old to support it
3942 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003943 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003944 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003945
Emilian Peev31abd0a2017-05-11 18:37:46 +01003946 if (!err.isOk()) {
3947 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3948 res = DEAD_OBJECT;
3949 } else {
3950 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003951 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003952
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003953 return res;
3954}
3955
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003956status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003957 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003958 ATRACE_NAME("CameraHal::configureStreams");
3959 if (!valid()) return INVALID_OPERATION;
3960 status_t res = OK;
3961
Emilian Peev31abd0a2017-05-11 18:37:46 +01003962 // Convert stream config to HIDL
3963 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003964 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3965 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3966 requestedConfiguration3_2.streams.resize(config->num_streams);
3967 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003968 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003969 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3970 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003971 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003972
Emilian Peev31abd0a2017-05-11 18:37:46 +01003973 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3974 cam3stream->setBufferFreedListener(this);
3975 int streamId = cam3stream->getId();
3976 StreamType streamType;
3977 switch (src->stream_type) {
3978 case CAMERA3_STREAM_OUTPUT:
3979 streamType = StreamType::OUTPUT;
3980 break;
3981 case CAMERA3_STREAM_INPUT:
3982 streamType = StreamType::INPUT;
3983 break;
3984 default:
3985 ALOGE("%s: Stream %d: Unsupported stream type %d",
3986 __FUNCTION__, streamId, config->streams[i]->stream_type);
3987 return BAD_VALUE;
3988 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003989 dst3_2.id = streamId;
3990 dst3_2.streamType = streamType;
3991 dst3_2.width = src->width;
3992 dst3_2.height = src->height;
3993 dst3_2.format = mapToPixelFormat(src->format);
3994 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3995 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3996 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3997 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003998 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003999 if (src->physical_camera_id != nullptr) {
4000 dst3_4.physicalCameraId = src->physical_camera_id;
4001 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004002
4003 activeStreams.insert(streamId);
4004 // Create Buffer ID map if necessary
4005 if (mBufferIdMaps.count(streamId) == 0) {
4006 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4007 }
4008 }
4009 // remove BufferIdMap for deleted streams
4010 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4011 int streamId = it->first;
4012 bool active = activeStreams.count(streamId) > 0;
4013 if (!active) {
4014 it = mBufferIdMaps.erase(it);
4015 } else {
4016 ++it;
4017 }
4018 }
4019
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004020 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004021 res = mapToStreamConfigurationMode(
4022 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004023 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004024 if (res != OK) {
4025 return res;
4026 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004027 requestedConfiguration3_2.operationMode = operationMode;
4028 requestedConfiguration3_4.operationMode = operationMode;
4029 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004030 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4031 get_camera_metadata_size(sessionParams));
4032
Emilian Peev31abd0a2017-05-11 18:37:46 +01004033 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004034 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004035 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004036 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004037
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004038 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004039 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4040 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004041 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004042 };
4043
4044 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4045 (hardware::Return<void>& err) -> status_t {
4046 if (!err.isOk()) {
4047 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4048 return DEAD_OBJECT;
4049 }
4050 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4051 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4052 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4053 }
4054 return OK;
4055 };
4056
4057 // See if we have v3.4 or v3.3 HAL
4058 if (mHidlSession_3_5 != nullptr) {
4059 ALOGV("%s: v3.5 device found", __FUNCTION__);
4060 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4061 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4062 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4063 auto err = mHidlSession_3_5->configureStreams_3_5(
4064 requestedConfiguration3_5, configStream34Cb);
4065 res = postprocConfigStream34(err);
4066 if (res != OK) {
4067 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004068 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004069 } else if (mHidlSession_3_4 != nullptr) {
4070 // We do; use v3.4 for the call
4071 ALOGV("%s: v3.4 device found", __FUNCTION__);
4072 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
4073 auto err = mHidlSession_3_4->configureStreams_3_4(
4074 requestedConfiguration3_4, configStream34Cb);
4075 res = postprocConfigStream34(err);
4076 if (res != OK) {
4077 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004078 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004079 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004080 // We do; use v3.3 for the call
4081 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004082 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004083 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004084 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004085 finalConfiguration = halConfiguration;
4086 status = s;
4087 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004088 if (!err.isOk()) {
4089 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4090 return DEAD_OBJECT;
4091 }
4092 } else {
4093 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4094 ALOGV("%s: v3.2 device found", __FUNCTION__);
4095 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004096 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004097 [&status, &finalConfiguration_3_2]
4098 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4099 finalConfiguration_3_2 = halConfiguration;
4100 status = s;
4101 });
4102 if (!err.isOk()) {
4103 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4104 return DEAD_OBJECT;
4105 }
4106 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4107 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4108 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4109 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004110 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004111 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004112 }
4113
4114 if (status != common::V1_0::Status::OK ) {
4115 return CameraProviderManager::mapToStatusT(status);
4116 }
4117
4118 // And convert output stream configuration from HIDL
4119
4120 for (size_t i = 0; i < config->num_streams; i++) {
4121 camera3_stream_t *dst = config->streams[i];
4122 int streamId = Camera3Stream::cast(dst)->getId();
4123
4124 // Start scan at i, with the assumption that the stream order matches
4125 size_t realIdx = i;
4126 bool found = false;
4127 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004128 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004129 found = true;
4130 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004131 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004132 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4133 }
4134 if (!found) {
4135 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4136 __FUNCTION__, streamId);
4137 return INVALID_OPERATION;
4138 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004139 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004140
Emilian Peev710c1422017-08-30 11:19:38 +01004141 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4142 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004143 dstStream->setDataSpaceOverride(false);
4144 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4145 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4146
Emilian Peev31abd0a2017-05-11 18:37:46 +01004147 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4148 if (dst->format != overrideFormat) {
4149 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4150 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004151 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004152 if (dst->data_space != overrideDataSpace) {
4153 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4154 streamId, dst->format);
4155 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004156 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004157 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004158 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4159
Emilian Peev31abd0a2017-05-11 18:37:46 +01004160 // Override allowed with IMPLEMENTATION_DEFINED
4161 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004162 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004163 }
4164
Emilian Peev31abd0a2017-05-11 18:37:46 +01004165 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004166 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004167 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004168 __FUNCTION__, streamId);
4169 return INVALID_OPERATION;
4170 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004171 dstStream->setUsage(
4172 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004173 } else {
4174 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004175 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004176 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4177 __FUNCTION__, streamId);
4178 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004179 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004180 dstStream->setUsage(
4181 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004182 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004183 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004184 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004185
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004186 return res;
4187}
4188
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004189void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
4190 /*out*/device::V3_2::CaptureRequest* captureRequest,
4191 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004192 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004193 if (captureRequest == nullptr || handlesCreated == nullptr) {
4194 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4195 __FUNCTION__, captureRequest, handlesCreated);
4196 return;
4197 }
4198
4199 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004200
4201 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004202
4203 {
4204 std::lock_guard<std::mutex> lock(mInflightLock);
4205 if (request->input_buffer != nullptr) {
4206 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4207 buffer_handle_t buf = *(request->input_buffer->buffer);
4208 auto pair = getBufferId(buf, streamId);
4209 bool isNewBuffer = pair.first;
4210 uint64_t bufferId = pair.second;
4211 captureRequest->inputBuffer.streamId = streamId;
4212 captureRequest->inputBuffer.bufferId = bufferId;
4213 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4214 captureRequest->inputBuffer.status = BufferStatus::OK;
4215 native_handle_t *acquireFence = nullptr;
4216 if (request->input_buffer->acquire_fence != -1) {
4217 acquireFence = native_handle_create(1,0);
4218 acquireFence->data[0] = request->input_buffer->acquire_fence;
4219 handlesCreated->push_back(acquireFence);
4220 }
4221 captureRequest->inputBuffer.acquireFence = acquireFence;
4222 captureRequest->inputBuffer.releaseFence = nullptr;
4223
4224 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4225 request->input_buffer->buffer,
4226 request->input_buffer->acquire_fence);
4227 } else {
4228 captureRequest->inputBuffer.streamId = -1;
4229 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4230 }
4231
4232 captureRequest->outputBuffers.resize(request->num_output_buffers);
4233 for (size_t i = 0; i < request->num_output_buffers; i++) {
4234 const camera3_stream_buffer_t *src = request->output_buffers + i;
4235 StreamBuffer &dst = captureRequest->outputBuffers[i];
4236 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
4237 buffer_handle_t buf = *(src->buffer);
4238 auto pair = getBufferId(buf, streamId);
4239 bool isNewBuffer = pair.first;
4240 dst.streamId = streamId;
4241 dst.bufferId = pair.second;
4242 dst.buffer = isNewBuffer ? buf : nullptr;
4243 dst.status = BufferStatus::OK;
4244 native_handle_t *acquireFence = nullptr;
4245 if (src->acquire_fence != -1) {
4246 acquireFence = native_handle_create(1,0);
4247 acquireFence->data[0] = src->acquire_fence;
4248 handlesCreated->push_back(acquireFence);
4249 }
4250 dst.acquireFence = acquireFence;
4251 dst.releaseFence = nullptr;
4252
4253 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4254 src->buffer, src->acquire_fence);
4255 }
4256 }
4257}
4258
4259status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4260 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4261 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4262 if (!valid()) return INVALID_OPERATION;
4263
Emilian Peevaebbe412018-01-15 13:53:24 +00004264 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4265 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4266 if (castResult_3_4.isOk()) {
4267 hidlSession_3_4 = castResult_3_4;
4268 }
4269
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004270 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004271 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004272 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004273 if (hidlSession_3_4 != nullptr) {
4274 captureRequests_3_4.resize(batchSize);
4275 } else {
4276 captureRequests.resize(batchSize);
4277 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004278 std::vector<native_handle_t*> handlesCreated;
4279
4280 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004281 if (hidlSession_3_4 != nullptr) {
4282 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
4283 /*out*/&handlesCreated);
4284 } else {
4285 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
4286 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004287 }
4288
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004289 std::vector<device::V3_2::BufferCache> cachesToRemove;
4290 {
4291 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4292 for (auto& pair : mFreedBuffers) {
4293 // The stream might have been removed since onBufferFreed
4294 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4295 cachesToRemove.push_back({pair.first, pair.second});
4296 }
4297 }
4298 mFreedBuffers.clear();
4299 }
4300
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004301 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4302 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004303
4304 // Write metadata to FMQ.
4305 for (size_t i = 0; i < batchSize; i++) {
4306 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004307 device::V3_2::CaptureRequest* captureRequest;
4308 if (hidlSession_3_4 != nullptr) {
4309 captureRequest = &captureRequests_3_4[i].v3_2;
4310 } else {
4311 captureRequest = &captureRequests[i];
4312 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004313
4314 if (request->settings != nullptr) {
4315 size_t settingsSize = get_camera_metadata_size(request->settings);
4316 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4317 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4318 captureRequest->settings.resize(0);
4319 captureRequest->fmqSettingsSize = settingsSize;
4320 } else {
4321 if (mRequestMetadataQueue != nullptr) {
4322 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4323 }
4324 captureRequest->settings.setToExternal(
4325 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4326 get_camera_metadata_size(request->settings));
4327 captureRequest->fmqSettingsSize = 0u;
4328 }
4329 } else {
4330 // A null request settings maps to a size-0 CameraMetadata
4331 captureRequest->settings.resize(0);
4332 captureRequest->fmqSettingsSize = 0u;
4333 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004334
4335 if (hidlSession_3_4 != nullptr) {
4336 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4337 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004338 if (request->physcam_settings != nullptr) {
4339 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4340 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4341 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4342 settingsSize)) {
4343 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4344 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4345 settingsSize;
4346 } else {
4347 if (mRequestMetadataQueue != nullptr) {
4348 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4349 }
4350 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4351 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4352 request->physcam_settings[j])),
4353 get_camera_metadata_size(request->physcam_settings[j]));
4354 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004355 }
Emilian Peev00420d22018-02-05 21:33:13 +00004356 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004357 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004358 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004359 }
4360 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4361 request->physcam_id[j];
4362 }
4363 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004364 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004365
4366 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004367 auto resultCallback =
4368 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4369 status = s;
4370 *numRequestProcessed = n;
4371 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004372 if (hidlSession_3_4 != nullptr) {
4373 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004374 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004375 } else {
4376 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004377 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004378 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004379 if (!err.isOk()) {
4380 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4381 return DEAD_OBJECT;
4382 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004383 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4384 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4385 __FUNCTION__, *numRequestProcessed, batchSize);
4386 status = common::V1_0::Status::INTERNAL_ERROR;
4387 }
4388
4389 for (auto& handle : handlesCreated) {
4390 native_handle_delete(handle);
4391 }
4392 return CameraProviderManager::mapToStatusT(status);
4393}
4394
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004395status_t Camera3Device::HalInterface::processCaptureRequest(
4396 camera3_capture_request_t *request) {
4397 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004398 if (!valid()) return INVALID_OPERATION;
4399 status_t res = OK;
4400
Emilian Peev31abd0a2017-05-11 18:37:46 +01004401 uint32_t numRequestProcessed = 0;
4402 std::vector<camera3_capture_request_t*> requests(1);
4403 requests[0] = request;
4404 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4405
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004406 return res;
4407}
4408
4409status_t Camera3Device::HalInterface::flush() {
4410 ATRACE_NAME("CameraHal::flush");
4411 if (!valid()) return INVALID_OPERATION;
4412 status_t res = OK;
4413
Emilian Peev31abd0a2017-05-11 18:37:46 +01004414 auto err = mHidlSession->flush();
4415 if (!err.isOk()) {
4416 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4417 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004418 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004419 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004420 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004421
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004422 return res;
4423}
4424
Emilian Peev31abd0a2017-05-11 18:37:46 +01004425status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004426 ATRACE_NAME("CameraHal::dump");
4427 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004428
Emilian Peev31abd0a2017-05-11 18:37:46 +01004429 // Handled by CameraProviderManager::dump
4430
4431 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004432}
4433
4434status_t Camera3Device::HalInterface::close() {
4435 ATRACE_NAME("CameraHal::close()");
4436 if (!valid()) return INVALID_OPERATION;
4437 status_t res = OK;
4438
Emilian Peev31abd0a2017-05-11 18:37:46 +01004439 auto err = mHidlSession->close();
4440 // Interface will be dead shortly anyway, so don't log errors
4441 if (!err.isOk()) {
4442 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004443 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004444
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004445 return res;
4446}
4447
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004448void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4449 ATRACE_NAME("CameraHal::signalPipelineDrain");
4450 if (!valid() || mHidlSession_3_5 == nullptr) {
4451 ALOGE("%s called on invalid camera!", __FUNCTION__);
4452 return;
4453 }
4454
4455 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter);
4456 if (!err.isOk()) {
4457 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4458 return;
4459 }
4460}
4461
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004462void Camera3Device::HalInterface::getInflightBufferKeys(
4463 std::vector<std::pair<int32_t, int32_t>>* out) {
4464 std::lock_guard<std::mutex> lock(mInflightLock);
4465 out->clear();
4466 out->reserve(mInflightBufferMap.size());
4467 for (auto& pair : mInflightBufferMap) {
4468 uint64_t key = pair.first;
4469 int32_t streamId = key & 0xFFFFFFFF;
4470 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4471 out->push_back(std::make_pair(frameNumber, streamId));
4472 }
4473 return;
4474}
4475
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004476status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004477 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004478 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004479 auto pair = std::make_pair(buffer, acquireFence);
4480 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004481 return OK;
4482}
4483
4484status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004485 int32_t frameNumber, int32_t streamId,
4486 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004487 std::lock_guard<std::mutex> lock(mInflightLock);
4488
4489 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4490 auto it = mInflightBufferMap.find(key);
4491 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004492 auto pair = it->second;
4493 *buffer = pair.first;
4494 int acquireFence = pair.second;
4495 if (acquireFence > 0) {
4496 ::close(acquireFence);
4497 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004498 mInflightBufferMap.erase(it);
4499 return OK;
4500}
4501
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004502status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4503 uint64_t bufferId, buffer_handle_t* buf) {
4504 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4505 auto pair = mRequestedBuffers.insert({bufferId, buf});
4506 if (!pair.second) {
4507 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4508 __FUNCTION__, bufferId);
4509 return BAD_VALUE;
4510 }
4511 return OK;
4512}
4513
4514// Find and pop a buffer_handle_t based on bufferId
4515status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4516 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4517 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4518 auto it = mRequestedBuffers.find(bufferId);
4519 if (it == mRequestedBuffers.end()) {
4520 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4521 __FUNCTION__, bufferId);
4522 return BAD_VALUE;
4523 }
4524 *buffer = it->second;
4525 mRequestedBuffers.erase(it);
4526 return OK;
4527}
4528
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004529std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4530 const buffer_handle_t& buf, int streamId) {
4531 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4532
4533 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4534 auto it = bIdMap.find(buf);
4535 if (it == bIdMap.end()) {
4536 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004537 ALOGV("stream %d now have %zu buffer caches, buf %p",
4538 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004539 return std::make_pair(true, mNextBufferId - 1);
4540 } else {
4541 return std::make_pair(false, it->second);
4542 }
4543}
4544
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004545void Camera3Device::HalInterface::onBufferFreed(
4546 int streamId, const native_handle_t* handle) {
4547 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4548 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4549 auto mapIt = mBufferIdMaps.find(streamId);
4550 if (mapIt == mBufferIdMaps.end()) {
4551 // streamId might be from a deleted stream here
4552 ALOGI("%s: stream %d has been removed",
4553 __FUNCTION__, streamId);
4554 return;
4555 }
4556 BufferIdMap& bIdMap = mapIt->second;
4557 auto it = bIdMap.find(handle);
4558 if (it == bIdMap.end()) {
4559 ALOGW("%s: cannot find buffer %p in stream %d",
4560 __FUNCTION__, handle, streamId);
4561 return;
4562 } else {
4563 bufferId = it->second;
4564 bIdMap.erase(it);
4565 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4566 __FUNCTION__, streamId, bIdMap.size(), handle);
4567 }
4568 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4569}
4570
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004571/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004572 * RequestThread inner class methods
4573 */
4574
4575Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004576 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004577 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4578 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004579 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004580 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004581 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004582 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004583 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004584 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004585 mReconfigured(false),
4586 mDoPause(false),
4587 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004588 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004589 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004590 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004591 mCurrentAfTriggerId(0),
4592 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004593 mRepeatingLastFrameNumber(
4594 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004595 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004596 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004597 mRequestLatency(kRequestLatencyBinSize),
4598 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004599 mLatestSessionParams(sessionParamKeys.size()),
4600 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004601 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004602}
4603
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004604Camera3Device::RequestThread::~RequestThread() {}
4605
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004606void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004607 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004608 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004609 Mutex::Autolock l(mRequestLock);
4610 mListener = listener;
4611}
4612
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004613void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4614 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004615 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004616 Mutex::Autolock l(mRequestLock);
4617 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004618 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004619 // Prepare video stream for high speed recording.
4620 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004621 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004622}
4623
Jianing Wei90e59c92014-03-12 18:29:36 -07004624status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004625 List<sp<CaptureRequest> > &requests,
4626 /*out*/
4627 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004628 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004629 Mutex::Autolock l(mRequestLock);
4630 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4631 ++it) {
4632 mRequestQueue.push_back(*it);
4633 }
4634
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004635 if (lastFrameNumber != NULL) {
4636 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4637 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4638 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4639 *lastFrameNumber);
4640 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004641
Jianing Wei90e59c92014-03-12 18:29:36 -07004642 unpauseForNewRequests();
4643
4644 return OK;
4645}
4646
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004647
4648status_t Camera3Device::RequestThread::queueTrigger(
4649 RequestTrigger trigger[],
4650 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004651 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004652 Mutex::Autolock l(mTriggerMutex);
4653 status_t ret;
4654
4655 for (size_t i = 0; i < count; ++i) {
4656 ret = queueTriggerLocked(trigger[i]);
4657
4658 if (ret != OK) {
4659 return ret;
4660 }
4661 }
4662
4663 return OK;
4664}
4665
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004666const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4667 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004668 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004669 if (d != nullptr) return d->mId;
4670 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004671}
4672
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004673status_t Camera3Device::RequestThread::queueTriggerLocked(
4674 RequestTrigger trigger) {
4675
4676 uint32_t tag = trigger.metadataTag;
4677 ssize_t index = mTriggerMap.indexOfKey(tag);
4678
4679 switch (trigger.getTagType()) {
4680 case TYPE_BYTE:
4681 // fall-through
4682 case TYPE_INT32:
4683 break;
4684 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004685 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4686 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004687 return INVALID_OPERATION;
4688 }
4689
4690 /**
4691 * Collect only the latest trigger, since we only have 1 field
4692 * in the request settings per trigger tag, and can't send more than 1
4693 * trigger per request.
4694 */
4695 if (index != NAME_NOT_FOUND) {
4696 mTriggerMap.editValueAt(index) = trigger;
4697 } else {
4698 mTriggerMap.add(tag, trigger);
4699 }
4700
4701 return OK;
4702}
4703
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004704status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004705 const RequestList &requests,
4706 /*out*/
4707 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004708 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004709 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004710 if (lastFrameNumber != NULL) {
4711 *lastFrameNumber = mRepeatingLastFrameNumber;
4712 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004713 mRepeatingRequests.clear();
4714 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4715 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004716
4717 unpauseForNewRequests();
4718
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004719 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004720 return OK;
4721}
4722
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004723bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004724 if (mRepeatingRequests.empty()) {
4725 return false;
4726 }
4727 int32_t requestId = requestIn->mResultExtras.requestId;
4728 const RequestList &repeatRequests = mRepeatingRequests;
4729 // All repeating requests are guaranteed to have same id so only check first quest
4730 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4731 return (firstRequest->mResultExtras.requestId == requestId);
4732}
4733
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004734status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004735 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004736 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004737 return clearRepeatingRequestsLocked(lastFrameNumber);
4738
4739}
4740
4741status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004742 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004743 if (lastFrameNumber != NULL) {
4744 *lastFrameNumber = mRepeatingLastFrameNumber;
4745 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004746 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004747 return OK;
4748}
4749
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004750status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004751 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004752 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004753 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004754 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004755
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004756 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004757
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004758 // Send errors for all requests pending in the request queue, including
4759 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004760 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004761 if (listener != NULL) {
4762 for (RequestList::iterator it = mRequestQueue.begin();
4763 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004764 // Abort the input buffers for reprocess requests.
4765 if ((*it)->mInputStream != NULL) {
4766 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004767 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4768 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004769 if (res != OK) {
4770 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4771 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4772 } else {
4773 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4774 if (res != OK) {
4775 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4776 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4777 }
4778 }
4779 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004780 // Set the frame number this request would have had, if it
4781 // had been submitted; this frame number will not be reused.
4782 // The requestId and burstId fields were set when the request was
4783 // submitted originally (in convertMetadataListToRequestListLocked)
4784 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004785 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004786 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004787 }
4788 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004789 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004790
4791 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004792 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004793 if (lastFrameNumber != NULL) {
4794 *lastFrameNumber = mRepeatingLastFrameNumber;
4795 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004796 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004797 return OK;
4798}
4799
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004800status_t Camera3Device::RequestThread::flush() {
4801 ATRACE_CALL();
4802 Mutex::Autolock l(mFlushLock);
4803
Emilian Peev08dd2452017-04-06 16:55:14 +01004804 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004805}
4806
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004807void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004808 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004809 Mutex::Autolock l(mPauseLock);
4810 mDoPause = paused;
4811 mDoPauseSignal.signal();
4812}
4813
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004814status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4815 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004816 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004817 Mutex::Autolock l(mLatestRequestMutex);
4818 status_t res;
4819 while (mLatestRequestId != requestId) {
4820 nsecs_t startTime = systemTime();
4821
4822 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4823 if (res != OK) return res;
4824
4825 timeout -= (systemTime() - startTime);
4826 }
4827
4828 return OK;
4829}
4830
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004831void Camera3Device::RequestThread::requestExit() {
4832 // Call parent to set up shutdown
4833 Thread::requestExit();
4834 // The exit from any possible waits
4835 mDoPauseSignal.signal();
4836 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004837
4838 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4839 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004840}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004841
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004842void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004843 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004844 bool surfaceAbandoned = false;
4845 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004846 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004847 {
4848 Mutex::Autolock l(mRequestLock);
4849 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4850 // repeating requests.
4851 for (const auto& request : mRepeatingRequests) {
4852 for (const auto& s : request->mOutputStreams) {
4853 if (s->isAbandoned()) {
4854 surfaceAbandoned = true;
4855 clearRepeatingRequestsLocked(&lastFrameNumber);
4856 break;
4857 }
4858 }
4859 if (surfaceAbandoned) {
4860 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004861 }
4862 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004863 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004864 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004865
4866 if (listener != NULL && surfaceAbandoned) {
4867 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004868 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004869}
4870
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004871bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004872 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004873 status_t res;
4874 size_t batchSize = mNextRequests.size();
4875 std::vector<camera3_capture_request_t*> requests(batchSize);
4876 uint32_t numRequestProcessed = 0;
4877 for (size_t i = 0; i < batchSize; i++) {
4878 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004879 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004880 }
4881
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004882 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4883
4884 bool triggerRemoveFailed = false;
4885 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4886 for (size_t i = 0; i < numRequestProcessed; i++) {
4887 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4888 nextRequest.submitted = true;
4889
4890
4891 // Update the latest request sent to HAL
4892 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4893 Mutex::Autolock al(mLatestRequestMutex);
4894
4895 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4896 mLatestRequest.acquire(cloned);
4897
4898 sp<Camera3Device> parent = mParent.promote();
4899 if (parent != NULL) {
4900 parent->monitorMetadata(TagMonitor::REQUEST,
4901 nextRequest.halRequest.frame_number,
4902 0, mLatestRequest);
4903 }
4904 }
4905
4906 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004907 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4908 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004909 }
4910
Emilian Peevaebbe412018-01-15 13:53:24 +00004911 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4912
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004913 if (!triggerRemoveFailed) {
4914 // Remove any previously queued triggers (after unlock)
4915 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4916 if (removeTriggerRes != OK) {
4917 triggerRemoveFailed = true;
4918 triggerFailedRequest = nextRequest;
4919 }
4920 }
4921 }
4922
4923 if (triggerRemoveFailed) {
4924 SET_ERR("RequestThread: Unable to remove triggers "
4925 "(capture request %d, HAL device: %s (%d)",
4926 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4927 cleanUpFailedRequests(/*sendRequestError*/ false);
4928 return false;
4929 }
4930
4931 if (res != OK) {
4932 // Should only get a failure here for malformed requests or device-level
4933 // errors, so consider all errors fatal. Bad metadata failures should
4934 // come through notify.
4935 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4936 mNextRequests[numRequestProcessed].halRequest.frame_number,
4937 strerror(-res), res);
4938 cleanUpFailedRequests(/*sendRequestError*/ false);
4939 return false;
4940 }
4941 return true;
4942}
4943
4944bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4945 status_t res;
4946
4947 for (auto& nextRequest : mNextRequests) {
4948 // Submit request and block until ready for next one
4949 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4950 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4951
4952 if (res != OK) {
4953 // Should only get a failure here for malformed requests or device-level
4954 // errors, so consider all errors fatal. Bad metadata failures should
4955 // come through notify.
4956 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4957 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4958 res);
4959 cleanUpFailedRequests(/*sendRequestError*/ false);
4960 return false;
4961 }
4962
4963 // Mark that the request has be submitted successfully.
4964 nextRequest.submitted = true;
4965
4966 // Update the latest request sent to HAL
4967 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4968 Mutex::Autolock al(mLatestRequestMutex);
4969
4970 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4971 mLatestRequest.acquire(cloned);
4972
4973 sp<Camera3Device> parent = mParent.promote();
4974 if (parent != NULL) {
4975 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4976 0, mLatestRequest);
4977 }
4978 }
4979
4980 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004981 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4982 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004983 }
4984
Emilian Peevaebbe412018-01-15 13:53:24 +00004985 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4986
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004987 // Remove any previously queued triggers (after unlock)
4988 res = removeTriggers(mPrevRequest);
4989 if (res != OK) {
4990 SET_ERR("RequestThread: Unable to remove triggers "
4991 "(capture request %d, HAL device: %s (%d)",
4992 nextRequest.halRequest.frame_number, strerror(-res), res);
4993 cleanUpFailedRequests(/*sendRequestError*/ false);
4994 return false;
4995 }
4996 }
4997 return true;
4998}
4999
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005000nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5001 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5002 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5003 find_camera_metadata_ro_entry(request,
5004 ANDROID_CONTROL_AE_MODE,
5005 &e);
5006 if (e.count == 0) return maxExpectedDuration;
5007
5008 switch (e.data.u8[0]) {
5009 case ANDROID_CONTROL_AE_MODE_OFF:
5010 find_camera_metadata_ro_entry(request,
5011 ANDROID_SENSOR_EXPOSURE_TIME,
5012 &e);
5013 if (e.count > 0) {
5014 maxExpectedDuration = e.data.i64[0];
5015 }
5016 find_camera_metadata_ro_entry(request,
5017 ANDROID_SENSOR_FRAME_DURATION,
5018 &e);
5019 if (e.count > 0) {
5020 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5021 }
5022 break;
5023 default:
5024 find_camera_metadata_ro_entry(request,
5025 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5026 &e);
5027 if (e.count > 1) {
5028 maxExpectedDuration = 1e9 / e.data.u8[0];
5029 }
5030 break;
5031 }
5032
5033 return maxExpectedDuration;
5034}
5035
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005036bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5037 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5038 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5039 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5040 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5041 return true;
5042 }
5043
5044 return false;
5045}
5046
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005047bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5048 ATRACE_CALL();
5049 bool updatesDetected = false;
5050
5051 for (auto tag : mSessionParamKeys) {
5052 camera_metadata_ro_entry entry = settings.find(tag);
5053 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
5054
5055 if (entry.count > 0) {
5056 bool isDifferent = false;
5057 if (lastEntry.count > 0) {
5058 // Have a last value, compare to see if changed
5059 if (lastEntry.type == entry.type &&
5060 lastEntry.count == entry.count) {
5061 // Same type and count, compare values
5062 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5063 size_t entryBytes = bytesPerValue * lastEntry.count;
5064 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5065 if (cmp != 0) {
5066 isDifferent = true;
5067 }
5068 } else {
5069 // Count or type has changed
5070 isDifferent = true;
5071 }
5072 } else {
5073 // No last entry, so always consider to be different
5074 isDifferent = true;
5075 }
5076
5077 if (isDifferent) {
5078 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005079 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5080 updatesDetected = true;
5081 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005082 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005083 }
5084 } else if (lastEntry.count > 0) {
5085 // Value has been removed
5086 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
5087 mLatestSessionParams.erase(tag);
5088 updatesDetected = true;
5089 }
5090 }
5091
5092 return updatesDetected;
5093}
5094
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005095bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005096 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005097 status_t res;
5098
5099 // Handle paused state.
5100 if (waitIfPaused()) {
5101 return true;
5102 }
5103
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005104 // Wait for the next batch of requests.
5105 waitForNextRequestBatch();
5106 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005107 return true;
5108 }
5109
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005110 // Get the latest request ID, if any
5111 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005112 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005113 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005114 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005115 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005116 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005117 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5118 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005119 }
5120
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005121 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5122 // or a single request from streaming or burst. In either case the first element
5123 // should contain the latest camera settings that we need to check for any session
5124 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005125 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005126 res = OK;
5127
5128 //Input stream buffers are already acquired at this point so an input stream
5129 //will not be able to move to idle state unless we force it.
5130 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5131 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5132 if (res != OK) {
5133 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5134 cleanUpFailedRequests(/*sendRequestError*/ false);
5135 return false;
5136 }
5137 }
5138
5139 if (res == OK) {
5140 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5141 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005142 sp<Camera3Device> parent = mParent.promote();
5143 if (parent != nullptr) {
5144 parent->pauseStateNotify(true);
5145 }
5146
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005147 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5148
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005149 if (parent != nullptr) {
5150 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5151 }
5152
5153 statusTracker->markComponentActive(mStatusId);
5154 setPaused(false);
5155 }
5156
5157 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5158 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5159 if (res != OK) {
5160 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5161 cleanUpFailedRequests(/*sendRequestError*/ false);
5162 return false;
5163 }
5164 }
5165 }
5166 }
5167
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005168 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005169 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005170 if (res == TIMED_OUT) {
5171 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005172 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005173 // Check if any stream is abandoned.
5174 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005175 return true;
5176 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005177 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005178 return false;
5179 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005180
Zhijun Hecc27e112013-10-03 16:12:43 -07005181 // Inform waitUntilRequestProcessed thread of a new request ID
5182 {
5183 Mutex::Autolock al(mLatestRequestMutex);
5184
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005185 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005186 mLatestRequestSignal.signal();
5187 }
5188
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005189 // Submit a batch of requests to HAL.
5190 // Use flush lock only when submitting multilple requests in a batch.
5191 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5192 // which may take a long time to finish so synchronizing flush() and
5193 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5194 // For now, only synchronize for high speed recording and we should figure something out for
5195 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005196 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005197
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005198 if (useFlushLock) {
5199 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005200 }
5201
Zhijun Hef0645c12016-08-02 00:58:11 -07005202 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005203 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005204
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005205 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005206 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005207 if (mInterface->supportBatchRequest()) {
5208 submitRequestSuccess = sendRequestsBatch();
5209 } else {
5210 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005211 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005212 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5213 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005214
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005215 if (submitRequestSuccess) {
5216 sp<Camera3Device> parent = mParent.promote();
5217 if (parent != nullptr) {
5218 parent->mRequestBufferSM.onRequestSubmitted();
5219 }
5220 }
5221
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005222 if (useFlushLock) {
5223 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005224 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005225
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005226 // Unset as current request
5227 {
5228 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005229 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005230 }
5231
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005232 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005233}
5234
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005235status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005236 ATRACE_CALL();
5237
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005238 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005239 for (size_t i = 0; i < mNextRequests.size(); i++) {
5240 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005241 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5242 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5243 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5244
5245 // Prepare a request to HAL
5246 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5247
5248 // Insert any queued triggers (before metadata is locked)
5249 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005250 if (res < 0) {
5251 SET_ERR("RequestThread: Unable to insert triggers "
5252 "(capture request %d, HAL device: %s (%d)",
5253 halRequest->frame_number, strerror(-res), res);
5254 return INVALID_OPERATION;
5255 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005256
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005257 int triggerCount = res;
5258 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5259 mPrevTriggers = triggerCount;
5260
5261 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005262 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5263 // Request settings are all the same within one batch, so only treat the first
5264 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005265 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005266 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005267 /**
5268 * HAL workaround:
5269 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5270 */
5271 res = addDummyTriggerIds(captureRequest);
5272 if (res != OK) {
5273 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5274 "(capture request %d, HAL device: %s (%d)",
5275 halRequest->frame_number, strerror(-res), res);
5276 return INVALID_OPERATION;
5277 }
5278
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005279 {
5280 // Correct metadata regions for distortion correction if enabled
5281 sp<Camera3Device> parent = mParent.promote();
5282 if (parent != nullptr) {
5283 res = parent->mDistortionMapper.correctCaptureRequest(
5284 &(captureRequest->mSettingsList.begin()->metadata));
5285 if (res != OK) {
5286 SET_ERR("RequestThread: Unable to correct capture requests "
5287 "for lens distortion for request %d: %s (%d)",
5288 halRequest->frame_number, strerror(-res), res);
5289 return INVALID_OPERATION;
5290 }
5291 }
5292 }
5293
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005294 /**
5295 * The request should be presorted so accesses in HAL
5296 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5297 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005298 captureRequest->mSettingsList.begin()->metadata.sort();
5299 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005300 mPrevRequest = captureRequest;
5301 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5302
5303 IF_ALOGV() {
5304 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5305 find_camera_metadata_ro_entry(
5306 halRequest->settings,
5307 ANDROID_CONTROL_AF_TRIGGER,
5308 &e
5309 );
5310 if (e.count > 0) {
5311 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5312 __FUNCTION__,
5313 halRequest->frame_number,
5314 e.data.u8[0]);
5315 }
5316 }
5317 } else {
5318 // leave request.settings NULL to indicate 'reuse latest given'
5319 ALOGVV("%s: Request settings are REUSED",
5320 __FUNCTION__);
5321 }
5322
Emilian Peevaebbe412018-01-15 13:53:24 +00005323 if (captureRequest->mSettingsList.size() > 1) {
5324 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5325 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005326 if (newRequest) {
5327 halRequest->physcam_settings =
5328 new const camera_metadata* [halRequest->num_physcam_settings];
5329 } else {
5330 halRequest->physcam_settings = nullptr;
5331 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005332 auto it = ++captureRequest->mSettingsList.begin();
5333 size_t i = 0;
5334 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5335 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005336 if (newRequest) {
5337 it->metadata.sort();
5338 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5339 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005340 }
5341 }
5342
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005343 uint32_t totalNumBuffers = 0;
5344
5345 // Fill in buffers
5346 if (captureRequest->mInputStream != NULL) {
5347 halRequest->input_buffer = &captureRequest->mInputBuffer;
5348 totalNumBuffers += 1;
5349 } else {
5350 halRequest->input_buffer = NULL;
5351 }
5352
5353 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5354 captureRequest->mOutputStreams.size());
5355 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005356 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005357
5358 sp<Camera3Device> parent = mParent.promote();
5359 if (parent == NULL) {
5360 // Should not happen, and nowhere to send errors to, so just log it
5361 CLOGE("RequestThread: Parent is gone");
5362 return INVALID_OPERATION;
5363 }
5364 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5365
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005366 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005367 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005368 sp<Camera3OutputStreamInterface> outputStream =
5369 captureRequest->mOutputStreams.editItemAt(j);
5370 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005371
5372 // Prepare video buffers for high speed recording on the first video request.
5373 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5374 // Only try to prepare video stream on the first video request.
5375 mPrepareVideoStream = false;
5376
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005377 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5378 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005379 while (res == NOT_ENOUGH_DATA) {
5380 res = outputStream->prepareNextBuffer();
5381 }
5382 if (res != OK) {
5383 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5384 __FUNCTION__, strerror(-res), res);
5385 outputStream->cancelPrepare();
5386 }
5387 }
5388
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005389 std::vector<size_t> uniqueSurfaceIds;
5390 res = outputStream->getUniqueSurfaceIds(
5391 captureRequest->mOutputSurfaces[streamId],
5392 &uniqueSurfaceIds);
5393 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5394 if (res != OK && res != INVALID_OPERATION) {
5395 ALOGE("%s: failed to query stream %d unique surface IDs",
5396 __FUNCTION__, streamId);
5397 return res;
5398 }
5399 if (res == OK) {
5400 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5401 }
5402
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005403 if (mUseHalBufManager) {
5404 // HAL will request buffer through requestStreamBuffer API
5405 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5406 buffer.stream = outputStream->asHalStream();
5407 buffer.buffer = nullptr;
5408 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5409 buffer.acquire_fence = -1;
5410 buffer.release_fence = -1;
5411 } else {
5412 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5413 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005414 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005415 if (res != OK) {
5416 // Can't get output buffer from gralloc queue - this could be due to
5417 // abandoned queue or other consumer misbehavior, so not a fatal
5418 // error
5419 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5420 " %s (%d)", strerror(-res), res);
5421
5422 return TIMED_OUT;
5423 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005424 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005425
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005426 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5427
5428 if (!physicalCameraId.isEmpty()) {
5429 // Physical stream isn't supported for input request.
5430 if (halRequest->input_buffer) {
5431 CLOGE("Physical stream is not supported for input request");
5432 return INVALID_OPERATION;
5433 }
5434 requestedPhysicalCameras.insert(physicalCameraId);
5435 }
5436 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005437 }
5438 totalNumBuffers += halRequest->num_output_buffers;
5439
5440 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005441 // If this request list is for constrained high speed recording (not
5442 // preview), and the current request is not the last one in the batch,
5443 // do not send callback to the app.
5444 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005445 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005446 hasCallback = false;
5447 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005448 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005449 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005450 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5451 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5452 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5453 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5454 isStillCapture = true;
5455 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5456 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005457
5458 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5459 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5460 isZslCapture = true;
5461 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005462 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005463 res = parent->registerInFlight(halRequest->frame_number,
5464 totalNumBuffers, captureRequest->mResultExtras,
5465 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005466 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005467 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005468 requestedPhysicalCameras, isStillCapture, isZslCapture,
5469 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5470 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005471 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5472 ", burstId = %" PRId32 ".",
5473 __FUNCTION__,
5474 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5475 captureRequest->mResultExtras.burstId);
5476 if (res != OK) {
5477 SET_ERR("RequestThread: Unable to register new in-flight request:"
5478 " %s (%d)", strerror(-res), res);
5479 return INVALID_OPERATION;
5480 }
5481 }
5482
5483 return OK;
5484}
5485
Igor Murashkin1e479c02013-09-06 16:55:14 -07005486CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005487 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005488 Mutex::Autolock al(mLatestRequestMutex);
5489
5490 ALOGV("RequestThread::%s", __FUNCTION__);
5491
5492 return mLatestRequest;
5493}
5494
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005495bool Camera3Device::RequestThread::isStreamPending(
5496 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005497 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005498 Mutex::Autolock l(mRequestLock);
5499
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005500 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005501 if (!nextRequest.submitted) {
5502 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5503 if (stream == s) return true;
5504 }
5505 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005506 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005507 }
5508
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005509 for (const auto& request : mRequestQueue) {
5510 for (const auto& s : request->mOutputStreams) {
5511 if (stream == s) return true;
5512 }
5513 if (stream == request->mInputStream) return true;
5514 }
5515
5516 for (const auto& request : mRepeatingRequests) {
5517 for (const auto& s : request->mOutputStreams) {
5518 if (stream == s) return true;
5519 }
5520 if (stream == request->mInputStream) return true;
5521 }
5522
5523 return false;
5524}
Jianing Weicb0652e2014-03-12 18:29:36 -07005525
Emilian Peev40ead602017-09-26 15:46:36 +01005526bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5527 ATRACE_CALL();
5528 Mutex::Autolock l(mRequestLock);
5529
5530 for (const auto& nextRequest : mNextRequests) {
5531 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5532 if (s.first == streamId) {
5533 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5534 if (it != s.second.end()) {
5535 return true;
5536 }
5537 }
5538 }
5539 }
5540
5541 for (const auto& request : mRequestQueue) {
5542 for (const auto& s : request->mOutputSurfaces) {
5543 if (s.first == streamId) {
5544 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5545 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005546 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005547 }
5548 }
5549 }
5550 }
5551
5552 for (const auto& request : mRepeatingRequests) {
5553 for (const auto& s : request->mOutputSurfaces) {
5554 if (s.first == streamId) {
5555 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5556 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005557 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005558 }
5559 }
5560 }
5561 }
5562
5563 return false;
5564}
5565
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005566void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5567 if (!mUseHalBufManager) {
5568 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5569 return;
5570 }
5571
5572 Mutex::Autolock pl(mPauseLock);
5573 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005574 mInterface->signalPipelineDrain(streamIds);
5575 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005576 }
5577 // If request thread is still busy, wait until paused then notify HAL
5578 mNotifyPipelineDrain = true;
5579 mStreamIdsToBeDrained = streamIds;
5580}
5581
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005582nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005583 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005584 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005585 return mExpectedInflightDuration > kMinInflightDuration ?
5586 mExpectedInflightDuration : kMinInflightDuration;
5587}
5588
Emilian Peevaebbe412018-01-15 13:53:24 +00005589void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5590 camera3_capture_request_t *halRequest) {
5591 if ((request == nullptr) || (halRequest == nullptr)) {
5592 ALOGE("%s: Invalid request!", __FUNCTION__);
5593 return;
5594 }
5595
5596 if (halRequest->num_physcam_settings > 0) {
5597 if (halRequest->physcam_id != nullptr) {
5598 delete [] halRequest->physcam_id;
5599 halRequest->physcam_id = nullptr;
5600 }
5601 if (halRequest->physcam_settings != nullptr) {
5602 auto it = ++(request->mSettingsList.begin());
5603 size_t i = 0;
5604 for (; it != request->mSettingsList.end(); it++, i++) {
5605 it->metadata.unlock(halRequest->physcam_settings[i]);
5606 }
5607 delete [] halRequest->physcam_settings;
5608 halRequest->physcam_settings = nullptr;
5609 }
5610 }
5611}
5612
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005613void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5614 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005615 return;
5616 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005617
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005618 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005619 // Skip the ones that have been submitted successfully.
5620 if (nextRequest.submitted) {
5621 continue;
5622 }
5623
5624 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5625 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5626 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5627
5628 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005629 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005630 }
5631
Emilian Peevaebbe412018-01-15 13:53:24 +00005632 cleanupPhysicalSettings(captureRequest, halRequest);
5633
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005634 if (captureRequest->mInputStream != NULL) {
5635 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5636 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5637 }
5638
5639 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005640 //Buffers that failed processing could still have
5641 //valid acquire fence.
5642 int acquireFence = (*outputBuffers)[i].acquire_fence;
5643 if (0 <= acquireFence) {
5644 close(acquireFence);
5645 outputBuffers->editItemAt(i).acquire_fence = -1;
5646 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005647 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5648 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5649 }
5650
5651 if (sendRequestError) {
5652 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005653 sp<NotificationListener> listener = mListener.promote();
5654 if (listener != NULL) {
5655 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005656 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005657 captureRequest->mResultExtras);
5658 }
5659 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005660
5661 // Remove yet-to-be submitted inflight request from inflightMap
5662 {
5663 sp<Camera3Device> parent = mParent.promote();
5664 if (parent != NULL) {
5665 Mutex::Autolock l(parent->mInFlightLock);
5666 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5667 if (idx >= 0) {
5668 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5669 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5670 parent->removeInFlightMapEntryLocked(idx);
5671 }
5672 }
5673 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005674 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005675
5676 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005677 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005678}
5679
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005680void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005681 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005682 // Optimized a bit for the simple steady-state case (single repeating
5683 // request), to avoid putting that request in the queue temporarily.
5684 Mutex::Autolock l(mRequestLock);
5685
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005686 assert(mNextRequests.empty());
5687
5688 NextRequest nextRequest;
5689 nextRequest.captureRequest = waitForNextRequestLocked();
5690 if (nextRequest.captureRequest == nullptr) {
5691 return;
5692 }
5693
5694 nextRequest.halRequest = camera3_capture_request_t();
5695 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005696 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005697
5698 // Wait for additional requests
5699 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5700
5701 for (size_t i = 1; i < batchSize; i++) {
5702 NextRequest additionalRequest;
5703 additionalRequest.captureRequest = waitForNextRequestLocked();
5704 if (additionalRequest.captureRequest == nullptr) {
5705 break;
5706 }
5707
5708 additionalRequest.halRequest = camera3_capture_request_t();
5709 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005710 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005711 }
5712
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005713 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005714 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005715 mNextRequests.size(), batchSize);
5716 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005717 }
5718
5719 return;
5720}
5721
5722sp<Camera3Device::CaptureRequest>
5723 Camera3Device::RequestThread::waitForNextRequestLocked() {
5724 status_t res;
5725 sp<CaptureRequest> nextRequest;
5726
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005727 while (mRequestQueue.empty()) {
5728 if (!mRepeatingRequests.empty()) {
5729 // Always atomically enqueue all requests in a repeating request
5730 // list. Guarantees a complete in-sequence set of captures to
5731 // application.
5732 const RequestList &requests = mRepeatingRequests;
5733 RequestList::const_iterator firstRequest =
5734 requests.begin();
5735 nextRequest = *firstRequest;
5736 mRequestQueue.insert(mRequestQueue.end(),
5737 ++firstRequest,
5738 requests.end());
5739 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005740
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005741 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005742
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005743 break;
5744 }
5745
5746 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5747
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005748 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5749 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005750 Mutex::Autolock pl(mPauseLock);
5751 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005752 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005753 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005754 // Let the tracker know
5755 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5756 if (statusTracker != 0) {
5757 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5758 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005759 if (mNotifyPipelineDrain) {
5760 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5761 mNotifyPipelineDrain = false;
5762 mStreamIdsToBeDrained.clear();
5763 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005764 sp<Camera3Device> parent = mParent.promote();
5765 if (parent != nullptr) {
5766 parent->mRequestBufferSM.onRequestThreadPaused();
5767 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005768 }
5769 // Stop waiting for now and let thread management happen
5770 return NULL;
5771 }
5772 }
5773
5774 if (nextRequest == NULL) {
5775 // Don't have a repeating request already in hand, so queue
5776 // must have an entry now.
5777 RequestList::iterator firstRequest =
5778 mRequestQueue.begin();
5779 nextRequest = *firstRequest;
5780 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005781 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5782 sp<NotificationListener> listener = mListener.promote();
5783 if (listener != NULL) {
5784 listener->notifyRequestQueueEmpty();
5785 }
5786 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005787 }
5788
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005789 // In case we've been unpaused by setPaused clearing mDoPause, need to
5790 // update internal pause state (capture/setRepeatingRequest unpause
5791 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005792 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005793 if (mPaused) {
5794 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5795 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5796 if (statusTracker != 0) {
5797 statusTracker->markComponentActive(mStatusId);
5798 }
5799 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005800 mPaused = false;
5801
5802 // Check if we've reconfigured since last time, and reset the preview
5803 // request if so. Can't use 'NULL request == repeat' across configure calls.
5804 if (mReconfigured) {
5805 mPrevRequest.clear();
5806 mReconfigured = false;
5807 }
5808
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005809 if (nextRequest != NULL) {
5810 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005811 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5812 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005813
5814 // Since RequestThread::clear() removes buffers from the input stream,
5815 // get the right buffer here before unlocking mRequestLock
5816 if (nextRequest->mInputStream != NULL) {
5817 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5818 if (res != OK) {
5819 // Can't get input buffer from gralloc queue - this could be due to
5820 // disconnected queue or other producer misbehavior, so not a fatal
5821 // error
5822 ALOGE("%s: Can't get input buffer, skipping request:"
5823 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005824
5825 sp<NotificationListener> listener = mListener.promote();
5826 if (listener != NULL) {
5827 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005828 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005829 nextRequest->mResultExtras);
5830 }
5831 return NULL;
5832 }
5833 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005834 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005835
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005836 return nextRequest;
5837}
5838
5839bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005840 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005841 status_t res;
5842 Mutex::Autolock l(mPauseLock);
5843 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005844 if (mPaused == false) {
5845 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005846 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5847 // Let the tracker know
5848 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5849 if (statusTracker != 0) {
5850 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5851 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005852 if (mNotifyPipelineDrain) {
5853 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5854 mNotifyPipelineDrain = false;
5855 mStreamIdsToBeDrained.clear();
5856 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005857 sp<Camera3Device> parent = mParent.promote();
5858 if (parent != nullptr) {
5859 parent->mRequestBufferSM.onRequestThreadPaused();
5860 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005861 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005862
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005863 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005864 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005865 return true;
5866 }
5867 }
5868 // We don't set mPaused to false here, because waitForNextRequest needs
5869 // to further manage the paused state in case of starvation.
5870 return false;
5871}
5872
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005873void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005874 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005875 // With work to do, mark thread as unpaused.
5876 // If paused by request (setPaused), don't resume, to avoid
5877 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005878 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005879 Mutex::Autolock p(mPauseLock);
5880 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005881 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5882 if (mPaused) {
5883 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5884 if (statusTracker != 0) {
5885 statusTracker->markComponentActive(mStatusId);
5886 }
5887 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005888 mPaused = false;
5889 }
5890}
5891
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005892void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5893 sp<Camera3Device> parent = mParent.promote();
5894 if (parent != NULL) {
5895 va_list args;
5896 va_start(args, fmt);
5897
5898 parent->setErrorStateV(fmt, args);
5899
5900 va_end(args);
5901 }
5902}
5903
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005904status_t Camera3Device::RequestThread::insertTriggers(
5905 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005906 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005907 Mutex::Autolock al(mTriggerMutex);
5908
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005909 sp<Camera3Device> parent = mParent.promote();
5910 if (parent == NULL) {
5911 CLOGE("RequestThread: Parent is gone");
5912 return DEAD_OBJECT;
5913 }
5914
Emilian Peevaebbe412018-01-15 13:53:24 +00005915 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005916 size_t count = mTriggerMap.size();
5917
5918 for (size_t i = 0; i < count; ++i) {
5919 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005920 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005921
5922 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5923 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5924 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005925 if (isAeTrigger) {
5926 request->mResultExtras.precaptureTriggerId = triggerId;
5927 mCurrentPreCaptureTriggerId = triggerId;
5928 } else {
5929 request->mResultExtras.afTriggerId = triggerId;
5930 mCurrentAfTriggerId = triggerId;
5931 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005932 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005933 }
5934
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005935 camera_metadata_entry entry = metadata.find(tag);
5936
5937 if (entry.count > 0) {
5938 /**
5939 * Already has an entry for this trigger in the request.
5940 * Rewrite it with our requested trigger value.
5941 */
5942 RequestTrigger oldTrigger = trigger;
5943
5944 oldTrigger.entryValue = entry.data.u8[0];
5945
5946 mTriggerReplacedMap.add(tag, oldTrigger);
5947 } else {
5948 /**
5949 * More typical, no trigger entry, so we just add it
5950 */
5951 mTriggerRemovedMap.add(tag, trigger);
5952 }
5953
5954 status_t res;
5955
5956 switch (trigger.getTagType()) {
5957 case TYPE_BYTE: {
5958 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5959 res = metadata.update(tag,
5960 &entryValue,
5961 /*count*/1);
5962 break;
5963 }
5964 case TYPE_INT32:
5965 res = metadata.update(tag,
5966 &trigger.entryValue,
5967 /*count*/1);
5968 break;
5969 default:
5970 ALOGE("%s: Type not supported: 0x%x",
5971 __FUNCTION__,
5972 trigger.getTagType());
5973 return INVALID_OPERATION;
5974 }
5975
5976 if (res != OK) {
5977 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5978 ", value %d", __FUNCTION__, trigger.getTagName(),
5979 trigger.entryValue);
5980 return res;
5981 }
5982
5983 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5984 trigger.getTagName(),
5985 trigger.entryValue);
5986 }
5987
5988 mTriggerMap.clear();
5989
5990 return count;
5991}
5992
5993status_t Camera3Device::RequestThread::removeTriggers(
5994 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005995 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005996 Mutex::Autolock al(mTriggerMutex);
5997
Emilian Peevaebbe412018-01-15 13:53:24 +00005998 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005999
6000 /**
6001 * Replace all old entries with their old values.
6002 */
6003 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6004 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6005
6006 status_t res;
6007
6008 uint32_t tag = trigger.metadataTag;
6009 switch (trigger.getTagType()) {
6010 case TYPE_BYTE: {
6011 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6012 res = metadata.update(tag,
6013 &entryValue,
6014 /*count*/1);
6015 break;
6016 }
6017 case TYPE_INT32:
6018 res = metadata.update(tag,
6019 &trigger.entryValue,
6020 /*count*/1);
6021 break;
6022 default:
6023 ALOGE("%s: Type not supported: 0x%x",
6024 __FUNCTION__,
6025 trigger.getTagType());
6026 return INVALID_OPERATION;
6027 }
6028
6029 if (res != OK) {
6030 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6031 ", trigger value %d", __FUNCTION__,
6032 trigger.getTagName(), trigger.entryValue);
6033 return res;
6034 }
6035 }
6036 mTriggerReplacedMap.clear();
6037
6038 /**
6039 * Remove all new entries.
6040 */
6041 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6042 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6043 status_t res = metadata.erase(trigger.metadataTag);
6044
6045 if (res != OK) {
6046 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6047 ", trigger value %d", __FUNCTION__,
6048 trigger.getTagName(), trigger.entryValue);
6049 return res;
6050 }
6051 }
6052 mTriggerRemovedMap.clear();
6053
6054 return OK;
6055}
6056
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006057status_t Camera3Device::RequestThread::addDummyTriggerIds(
6058 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006059 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006060 static const int32_t dummyTriggerId = 1;
6061 status_t res;
6062
Emilian Peevaebbe412018-01-15 13:53:24 +00006063 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006064
6065 // If AF trigger is active, insert a dummy AF trigger ID if none already
6066 // exists
6067 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6068 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6069 if (afTrigger.count > 0 &&
6070 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6071 afId.count == 0) {
6072 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6073 if (res != OK) return res;
6074 }
6075
6076 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6077 // if none already exists
6078 camera_metadata_entry pcTrigger =
6079 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6080 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6081 if (pcTrigger.count > 0 &&
6082 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6083 pcId.count == 0) {
6084 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6085 &dummyTriggerId, 1);
6086 if (res != OK) return res;
6087 }
6088
6089 return OK;
6090}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006091
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006092/**
6093 * PreparerThread inner class methods
6094 */
6095
6096Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006097 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006098 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006099}
6100
6101Camera3Device::PreparerThread::~PreparerThread() {
6102 Thread::requestExitAndWait();
6103 if (mCurrentStream != nullptr) {
6104 mCurrentStream->cancelPrepare();
6105 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6106 mCurrentStream.clear();
6107 }
6108 clear();
6109}
6110
Ruben Brunkc78ac262015-08-13 17:58:46 -07006111status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006112 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006113 status_t res;
6114
6115 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006116 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006117
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006118 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006119 if (res == OK) {
6120 // No preparation needed, fire listener right off
6121 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006122 if (listener != NULL) {
6123 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006124 }
6125 return OK;
6126 } else if (res != NOT_ENOUGH_DATA) {
6127 return res;
6128 }
6129
6130 // Need to prepare, start up thread if necessary
6131 if (!mActive) {
6132 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6133 // isn't running
6134 Thread::requestExitAndWait();
6135 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6136 if (res != OK) {
6137 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006138 if (listener != NULL) {
6139 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006140 }
6141 return res;
6142 }
6143 mCancelNow = false;
6144 mActive = true;
6145 ALOGV("%s: Preparer stream started", __FUNCTION__);
6146 }
6147
6148 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006149 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006150 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6151
6152 return OK;
6153}
6154
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006155void Camera3Device::PreparerThread::pause() {
6156 ATRACE_CALL();
6157
6158 Mutex::Autolock l(mLock);
6159
6160 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6161 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6162 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6163 int currentMaxCount = mCurrentMaxCount;
6164 mPendingStreams.clear();
6165 mCancelNow = true;
6166 while (mActive) {
6167 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6168 if (res == TIMED_OUT) {
6169 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6170 return;
6171 } else if (res != OK) {
6172 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6173 return;
6174 }
6175 }
6176
6177 //Check whether the prepare thread was able to complete the current
6178 //stream. In case work is still pending emplace it along with the rest
6179 //of the streams in the pending list.
6180 if (currentStream != nullptr) {
6181 if (!mCurrentPrepareComplete) {
6182 pendingStreams.emplace(currentMaxCount, currentStream);
6183 }
6184 }
6185
6186 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6187 for (const auto& it : mPendingStreams) {
6188 it.second->cancelPrepare();
6189 }
6190}
6191
6192status_t Camera3Device::PreparerThread::resume() {
6193 ATRACE_CALL();
6194 status_t res;
6195
6196 Mutex::Autolock l(mLock);
6197 sp<NotificationListener> listener = mListener.promote();
6198
6199 if (mActive) {
6200 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6201 return NO_INIT;
6202 }
6203
6204 auto it = mPendingStreams.begin();
6205 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006206 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006207 if (res == OK) {
6208 if (listener != NULL) {
6209 listener->notifyPrepared(it->second->getId());
6210 }
6211 it = mPendingStreams.erase(it);
6212 } else if (res != NOT_ENOUGH_DATA) {
6213 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6214 res, strerror(-res));
6215 it = mPendingStreams.erase(it);
6216 } else {
6217 it++;
6218 }
6219 }
6220
6221 if (mPendingStreams.empty()) {
6222 return OK;
6223 }
6224
6225 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6226 if (res != OK) {
6227 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6228 __FUNCTION__, res, strerror(-res));
6229 return res;
6230 }
6231 mCancelNow = false;
6232 mActive = true;
6233 ALOGV("%s: Preparer stream started", __FUNCTION__);
6234
6235 return OK;
6236}
6237
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006238status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006239 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006240 Mutex::Autolock l(mLock);
6241
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006242 for (const auto& it : mPendingStreams) {
6243 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006244 }
6245 mPendingStreams.clear();
6246 mCancelNow = true;
6247
6248 return OK;
6249}
6250
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006251void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006252 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006253 Mutex::Autolock l(mLock);
6254 mListener = listener;
6255}
6256
6257bool Camera3Device::PreparerThread::threadLoop() {
6258 status_t res;
6259 {
6260 Mutex::Autolock l(mLock);
6261 if (mCurrentStream == nullptr) {
6262 // End thread if done with work
6263 if (mPendingStreams.empty()) {
6264 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6265 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6266 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6267 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006268 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006269 return false;
6270 }
6271
6272 // Get next stream to prepare
6273 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006274 mCurrentStream = it->second;
6275 mCurrentMaxCount = it->first;
6276 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006277 mPendingStreams.erase(it);
6278 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6279 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6280 } else if (mCancelNow) {
6281 mCurrentStream->cancelPrepare();
6282 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6283 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6284 mCurrentStream.clear();
6285 mCancelNow = false;
6286 return true;
6287 }
6288 }
6289
6290 res = mCurrentStream->prepareNextBuffer();
6291 if (res == NOT_ENOUGH_DATA) return true;
6292 if (res != OK) {
6293 // Something bad happened; try to recover by cancelling prepare and
6294 // signalling listener anyway
6295 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6296 mCurrentStream->getId(), res, strerror(-res));
6297 mCurrentStream->cancelPrepare();
6298 }
6299
6300 // This stream has finished, notify listener
6301 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006302 sp<NotificationListener> listener = mListener.promote();
6303 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006304 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6305 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006306 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006307 }
6308
6309 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6310 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006311 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006312
6313 return true;
6314}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006315
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006316status_t Camera3Device::RequestBufferStateMachine::initialize(
6317 sp<camera3::StatusTracker> statusTracker) {
6318 if (statusTracker == nullptr) {
6319 ALOGE("%s: statusTracker is null", __FUNCTION__);
6320 return BAD_VALUE;
6321 }
6322
6323 std::lock_guard<std::mutex> lock(mLock);
6324 mStatusTracker = statusTracker;
6325 mRequestBufferStatusId = statusTracker->addComponent();
6326 return OK;
6327}
6328
6329bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6330 std::lock_guard<std::mutex> lock(mLock);
6331 if (mStatus == RB_STATUS_READY) {
6332 mRequestBufferOngoing = true;
6333 return true;
6334 }
6335 return false;
6336}
6337
6338void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6339 std::lock_guard<std::mutex> lock(mLock);
6340 if (!mRequestBufferOngoing) {
6341 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6342 return;
6343 }
6344 mRequestBufferOngoing = false;
6345 if (mStatus == RB_STATUS_PENDING_STOP) {
6346 checkSwitchToStopLocked();
6347 }
6348}
6349
6350void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6351 std::lock_guard<std::mutex> lock(mLock);
6352 RequestBufferState oldStatus = mStatus;
6353 mStatus = RB_STATUS_READY;
6354 if (oldStatus != RB_STATUS_READY) {
6355 notifyTrackerLocked(/*active*/true);
6356 }
6357 return;
6358}
6359
6360void Camera3Device::RequestBufferStateMachine::onRequestSubmitted() {
6361 std::lock_guard<std::mutex> lock(mLock);
6362 mRequestThreadPaused = false;
6363 mInflightMapEmpty = false;
6364 if (mStatus == RB_STATUS_STOPPED) {
6365 mStatus = RB_STATUS_READY;
6366 notifyTrackerLocked(/*active*/true);
6367 }
6368 return;
6369}
6370
6371void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6372 std::lock_guard<std::mutex> lock(mLock);
6373 mRequestThreadPaused = true;
6374 if (mStatus == RB_STATUS_PENDING_STOP) {
6375 checkSwitchToStopLocked();
6376 }
6377 return;
6378}
6379
6380void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6381 std::lock_guard<std::mutex> lock(mLock);
6382 mInflightMapEmpty = true;
6383 if (mStatus == RB_STATUS_PENDING_STOP) {
6384 checkSwitchToStopLocked();
6385 }
6386 return;
6387}
6388
6389void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6390 std::lock_guard<std::mutex> lock(mLock);
6391 if (!checkSwitchToStopLocked()) {
6392 mStatus = RB_STATUS_PENDING_STOP;
6393 }
6394 return;
6395}
6396
6397void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6398 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6399 if (statusTracker != nullptr) {
6400 if (active) {
6401 statusTracker->markComponentActive(mRequestBufferStatusId);
6402 } else {
6403 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6404 }
6405 }
6406}
6407
6408bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6409 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6410 mStatus = RB_STATUS_STOPPED;
6411 notifyTrackerLocked(/*active*/false);
6412 return true;
6413 }
6414 return false;
6415}
6416
Shuzhen Wang268a1362018-10-16 16:32:59 -07006417status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6418 CameraMetadata& resultMetadata) {
6419 status_t res = OK;
6420 if (!mNeedFixupMonochromeTags) {
6421 return res;
6422 }
6423
6424 // Remove tags that are not applicable to monochrome camera.
6425 int32_t tagsToRemove[] = {
6426 ANDROID_SENSOR_GREEN_SPLIT,
6427 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6428 ANDROID_COLOR_CORRECTION_MODE,
6429 ANDROID_COLOR_CORRECTION_TRANSFORM,
6430 ANDROID_COLOR_CORRECTION_GAINS,
6431 };
6432 for (auto tag : tagsToRemove) {
6433 res = resultMetadata.erase(tag);
6434 if (res != OK) {
6435 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6436 return res;
6437 }
6438 }
6439
6440 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6441 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6442 for (size_t i = 1; i < blEntry.count; i++) {
6443 blEntry.data.f[i] = blEntry.data.f[0];
6444 }
6445
6446 // ANDROID_SENSOR_NOISE_PROFILE
6447 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6448 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6449 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6450 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6451 if (res != OK) {
6452 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6453 __FUNCTION__, strerror(-res), res);
6454 return res;
6455 }
6456 }
6457
6458 // ANDROID_STATISTICS_LENS_SHADING_MAP
6459 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6460 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6461 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6462 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6463 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6464 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6465 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6466 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6467 }
6468 }
6469
6470 // ANDROID_TONEMAP_CURVE_BLUE
6471 // ANDROID_TONEMAP_CURVE_GREEN
6472 // ANDROID_TONEMAP_CURVE_RED
6473 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6474 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6475 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6476 if (tcbEntry.count > 0
6477 && tcbEntry.count == tcgEntry.count
6478 && tcbEntry.count == tcrEntry.count) {
6479 for (size_t i = 0; i < tcbEntry.count; i++) {
6480 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6481 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6482 }
6483 }
6484
6485 return res;
6486}
6487
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006488}; // namespace android