blob: 32952cc12c9f7aab75af055638ffb3d885e50272 [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 Yeh651fe2e2018-11-13 11:49:31 -0800184 camera_metadata_entry bufMgrMode =
185 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
186 if (bufMgrMode.count > 0) {
187 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
188 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
189 }
190
191 mInterface = new HalInterface(session, queue, mUseHalBufManager);
Emilian Peev71c73a22017-03-21 16:35:51 +0000192 std::string providerType;
193 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000194 mTagMonitor.initialize(mVendorTagId);
195 if (!monitorTags.isEmpty()) {
196 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
197 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800198
Shuzhen Wang268a1362018-10-16 16:32:59 -0700199 // Metadata tags needs fixup for monochrome camera device version less
200 // than 3.5.
201 hardware::hidl_version maxVersion{0,0};
202 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
203 if (res != OK) {
204 ALOGE("%s: Error in getting camera device version id: %s (%d)",
205 __FUNCTION__, strerror(-res), res);
206 return res;
207 }
208 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
209 maxVersion.get_major(), maxVersion.get_minor());
210
211 bool isMonochrome = false;
212 camera_metadata_entry_t entry = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
213 for (size_t i = 0; i < entry.count; i++) {
214 uint8_t capability = entry.data.u8[i];
215 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
216 isMonochrome = true;
217 }
218 }
219 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
220
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800221 return initializeCommonLocked();
222}
223
224status_t Camera3Device::initializeCommonLocked() {
225
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700226 /** Start up status tracker thread */
227 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800228 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700229 if (res != OK) {
230 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
231 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800232 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700233 mStatusTracker.clear();
234 return res;
235 }
236
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700237 /** Register in-flight map to the status tracker */
238 mInFlightStatusId = mStatusTracker->addComponent();
239
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700240 if (mUseHalBufManager) {
241 res = mRequestBufferSM.initialize(mStatusTracker);
242 if (res != OK) {
243 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
244 strerror(-res), res);
245 mInterface->close();
246 mStatusTracker.clear();
247 return res;
248 }
249 }
250
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800251 /** Create buffer manager */
252 mBufferManager = new Camera3BufferManager();
253
254 Vector<int32_t> sessionParamKeys;
255 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
256 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
257 if (sessionKeysEntry.count > 0) {
258 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
259 }
260
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700261 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700262 mRequestThread = new RequestThread(
263 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800264 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800265 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700266 SET_ERR_L("Unable to start request queue thread: %s (%d)",
267 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800268 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800269 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800270 return res;
271 }
272
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700273 mPreparerThread = new PreparerThread();
274
Ruben Brunk183f0562015-08-12 12:55:02 -0700275 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800276 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700277 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700278 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700279 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800280
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800281 // Measure the clock domain offset between camera and video/hw_composer
282 camera_metadata_entry timestampSource =
283 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
284 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
285 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
286 mTimestampOffset = getMonoToBoottimeOffset();
287 }
288
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700289 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100290 camera_metadata_entry partialResultsCount =
291 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
292 if (partialResultsCount.count > 0) {
293 mNumPartialResults = partialResultsCount.data.i32[0];
294 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700295 }
296
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700297 camera_metadata_entry configs =
298 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
299 for (uint32_t i = 0; i < configs.count; i += 4) {
300 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
301 configs.data.i32[i + 3] ==
302 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
303 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
304 configs.data.i32[i + 2]));
305 }
306 }
307
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700308 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
309 res = mDistortionMapper.setupStaticInfo(mDeviceInfo);
310 if (res != OK) {
311 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
312 return res;
313 }
314 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800315 return OK;
316}
317
318status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700319 return disconnectImpl();
320}
321
322status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800323 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700324 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800325
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700326 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800327
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700328 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700329 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700330 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700331 {
332 Mutex::Autolock l(mLock);
333 if (mStatus == STATUS_UNINITIALIZED) return res;
334
335 if (mStatus == STATUS_ACTIVE ||
336 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
337 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700338 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700339 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700340 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700341 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700342 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700343 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700344 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
345 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700346 // Continue to close device even in case of error
347 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700348 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800349 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800350
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700351 if (mStatus == STATUS_ERROR) {
352 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700353 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700354
355 if (mStatusTracker != NULL) {
356 mStatusTracker->requestExit();
357 }
358
359 if (mRequestThread != NULL) {
360 mRequestThread->requestExit();
361 }
362
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700363 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
364 for (size_t i = 0; i < mOutputStreams.size(); i++) {
365 streams.push_back(mOutputStreams[i]);
366 }
367 if (mInputStream != nullptr) {
368 streams.push_back(mInputStream);
369 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700370 }
371
372 // Joining done without holding mLock, otherwise deadlocks may ensue
373 // as the threads try to access parent state
374 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
375 // HAL may be in a bad state, so waiting for request thread
376 // (which may be stuck in the HAL processCaptureRequest call)
377 // could be dangerous.
378 mRequestThread->join();
379 }
380
381 if (mStatusTracker != NULL) {
382 mStatusTracker->join();
383 }
384
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800385 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700386 {
387 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800388 mRequestThread.clear();
Emilian Peev2843c362018-09-26 08:49:40 +0100389 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700390 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800391 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700392 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800393
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700394 // Call close without internal mutex held, as the HAL close may need to
395 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800396 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700397
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700398 flushInflightRequests();
399
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700400 {
401 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800402 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700403 mOutputStreams.clear();
404 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700405 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700406 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700407 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700408 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800409
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700410 for (auto& weakStream : streams) {
411 sp<Camera3StreamInterface> stream = weakStream.promote();
412 if (stream != nullptr) {
413 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
414 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
415 }
416 }
417
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700418 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700419 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800420}
421
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700422// For dumping/debugging only -
423// try to acquire a lock a few times, eventually give up to proceed with
424// debug/dump operations
425bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
426 bool gotLock = false;
427 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
428 if (lock.tryLock() == NO_ERROR) {
429 gotLock = true;
430 break;
431 } else {
432 usleep(kDumpSleepDuration);
433 }
434 }
435 return gotLock;
436}
437
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700438Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
439 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100440 const int STREAM_CONFIGURATION_SIZE = 4;
441 const int STREAM_FORMAT_OFFSET = 0;
442 const int STREAM_WIDTH_OFFSET = 1;
443 const int STREAM_HEIGHT_OFFSET = 2;
444 const int STREAM_IS_INPUT_OFFSET = 3;
445 camera_metadata_ro_entry_t availableStreamConfigs =
446 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
447 if (availableStreamConfigs.count == 0 ||
448 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
449 return Size(0, 0);
450 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700451
Emilian Peev08dd2452017-04-06 16:55:14 +0100452 // Get max jpeg size (area-wise).
453 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
454 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
455 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
456 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
457 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
458 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
459 && format == HAL_PIXEL_FORMAT_BLOB &&
460 (width * height > maxJpegWidth * maxJpegHeight)) {
461 maxJpegWidth = width;
462 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700463 }
464 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100465
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700466 return Size(maxJpegWidth, maxJpegHeight);
467}
468
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800469nsecs_t Camera3Device::getMonoToBoottimeOffset() {
470 // try three times to get the clock offset, choose the one
471 // with the minimum gap in measurements.
472 const int tries = 3;
473 nsecs_t bestGap, measured;
474 for (int i = 0; i < tries; ++i) {
475 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
476 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
477 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
478 const nsecs_t gap = tmono2 - tmono;
479 if (i == 0 || gap < bestGap) {
480 bestGap = gap;
481 measured = tbase - ((tmono + tmono2) >> 1);
482 }
483 }
484 return measured;
485}
486
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800487hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
488 int frameworkFormat) {
489 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
490}
491
492DataspaceFlags Camera3Device::mapToHidlDataspace(
493 android_dataspace dataSpace) {
494 return dataSpace;
495}
496
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700497BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100498 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700499 return usage;
500}
501
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800502StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
503 switch (rotation) {
504 case CAMERA3_STREAM_ROTATION_0:
505 return StreamRotation::ROTATION_0;
506 case CAMERA3_STREAM_ROTATION_90:
507 return StreamRotation::ROTATION_90;
508 case CAMERA3_STREAM_ROTATION_180:
509 return StreamRotation::ROTATION_180;
510 case CAMERA3_STREAM_ROTATION_270:
511 return StreamRotation::ROTATION_270;
512 }
513 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
514 return StreamRotation::ROTATION_0;
515}
516
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800517status_t Camera3Device::mapToStreamConfigurationMode(
518 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
519 if (mode == nullptr) return BAD_VALUE;
520 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
521 switch(operationMode) {
522 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
523 *mode = StreamConfigurationMode::NORMAL_MODE;
524 break;
525 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
526 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
527 break;
528 default:
529 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
530 return BAD_VALUE;
531 }
532 } else {
533 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800535 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800536}
537
538camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
539 switch (status) {
540 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
541 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
542 }
543 return CAMERA3_BUFFER_STATUS_ERROR;
544}
545
546int Camera3Device::mapToFrameworkFormat(
547 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
548 return static_cast<uint32_t>(pixelFormat);
549}
550
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700551android_dataspace Camera3Device::mapToFrameworkDataspace(
552 DataspaceFlags dataSpace) {
553 return static_cast<android_dataspace>(dataSpace);
554}
555
Emilian Peev050f5dc2017-05-18 14:43:56 +0100556uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700557 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700558 return usage;
559}
560
Emilian Peev050f5dc2017-05-18 14:43:56 +0100561uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700562 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700563 return usage;
564}
565
Zhijun Hef7da0962014-04-24 13:27:56 -0700566ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700567 // Get max jpeg size (area-wise).
568 Size maxJpegResolution = getMaxJpegResolution();
569 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800570 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
571 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700572 return BAD_VALUE;
573 }
574
Zhijun Hef7da0962014-04-24 13:27:56 -0700575 // Get max jpeg buffer size
576 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700577 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
578 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800579 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
580 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700581 return BAD_VALUE;
582 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700583 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800584 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700585
586 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700587 float scaleFactor = ((float) (width * height)) /
588 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800589 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
590 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700591 if (jpegBufferSize > maxJpegBufferSize) {
592 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700593 }
594
595 return jpegBufferSize;
596}
597
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700598ssize_t Camera3Device::getPointCloudBufferSize() const {
599 const int FLOATS_PER_POINT=4;
600 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
601 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800602 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
603 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700604 return BAD_VALUE;
605 }
606 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
607 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
608 return maxBytesForPointCloud;
609}
610
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800611ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800612 const int PER_CONFIGURATION_SIZE = 3;
613 const int WIDTH_OFFSET = 0;
614 const int HEIGHT_OFFSET = 1;
615 const int SIZE_OFFSET = 2;
616 camera_metadata_ro_entry rawOpaqueSizes =
617 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800618 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800619 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800620 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
621 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800622 return BAD_VALUE;
623 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700624
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800625 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
626 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
627 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
628 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
629 }
630 }
631
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800632 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
633 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800634 return BAD_VALUE;
635}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700636
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800637status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
638 ATRACE_CALL();
639 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700640
641 // Try to lock, but continue in case of failure (to avoid blocking in
642 // deadlocks)
643 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
644 bool gotLock = tryLockSpinRightRound(mLock);
645
646 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800647 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
648 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700649 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800650 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
651 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700652
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800653 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700654
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800655 String16 templatesOption("-t");
656 int n = args.size();
657 for (int i = 0; i < n; i++) {
658 if (args[i] == templatesOption) {
659 dumpTemplates = true;
660 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000661 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700662 if (i + 1 < n) {
663 String8 monitorTags = String8(args[i + 1]);
664 if (monitorTags == "off") {
665 mTagMonitor.disableMonitoring();
666 } else {
667 mTagMonitor.parseTagsToMonitor(monitorTags);
668 }
669 } else {
670 mTagMonitor.disableMonitoring();
671 }
672 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800673 }
674
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800675 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800676
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800677 const char *status =
678 mStatus == STATUS_ERROR ? "ERROR" :
679 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700680 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
681 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800682 mStatus == STATUS_ACTIVE ? "ACTIVE" :
683 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700684
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800685 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700686 if (mStatus == STATUS_ERROR) {
687 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
688 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800689 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800690 const char *mode =
691 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
692 mOperatingMode == static_cast<int>(
693 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
694 "CUSTOM";
695 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800696
697 if (mInputStream != NULL) {
698 write(fd, lines.string(), lines.size());
699 mInputStream->dump(fd, args);
700 } else {
701 lines.appendFormat(" No input stream.\n");
702 write(fd, lines.string(), lines.size());
703 }
704 for (size_t i = 0; i < mOutputStreams.size(); i++) {
705 mOutputStreams[i]->dump(fd,args);
706 }
707
Zhijun He431503c2016-03-07 17:30:16 -0800708 if (mBufferManager != NULL) {
709 lines = String8(" Camera3 Buffer Manager:\n");
710 write(fd, lines.string(), lines.size());
711 mBufferManager->dump(fd, args);
712 }
Zhijun He125684a2015-12-26 15:07:30 -0800713
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700714 lines = String8(" In-flight requests:\n");
715 if (mInFlightMap.size() == 0) {
716 lines.append(" None\n");
717 } else {
718 for (size_t i = 0; i < mInFlightMap.size(); i++) {
719 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700720 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700721 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800722 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700723 r.numBuffersLeft);
724 }
725 }
726 write(fd, lines.string(), lines.size());
727
Shuzhen Wang686f6442017-06-20 16:16:04 -0700728 if (mRequestThread != NULL) {
729 mRequestThread->dumpCaptureRequestLatency(fd,
730 " ProcessCaptureRequest latency histogram:");
731 }
732
Igor Murashkin1e479c02013-09-06 16:55:14 -0700733 {
734 lines = String8(" Last request sent:\n");
735 write(fd, lines.string(), lines.size());
736
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700737 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700738 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
739 }
740
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800741 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800742 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800743 "TEMPLATE_PREVIEW",
744 "TEMPLATE_STILL_CAPTURE",
745 "TEMPLATE_VIDEO_RECORD",
746 "TEMPLATE_VIDEO_SNAPSHOT",
747 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800748 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800749 };
750
751 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800752 camera_metadata_t *templateRequest = nullptr;
753 mInterface->constructDefaultRequestSettings(
754 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800755 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800756 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800757 lines.append(" Not supported\n");
758 write(fd, lines.string(), lines.size());
759 } else {
760 write(fd, lines.string(), lines.size());
761 dump_indented_camera_metadata(templateRequest,
762 fd, /*verbosity*/2, /*indentation*/8);
763 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800764 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800765 }
766 }
767
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700768 mTagMonitor.dumpMonitoredMetadata(fd);
769
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800770 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800771 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800772 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800773 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800774 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800775
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700776 if (gotLock) mLock.unlock();
777 if (gotInterfaceLock) mInterfaceLock.unlock();
778
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800779 return OK;
780}
781
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700782const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800783 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800784 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
785 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700786 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800787 mStatus == STATUS_ERROR ?
788 "when in error state" : "before init");
789 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700790 if (physicalId.isEmpty()) {
791 return mDeviceInfo;
792 } else {
793 std::string id(physicalId.c_str());
794 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
795 return mPhysicalDeviceInfoMap.at(id);
796 } else {
797 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
798 return mDeviceInfo;
799 }
800 }
801}
802
803const CameraMetadata& Camera3Device::info() const {
804 String8 emptyId;
805 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800806}
807
Jianing Wei90e59c92014-03-12 18:29:36 -0700808status_t Camera3Device::checkStatusOkToCaptureLocked() {
809 switch (mStatus) {
810 case STATUS_ERROR:
811 CLOGE("Device has encountered a serious error");
812 return INVALID_OPERATION;
813 case STATUS_UNINITIALIZED:
814 CLOGE("Device not initialized");
815 return INVALID_OPERATION;
816 case STATUS_UNCONFIGURED:
817 case STATUS_CONFIGURED:
818 case STATUS_ACTIVE:
819 // OK
820 break;
821 default:
822 SET_ERR_L("Unexpected status: %d", mStatus);
823 return INVALID_OPERATION;
824 }
825 return OK;
826}
827
828status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000829 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700830 const std::list<const SurfaceMap> &surfaceMaps,
831 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700832 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700833 if (requestList == NULL) {
834 CLOGE("requestList cannot be NULL.");
835 return BAD_VALUE;
836 }
837
Jianing Weicb0652e2014-03-12 18:29:36 -0700838 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000839 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700840 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
841 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
842 ++metadataIt, ++surfaceMapIt) {
843 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700844 if (newRequest == 0) {
845 CLOGE("Can't create capture request");
846 return BAD_VALUE;
847 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700848
Shuzhen Wang9d066012016-09-30 11:30:20 -0700849 newRequest->mRepeating = repeating;
850
Jianing Weicb0652e2014-03-12 18:29:36 -0700851 // Setup burst Id and request Id
852 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000853 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
854 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700855 CLOGE("RequestID entry exists; but must not be empty in metadata");
856 return BAD_VALUE;
857 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000858 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
859 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700860 } else {
861 CLOGE("RequestID does not exist in metadata");
862 return BAD_VALUE;
863 }
864
Jianing Wei90e59c92014-03-12 18:29:36 -0700865 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700866
867 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700868 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700869 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
870 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
871 return BAD_VALUE;
872 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700873
874 // Setup batch size if this is a high speed video recording request.
875 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
876 auto firstRequest = requestList->begin();
877 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
878 if (outputStream->isVideoStream()) {
879 (*firstRequest)->mBatchSize = requestList->size();
880 break;
881 }
882 }
883 }
884
Jianing Wei90e59c92014-03-12 18:29:36 -0700885 return OK;
886}
887
Jianing Weicb0652e2014-03-12 18:29:36 -0700888status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800889 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800890
Emilian Peevaebbe412018-01-15 13:53:24 +0000891 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700892 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000893 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700894
Emilian Peevaebbe412018-01-15 13:53:24 +0000895 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700896}
897
Emilian Peevaebbe412018-01-15 13:53:24 +0000898void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700899 std::list<const SurfaceMap>& surfaceMaps,
900 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000901 PhysicalCameraSettingsList requestList;
902 requestList.push_back({std::string(getId().string()), request});
903 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700904
905 SurfaceMap surfaceMap;
906 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
907 // With no surface list passed in, stream and surface will have 1-to-1
908 // mapping. So the surface index is 0 for each stream in the surfaceMap.
909 for (size_t i = 0; i < streams.count; i++) {
910 surfaceMap[streams.data.i32[i]].push_back(0);
911 }
912 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800913}
914
Jianing Wei90e59c92014-03-12 18:29:36 -0700915status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000916 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700917 const std::list<const SurfaceMap> &surfaceMaps,
918 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700919 /*out*/
920 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700921 ATRACE_CALL();
922 Mutex::Autolock il(mInterfaceLock);
923 Mutex::Autolock l(mLock);
924
925 status_t res = checkStatusOkToCaptureLocked();
926 if (res != OK) {
927 // error logged by previous call
928 return res;
929 }
930
931 RequestList requestList;
932
Shuzhen Wang0129d522016-10-30 22:43:41 -0700933 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
934 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700935 if (res != OK) {
936 // error logged by previous call
937 return res;
938 }
939
940 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700941 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700942 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700943 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700944 }
945
946 if (res == OK) {
947 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
948 if (res != OK) {
949 SET_ERR_L("Can't transition to active in %f seconds!",
950 kActiveTimeout/1e9);
951 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800952 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700953 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700954 } else {
955 CLOGE("Cannot queue request. Impossible.");
956 return BAD_VALUE;
957 }
958
959 return res;
960}
961
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700962hardware::Return<void> Camera3Device::requestStreamBuffers(
963 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
964 requestStreamBuffers_cb _hidl_cb) {
965 using hardware::camera::device::V3_5::BufferRequestStatus;
966 using hardware::camera::device::V3_5::StreamBufferRet;
967 using hardware::camera::device::V3_5::StreamBufferRequestError;
968
969 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
970
971 hardware::hidl_vec<StreamBufferRet> bufRets;
972 if (!mUseHalBufManager) {
973 ALOGE("%s: Camera %s does not support HAL buffer management",
974 __FUNCTION__, mId.string());
975 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
976 return hardware::Void();
977 }
978
979 SortedVector<int32_t> streamIds;
980 ssize_t sz = streamIds.setCapacity(bufReqs.size());
981 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
982 ALOGE("%s: failed to allocate memory for %zu buffer requests",
983 __FUNCTION__, bufReqs.size());
984 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
985 return hardware::Void();
986 }
987
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700988 if (bufReqs.size() > mOutputStreams.size()) {
989 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
990 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
991 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
992 return hardware::Void();
993 }
994
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700995 // Check for repeated streamId
996 for (const auto& bufReq : bufReqs) {
997 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
998 ALOGE("%s: Stream %d appear multiple times in buffer requests",
999 __FUNCTION__, bufReq.streamId);
1000 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1001 return hardware::Void();
1002 }
1003 streamIds.add(bufReq.streamId);
1004 }
1005
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001006 if (!mRequestBufferSM.startRequestBuffer()) {
1007 ALOGE("%s: request buffer disallowed while camera service is configuring",
1008 __FUNCTION__);
1009 _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001010 return hardware::Void();
1011 }
1012
1013 bufRets.resize(bufReqs.size());
1014
1015 bool allReqsSucceeds = true;
1016 bool oneReqSucceeds = false;
1017 for (size_t i = 0; i < bufReqs.size(); i++) {
1018 const auto& bufReq = bufReqs[i];
1019 auto& bufRet = bufRets[i];
1020 int32_t streamId = bufReq.streamId;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001021 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
1022 if (outputStream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001023 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
1024 hardware::hidl_vec<StreamBufferRet> emptyBufRets;
1025 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001026 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001027 return hardware::Void();
1028 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001029
1030 bufRet.streamId = streamId;
1031 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
1032 size_t totalHandout = outputStream->getOutstandingBuffersCount() + numBuffersRequested;
1033 if (totalHandout > outputStream->asHalStream()->max_buffers) {
1034 // Not able to allocate enough buffer. Exit early for this stream
1035 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1036 allReqsSucceeds = false;
1037 continue;
1038 }
1039
1040 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1041 bool currentReqSucceeds = true;
1042 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1043 size_t numAllocatedBuffers = 0;
1044 size_t numPushedInflightBuffers = 0;
1045 for (size_t b = 0; b < numBuffersRequested; b++) {
1046 camera3_stream_buffer_t& sb = streamBuffers[b];
1047 // Since this method can run concurrently with request thread
1048 // We need to update the wait duration everytime we call getbuffer
1049 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1050 status_t res = outputStream->getBuffer(&sb, waitDuration);
1051 if (res != OK) {
1052 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1053 __FUNCTION__, streamId, strerror(-res), res);
1054 if (res == NO_INIT || res == DEAD_OBJECT) {
1055 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1056 } else if (res == TIMED_OUT || res == NO_MEMORY) {
1057 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1058 } else {
1059 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1060 }
1061 currentReqSucceeds = false;
1062 break;
1063 }
1064 numAllocatedBuffers++;
1065
1066 buffer_handle_t *buffer = sb.buffer;
1067 auto pair = mInterface->getBufferId(*buffer, streamId);
1068 bool isNewBuffer = pair.first;
1069 uint64_t bufferId = pair.second;
1070 StreamBuffer& hBuf = tmpRetBuffers[b];
1071
1072 hBuf.streamId = streamId;
1073 hBuf.bufferId = bufferId;
1074 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1075 hBuf.status = BufferStatus::OK;
1076 hBuf.releaseFence = nullptr;
1077
1078 native_handle_t *acquireFence = nullptr;
1079 if (sb.acquire_fence != -1) {
1080 acquireFence = native_handle_create(1,0);
1081 acquireFence->data[0] = sb.acquire_fence;
1082 }
1083 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1084 hBuf.releaseFence = nullptr;
1085
1086 res = mInterface->pushInflightRequestBuffer(bufferId, buffer);
1087 if (res != OK) {
1088 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1089 __FUNCTION__, streamId, strerror(-res), res);
1090 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1091 currentReqSucceeds = false;
1092 break;
1093 }
1094 numPushedInflightBuffers++;
1095 }
1096 if (currentReqSucceeds) {
1097 bufRet.val.buffers(std::move(tmpRetBuffers));
1098 oneReqSucceeds = true;
1099 } else {
1100 allReqsSucceeds = false;
1101 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1102 StreamBuffer& hBuf = tmpRetBuffers[b];
1103 buffer_handle_t* buffer;
1104 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1105 if (res != OK) {
1106 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1107 __FUNCTION__, streamId, strerror(-res), res);
1108 }
1109 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001110 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1111 camera3_stream_buffer_t& sb = streamBuffers[b];
1112 sb.acquire_fence = -1;
1113 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1114 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001115 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1116 }
1117 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001118
1119 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1120 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1121 BufferRequestStatus::FAILED_UNKNOWN,
1122 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001123 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001124 return hardware::Void();
1125}
1126
1127hardware::Return<void> Camera3Device::returnStreamBuffers(
1128 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1129 if (!mUseHalBufManager) {
1130 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1131 __FUNCTION__, mId.string());
1132 return hardware::Void();
1133 }
1134
1135 for (const auto& buf : buffers) {
1136 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1137 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1138 continue;
1139 }
1140
1141 buffer_handle_t* buffer;
1142 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1143
1144 if (res != OK) {
1145 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1146 __FUNCTION__, buf.bufferId, buf.streamId);
1147 continue;
1148 }
1149
1150 camera3_stream_buffer_t streamBuffer;
1151 streamBuffer.buffer = buffer;
1152 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1153 streamBuffer.acquire_fence = -1;
1154 streamBuffer.release_fence = -1;
1155
1156 if (buf.releaseFence == nullptr) {
1157 streamBuffer.release_fence = -1;
1158 } else if (buf.releaseFence->numFds == 1) {
1159 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1160 } else {
1161 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1162 __FUNCTION__, buf.releaseFence->numFds);
1163 continue;
1164 }
1165
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001166 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1167 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001168 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1169 continue;
1170 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001171 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001172 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1173 }
1174 return hardware::Void();
1175}
1176
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001177hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001178 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001179 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001180 // Ideally we should grab mLock, but that can lead to deadlock, and
1181 // it's not super important to get up to date value of mStatus for this
1182 // warning print, hence skipping the lock here
1183 if (mStatus == STATUS_ERROR) {
1184 // Per API contract, HAL should act as closed after device error
1185 // But mStatus can be set to error by framework as well, so just log
1186 // a warning here.
1187 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001188 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001189
1190 if (mProcessCaptureResultLock.tryLock() != OK) {
1191 // This should never happen; it indicates a wrong client implementation
1192 // that doesn't follow the contract. But, we can be tolerant here.
1193 ALOGE("%s: callback overlapped! waiting 1s...",
1194 __FUNCTION__);
1195 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1196 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1197 __FUNCTION__);
1198 // really don't know what to do, so bail out.
1199 return hardware::Void();
1200 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001201 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001202 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001203 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001204 }
1205 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001206 return hardware::Void();
1207}
1208
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001209// Only one processCaptureResult should be called at a time, so
1210// the locks won't block. The locks are present here simply to enforce this.
1211hardware::Return<void> Camera3Device::processCaptureResult(
1212 const hardware::hidl_vec<
1213 hardware::camera::device::V3_2::CaptureResult>& results) {
1214 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1215
1216 // Ideally we should grab mLock, but that can lead to deadlock, and
1217 // it's not super important to get up to date value of mStatus for this
1218 // warning print, hence skipping the lock here
1219 if (mStatus == STATUS_ERROR) {
1220 // Per API contract, HAL should act as closed after device error
1221 // But mStatus can be set to error by framework as well, so just log
1222 // a warning here.
1223 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1224 }
1225
1226 if (mProcessCaptureResultLock.tryLock() != OK) {
1227 // This should never happen; it indicates a wrong client implementation
1228 // that doesn't follow the contract. But, we can be tolerant here.
1229 ALOGE("%s: callback overlapped! waiting 1s...",
1230 __FUNCTION__);
1231 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1232 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1233 __FUNCTION__);
1234 // really don't know what to do, so bail out.
1235 return hardware::Void();
1236 }
1237 }
1238 for (const auto& result : results) {
1239 processOneCaptureResultLocked(result, noPhysMetadata);
1240 }
1241 mProcessCaptureResultLock.unlock();
1242 return hardware::Void();
1243}
1244
1245status_t Camera3Device::readOneCameraMetadataLocked(
1246 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1247 const hardware::camera::device::V3_2::CameraMetadata& result) {
1248 if (fmqResultSize > 0) {
1249 resultMetadata.resize(fmqResultSize);
1250 if (mResultMetadataQueue == nullptr) {
1251 return NO_MEMORY; // logged in initialize()
1252 }
1253 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1254 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1255 __FUNCTION__, fmqResultSize);
1256 return INVALID_OPERATION;
1257 }
1258 } else {
1259 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1260 result.size());
1261 }
1262
1263 if (resultMetadata.size() != 0) {
1264 status_t res;
1265 const camera_metadata_t* metadata =
1266 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1267 size_t expected_metadata_size = resultMetadata.size();
1268 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1269 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1270 __FUNCTION__, strerror(-res), res);
1271 return INVALID_OPERATION;
1272 }
1273 }
1274
1275 return OK;
1276}
1277
Yifan Honga640c5a2017-04-12 16:30:31 -07001278void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001279 const hardware::camera::device::V3_2::CaptureResult& result,
1280 const hardware::hidl_vec<
1281 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001282 camera3_capture_result r;
1283 status_t res;
1284 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001285
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001286 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001287 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001288 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1289 if (res != OK) {
1290 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1291 __FUNCTION__, result.frameNumber);
1292 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001293 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001294 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001295
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001296 // Read and validate physical camera metadata
1297 size_t physResultCount = physicalCameraMetadatas.size();
1298 std::vector<const char*> physCamIds(physResultCount);
1299 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1300 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1301 physResultMetadata.resize(physResultCount);
1302 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1303 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1304 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1305 if (res != OK) {
1306 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1307 __FUNCTION__, result.frameNumber,
1308 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001309 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001310 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001311 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1312 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1313 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001314 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001315 r.num_physcam_metadata = physResultCount;
1316 r.physcam_ids = physCamIds.data();
1317 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001318
1319 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1320 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1321 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1322 auto& bDst = outputBuffers[i];
1323 const StreamBuffer &bSrc = result.outputBuffers[i];
1324
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001325 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1326 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001327 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1328 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001329 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001330 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001331 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001332
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001333 bool noBufferReturned = false;
1334 buffer_handle_t *buffer = nullptr;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001335 if (mUseHalBufManager) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001336 // This is suspicious most of the time but can be correct during flush where HAL
1337 // has to return capture result before a buffer is requested
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001338 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001339 if (bSrc.status == BufferStatus::OK) {
1340 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1341 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1342 // Still proceeds so other buffers can be returned
1343 }
1344 noBufferReturned = true;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001345 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001346 if (noBufferReturned) {
1347 res = OK;
1348 } else {
1349 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1350 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001351 } else {
1352 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1353 }
1354
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001355 if (res != OK) {
1356 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1357 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001358 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001359 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001360
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001361 bDst.buffer = buffer;
1362 bDst.status = mapHidlBufferStatus(bSrc.status);
1363 bDst.acquire_fence = -1;
1364 if (bSrc.releaseFence == nullptr) {
1365 bDst.release_fence = -1;
1366 } else if (bSrc.releaseFence->numFds == 1) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001367 if (noBufferReturned) {
1368 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
1369 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001370 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1371 } else {
1372 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1373 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001374 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001375 }
1376 }
1377 r.num_output_buffers = outputBuffers.size();
1378 r.output_buffers = outputBuffers.data();
1379
1380 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001381 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001382 r.input_buffer = nullptr;
1383 } else {
1384 if (mInputStream->getId() != result.inputBuffer.streamId) {
1385 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1386 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001387 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001388 }
1389 inputBuffer.stream = mInputStream->asHalStream();
1390 buffer_handle_t *buffer;
1391 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1392 &buffer);
1393 if (res != OK) {
1394 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1395 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001396 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001397 }
1398 inputBuffer.buffer = buffer;
1399 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1400 inputBuffer.acquire_fence = -1;
1401 if (result.inputBuffer.releaseFence == nullptr) {
1402 inputBuffer.release_fence = -1;
1403 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1404 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1405 } else {
1406 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1407 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001408 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001409 }
1410 r.input_buffer = &inputBuffer;
1411 }
1412
1413 r.partial_result = result.partialResult;
1414
1415 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001416}
1417
1418hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001419 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001420 // Ideally we should grab mLock, but that can lead to deadlock, and
1421 // it's not super important to get up to date value of mStatus for this
1422 // warning print, hence skipping the lock here
1423 if (mStatus == STATUS_ERROR) {
1424 // Per API contract, HAL should act as closed after device error
1425 // But mStatus can be set to error by framework as well, so just log
1426 // a warning here.
1427 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001428 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001429
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001430 for (const auto& msg : msgs) {
1431 notify(msg);
1432 }
1433 return hardware::Void();
1434}
1435
1436void Camera3Device::notify(
1437 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1438
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001439 camera3_notify_msg m;
1440 switch (msg.type) {
1441 case MsgType::ERROR:
1442 m.type = CAMERA3_MSG_ERROR;
1443 m.message.error.frame_number = msg.msg.error.frameNumber;
1444 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001445 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1446 if (stream == nullptr) {
1447 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1448 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001449 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001450 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001451 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001452 } else {
1453 m.message.error.error_stream = nullptr;
1454 }
1455 switch (msg.msg.error.errorCode) {
1456 case ErrorCode::ERROR_DEVICE:
1457 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1458 break;
1459 case ErrorCode::ERROR_REQUEST:
1460 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1461 break;
1462 case ErrorCode::ERROR_RESULT:
1463 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1464 break;
1465 case ErrorCode::ERROR_BUFFER:
1466 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1467 break;
1468 }
1469 break;
1470 case MsgType::SHUTTER:
1471 m.type = CAMERA3_MSG_SHUTTER;
1472 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1473 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1474 break;
1475 }
1476 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001477}
1478
Emilian Peevaebbe412018-01-15 13:53:24 +00001479status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001480 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001481 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001482 ATRACE_CALL();
1483
Emilian Peevaebbe412018-01-15 13:53:24 +00001484 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001485}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001486
Jianing Weicb0652e2014-03-12 18:29:36 -07001487status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1488 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001489 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001490
Emilian Peevaebbe412018-01-15 13:53:24 +00001491 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001492 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001493 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001494
Emilian Peevaebbe412018-01-15 13:53:24 +00001495 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001496 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497}
1498
Emilian Peevaebbe412018-01-15 13:53:24 +00001499status_t Camera3Device::setStreamingRequestList(
1500 const List<const PhysicalCameraSettingsList> &requestsList,
1501 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001502 ATRACE_CALL();
1503
Emilian Peevaebbe412018-01-15 13:53:24 +00001504 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001505}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506
1507sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001508 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001509 status_t res;
1510
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001511 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001512 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1513 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001514 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1515 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001516 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001517 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001518 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001519 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001520 } else if (mStatus == STATUS_UNCONFIGURED) {
1521 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001522 CLOGE("No streams configured");
1523 return NULL;
1524 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001525 }
1526
Shuzhen Wang0129d522016-10-30 22:43:41 -07001527 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001529}
1530
Jianing Weicb0652e2014-03-12 18:29:36 -07001531status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001532 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001533 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001535
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 switch (mStatus) {
1537 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001538 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 return INVALID_OPERATION;
1540 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001541 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001543 case STATUS_UNCONFIGURED:
1544 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 case STATUS_ACTIVE:
1546 // OK
1547 break;
1548 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001549 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 return INVALID_OPERATION;
1551 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001552 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001553
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001554 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001555}
1556
1557status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1558 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001559 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001560
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001561 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001562}
1563
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001564status_t Camera3Device::createInputStream(
1565 uint32_t width, uint32_t height, int format, int *id) {
1566 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001567 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001568 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001569 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001570 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1571 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001572
1573 status_t res;
1574 bool wasActive = false;
1575
1576 switch (mStatus) {
1577 case STATUS_ERROR:
1578 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1579 return INVALID_OPERATION;
1580 case STATUS_UNINITIALIZED:
1581 ALOGE("%s: Device not initialized", __FUNCTION__);
1582 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001583 case STATUS_UNCONFIGURED:
1584 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001585 // OK
1586 break;
1587 case STATUS_ACTIVE:
1588 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001589 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001590 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001591 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001592 return res;
1593 }
1594 wasActive = true;
1595 break;
1596 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001597 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001598 return INVALID_OPERATION;
1599 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001600 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001601
1602 if (mInputStream != 0) {
1603 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1604 return INVALID_OPERATION;
1605 }
1606
1607 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1608 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001609 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001610
1611 mInputStream = newStream;
1612
1613 *id = mNextStreamId++;
1614
1615 // Continue captures if active at start
1616 if (wasActive) {
1617 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001618 // Reuse current operating mode and session parameters for new stream config
1619 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001620 if (res != OK) {
1621 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1622 __FUNCTION__, mNextStreamId, strerror(-res), res);
1623 return res;
1624 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001625 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001626 }
1627
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001628 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001629 return OK;
1630}
1631
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001632status_t Camera3Device::StreamSet::add(
1633 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1634 if (stream == nullptr) {
1635 ALOGE("%s: cannot add null stream", __FUNCTION__);
1636 return BAD_VALUE;
1637 }
1638 std::lock_guard<std::mutex> lock(mLock);
1639 return mData.add(streamId, stream);
1640}
1641
1642ssize_t Camera3Device::StreamSet::remove(int streamId) {
1643 std::lock_guard<std::mutex> lock(mLock);
1644 return mData.removeItem(streamId);
1645}
1646
1647sp<camera3::Camera3OutputStreamInterface>
1648Camera3Device::StreamSet::get(int streamId) {
1649 std::lock_guard<std::mutex> lock(mLock);
1650 ssize_t idx = mData.indexOfKey(streamId);
1651 if (idx == NAME_NOT_FOUND) {
1652 return nullptr;
1653 }
1654 return mData.editValueAt(idx);
1655}
1656
1657sp<camera3::Camera3OutputStreamInterface>
1658Camera3Device::StreamSet::operator[] (size_t index) {
1659 std::lock_guard<std::mutex> lock(mLock);
1660 return mData.editValueAt(index);
1661}
1662
1663size_t Camera3Device::StreamSet::size() const {
1664 std::lock_guard<std::mutex> lock(mLock);
1665 return mData.size();
1666}
1667
1668void Camera3Device::StreamSet::clear() {
1669 std::lock_guard<std::mutex> lock(mLock);
1670 return mData.clear();
1671}
1672
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001673std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1674 std::lock_guard<std::mutex> lock(mLock);
1675 std::vector<int> streamIds(mData.size());
1676 for (size_t i = 0; i < mData.size(); i++) {
1677 streamIds[i] = mData.keyAt(i);
1678 }
1679 return streamIds;
1680}
1681
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001682status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001683 uint32_t width, uint32_t height, int format,
1684 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001685 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001686 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001687 ATRACE_CALL();
1688
1689 if (consumer == nullptr) {
1690 ALOGE("%s: consumer must not be null", __FUNCTION__);
1691 return BAD_VALUE;
1692 }
1693
1694 std::vector<sp<Surface>> consumers;
1695 consumers.push_back(consumer);
1696
1697 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001698 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1699 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001700}
1701
1702status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1703 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1704 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001705 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001706 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001707 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001708
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001709 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001710 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001711 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001712 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001713 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1714 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1715 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001716
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001717 status_t res;
1718 bool wasActive = false;
1719
1720 switch (mStatus) {
1721 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001722 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001723 return INVALID_OPERATION;
1724 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001725 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001726 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001727 case STATUS_UNCONFIGURED:
1728 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001729 // OK
1730 break;
1731 case STATUS_ACTIVE:
1732 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001733 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001734 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001735 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001736 return res;
1737 }
1738 wasActive = true;
1739 break;
1740 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001741 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001742 return INVALID_OPERATION;
1743 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001744 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001745
1746 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001747
Shuzhen Wang0129d522016-10-30 22:43:41 -07001748 if (consumers.size() == 0 && !hasDeferredConsumer) {
1749 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1750 return BAD_VALUE;
1751 }
Zhijun He5d677d12016-05-29 16:52:39 -07001752
Shuzhen Wang0129d522016-10-30 22:43:41 -07001753 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001754 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1755 return BAD_VALUE;
1756 }
1757
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001758 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001759 ssize_t blobBufferSize;
1760 if (dataSpace != HAL_DATASPACE_DEPTH) {
1761 blobBufferSize = getJpegBufferSize(width, height);
1762 if (blobBufferSize <= 0) {
1763 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1764 return BAD_VALUE;
1765 }
1766 } else {
1767 blobBufferSize = getPointCloudBufferSize();
1768 if (blobBufferSize <= 0) {
1769 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1770 return BAD_VALUE;
1771 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001772 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001773 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001774 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001775 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001776 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1777 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1778 if (rawOpaqueBufferSize <= 0) {
1779 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1780 return BAD_VALUE;
1781 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001782 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001783 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001784 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001785 } else if (isShared) {
1786 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1787 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001788 mTimestampOffset, physicalCameraId, streamSetId,
1789 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001790 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001791 newStream = new Camera3OutputStream(mNextStreamId,
1792 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001793 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001794 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001795 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001796 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001797 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001798 }
Emilian Peev40ead602017-09-26 15:46:36 +01001799
1800 size_t consumerCount = consumers.size();
1801 for (size_t i = 0; i < consumerCount; i++) {
1802 int id = newStream->getSurfaceId(consumers[i]);
1803 if (id < 0) {
1804 SET_ERR_L("Invalid surface id");
1805 return BAD_VALUE;
1806 }
1807 if (surfaceIds != nullptr) {
1808 surfaceIds->push_back(id);
1809 }
1810 }
1811
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001812 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001813
Emilian Peev08dd2452017-04-06 16:55:14 +01001814 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001815
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001816 res = mOutputStreams.add(mNextStreamId, newStream);
1817 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001818 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001819 return res;
1820 }
1821
1822 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001823 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001824
1825 // Continue captures if active at start
1826 if (wasActive) {
1827 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001828 // Reuse current operating mode and session parameters for new stream config
1829 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001830 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001831 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1832 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001833 return res;
1834 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001835 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001836 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001837 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001838 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001839}
1840
Emilian Peev710c1422017-08-30 11:19:38 +01001841status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001842 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001843 if (nullptr == streamInfo) {
1844 return BAD_VALUE;
1845 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001846 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001847 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001848
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001849 switch (mStatus) {
1850 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001851 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001852 return INVALID_OPERATION;
1853 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001854 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001855 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001856 case STATUS_UNCONFIGURED:
1857 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001858 case STATUS_ACTIVE:
1859 // OK
1860 break;
1861 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001862 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001863 return INVALID_OPERATION;
1864 }
1865
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001866 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1867 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001868 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001869 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001870 }
1871
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001872 streamInfo->width = stream->getWidth();
1873 streamInfo->height = stream->getHeight();
1874 streamInfo->format = stream->getFormat();
1875 streamInfo->dataSpace = stream->getDataSpace();
1876 streamInfo->formatOverridden = stream->isFormatOverridden();
1877 streamInfo->originalFormat = stream->getOriginalFormat();
1878 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1879 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001880 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001881}
1882
1883status_t Camera3Device::setStreamTransform(int id,
1884 int transform) {
1885 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001886 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001887 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001888
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001889 switch (mStatus) {
1890 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001891 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001892 return INVALID_OPERATION;
1893 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001894 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001895 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001896 case STATUS_UNCONFIGURED:
1897 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001898 case STATUS_ACTIVE:
1899 // OK
1900 break;
1901 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001902 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001903 return INVALID_OPERATION;
1904 }
1905
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001906 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1907 if (stream == nullptr) {
1908 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001909 return BAD_VALUE;
1910 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001911 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001912}
1913
1914status_t Camera3Device::deleteStream(int id) {
1915 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001916 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001917 Mutex::Autolock l(mLock);
1918 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001919
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001920 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001921
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001922 // CameraDevice semantics require device to already be idle before
1923 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001924 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001925 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001926 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001927 }
1928
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001929 if (mStatus == STATUS_ERROR) {
1930 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1931 __FUNCTION__, mId.string());
1932 return -EBUSY;
1933 }
1934
Igor Murashkin2fba5842013-04-22 14:03:54 -07001935 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001936 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001937 if (mInputStream != NULL && id == mInputStream->getId()) {
1938 deletedStream = mInputStream;
1939 mInputStream.clear();
1940 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001941 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001942 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001943 return BAD_VALUE;
1944 }
Zhijun He5f446352014-01-22 09:49:33 -08001945 }
1946
1947 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001948 if (stream != nullptr) {
1949 deletedStream = stream;
1950 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001951 }
1952
1953 // Free up the stream endpoint so that it can be used by some other stream
1954 res = deletedStream->disconnect();
1955 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001956 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001957 // fall through since we want to still list the stream as deleted.
1958 }
1959 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001960 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001961
1962 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001963}
1964
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001965status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001966 ATRACE_CALL();
1967 ALOGV("%s: E", __FUNCTION__);
1968
1969 Mutex::Autolock il(mInterfaceLock);
1970 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001971
Emilian Peev811d2952018-05-25 11:08:40 +01001972 // In case the client doesn't include any session parameter, try a
1973 // speculative configuration using the values from the last cached
1974 // default request.
1975 if (sessionParams.isEmpty() &&
1976 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1977 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1978 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1979 mLastTemplateId);
1980 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1981 operatingMode);
1982 }
1983
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001984 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1985}
1986
1987status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1988 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001989 //Filter out any incoming session parameters
1990 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001991 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1992 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001993 CameraMetadata filteredParams(availableSessionKeys.count);
1994 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1995 filteredParams.getAndLock());
1996 set_camera_metadata_vendor_id(meta, mVendorTagId);
1997 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001998 if (availableSessionKeys.count > 0) {
1999 for (size_t i = 0; i < availableSessionKeys.count; i++) {
2000 camera_metadata_ro_entry entry = params.find(
2001 availableSessionKeys.data.i32[i]);
2002 if (entry.count > 0) {
2003 filteredParams.update(entry);
2004 }
2005 }
2006 }
2007
2008 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07002009}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002010
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002011status_t Camera3Device::getInputBufferProducer(
2012 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002013 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002014 Mutex::Autolock il(mInterfaceLock);
2015 Mutex::Autolock l(mLock);
2016
2017 if (producer == NULL) {
2018 return BAD_VALUE;
2019 } else if (mInputStream == NULL) {
2020 return INVALID_OPERATION;
2021 }
2022
2023 return mInputStream->getInputBufferProducer(producer);
2024}
2025
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002026status_t Camera3Device::createDefaultRequest(int templateId,
2027 CameraMetadata *request) {
2028 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002029 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002030
2031 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2032 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002033 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002034 return BAD_VALUE;
2035 }
2036
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002037 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002038
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002039 {
2040 Mutex::Autolock l(mLock);
2041 switch (mStatus) {
2042 case STATUS_ERROR:
2043 CLOGE("Device has encountered a serious error");
2044 return INVALID_OPERATION;
2045 case STATUS_UNINITIALIZED:
2046 CLOGE("Device is not initialized!");
2047 return INVALID_OPERATION;
2048 case STATUS_UNCONFIGURED:
2049 case STATUS_CONFIGURED:
2050 case STATUS_ACTIVE:
2051 // OK
2052 break;
2053 default:
2054 SET_ERR_L("Unexpected status: %d", mStatus);
2055 return INVALID_OPERATION;
2056 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002057
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002058 if (!mRequestTemplateCache[templateId].isEmpty()) {
2059 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002060 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002061 return OK;
2062 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002063 }
2064
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002065 camera_metadata_t *rawRequest;
2066 status_t res = mInterface->constructDefaultRequestSettings(
2067 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002068
2069 {
2070 Mutex::Autolock l(mLock);
2071 if (res == BAD_VALUE) {
2072 ALOGI("%s: template %d is not supported on this camera device",
2073 __FUNCTION__, templateId);
2074 return res;
2075 } else if (res != OK) {
2076 CLOGE("Unable to construct request template %d: %s (%d)",
2077 templateId, strerror(-res), res);
2078 return res;
2079 }
2080
2081 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2082 mRequestTemplateCache[templateId].acquire(rawRequest);
2083
2084 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002085 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002086 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002087 return OK;
2088}
2089
2090status_t Camera3Device::waitUntilDrained() {
2091 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002092 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002093 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002094 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002095
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002096 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002097}
2098
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002099status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002100 switch (mStatus) {
2101 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002102 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002103 ALOGV("%s: Already idle", __FUNCTION__);
2104 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002105 case STATUS_CONFIGURED:
2106 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002107 case STATUS_ERROR:
2108 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002109 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002110 break;
2111 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002112 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002113 return INVALID_OPERATION;
2114 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002115 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2116 maxExpectedDuration);
2117 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002118 if (res != OK) {
2119 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2120 res);
2121 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002122 return res;
2123}
2124
Ruben Brunk183f0562015-08-12 12:55:02 -07002125
2126void Camera3Device::internalUpdateStatusLocked(Status status) {
2127 mStatus = status;
2128 mRecentStatusUpdates.add(mStatus);
2129 mStatusChanged.broadcast();
2130}
2131
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002132void Camera3Device::pauseStateNotify(bool enable) {
2133 Mutex::Autolock il(mInterfaceLock);
2134 Mutex::Autolock l(mLock);
2135
2136 mPauseStateNotify = enable;
2137}
2138
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002139// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002140status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002141 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002142
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002143 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2144 maxExpectedDuration);
2145 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002146 if (res != OK) {
2147 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002148 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002149 }
2150
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002151 return res;
2152}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002153
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002154// Resume after internalPauseAndWaitLocked
2155status_t Camera3Device::internalResumeLocked() {
2156 status_t res;
2157
2158 mRequestThread->setPaused(false);
2159
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002160 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2161 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002162 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2163 if (res != OK) {
2164 SET_ERR_L("Can't transition to active in %f seconds!",
2165 kActiveTimeout/1e9);
2166 }
2167 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002168 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002169}
2170
Ruben Brunk183f0562015-08-12 12:55:02 -07002171status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002172 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002173
2174 size_t startIndex = 0;
2175 if (mStatusWaiters == 0) {
2176 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2177 // this status list
2178 mRecentStatusUpdates.clear();
2179 } else {
2180 // If other threads are waiting on updates to this status list, set the position of the
2181 // first element that this list will check rather than clearing the list.
2182 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002183 }
2184
Ruben Brunk183f0562015-08-12 12:55:02 -07002185 mStatusWaiters++;
2186
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002187 // Notify HAL to start draining. We need to notify the HalInterface layer
2188 // even when the device is already IDLE, so HalInterface can reject incoming
2189 // requestStreamBuffers call.
2190 if (!active && mUseHalBufManager) {
2191 auto streamIds = mOutputStreams.getStreamIds();
2192 mRequestThread->signalPipelineDrain(streamIds);
2193 mRequestBufferSM.onWaitUntilIdle();
2194 }
2195
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002196 bool stateSeen = false;
2197 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002198 if (active == (mStatus == STATUS_ACTIVE)) {
2199 // Desired state is current
2200 break;
2201 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002202
2203 res = mStatusChanged.waitRelative(mLock, timeout);
2204 if (res != OK) break;
2205
Ruben Brunk183f0562015-08-12 12:55:02 -07002206 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2207 // transitions.
2208 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2209 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2210 __FUNCTION__);
2211
2212 // Encountered desired state since we began waiting
2213 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002214 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2215 stateSeen = true;
2216 break;
2217 }
2218 }
2219 } while (!stateSeen);
2220
Ruben Brunk183f0562015-08-12 12:55:02 -07002221 mStatusWaiters--;
2222
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002223 return res;
2224}
2225
2226
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002227status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002228 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002229 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002230
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002231 if (listener != NULL && mListener != NULL) {
2232 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2233 }
2234 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002235 mRequestThread->setNotificationListener(listener);
2236 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002237
2238 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002239}
2240
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002241bool Camera3Device::willNotify3A() {
2242 return false;
2243}
2244
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002245status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002246 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002247 status_t res;
2248 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002249
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002250 while (mResultQueue.empty()) {
2251 res = mResultSignal.waitRelative(mOutputLock, timeout);
2252 if (res == TIMED_OUT) {
2253 return res;
2254 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002255 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2256 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002257 return res;
2258 }
2259 }
2260 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002261}
2262
Jianing Weicb0652e2014-03-12 18:29:36 -07002263status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002264 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002265 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002266
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002267 if (mResultQueue.empty()) {
2268 return NOT_ENOUGH_DATA;
2269 }
2270
Jianing Weicb0652e2014-03-12 18:29:36 -07002271 if (frame == NULL) {
2272 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2273 return BAD_VALUE;
2274 }
2275
2276 CaptureResult &result = *(mResultQueue.begin());
2277 frame->mResultExtras = result.mResultExtras;
2278 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002279 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002280 mResultQueue.erase(mResultQueue.begin());
2281
2282 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002283}
2284
2285status_t Camera3Device::triggerAutofocus(uint32_t id) {
2286 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002287 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002288
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002289 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2290 // Mix-in this trigger into the next request and only the next request.
2291 RequestTrigger trigger[] = {
2292 {
2293 ANDROID_CONTROL_AF_TRIGGER,
2294 ANDROID_CONTROL_AF_TRIGGER_START
2295 },
2296 {
2297 ANDROID_CONTROL_AF_TRIGGER_ID,
2298 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002299 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002300 };
2301
2302 return mRequestThread->queueTrigger(trigger,
2303 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002304}
2305
2306status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2307 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002308 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002309
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002310 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2311 // Mix-in this trigger into the next request and only the next request.
2312 RequestTrigger trigger[] = {
2313 {
2314 ANDROID_CONTROL_AF_TRIGGER,
2315 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2316 },
2317 {
2318 ANDROID_CONTROL_AF_TRIGGER_ID,
2319 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002320 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002321 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002322
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002323 return mRequestThread->queueTrigger(trigger,
2324 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002325}
2326
2327status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2328 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002329 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002330
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002331 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2332 // Mix-in this trigger into the next request and only the next request.
2333 RequestTrigger trigger[] = {
2334 {
2335 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2336 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2337 },
2338 {
2339 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2340 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002341 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002342 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002343
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002344 return mRequestThread->queueTrigger(trigger,
2345 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002346}
2347
Jianing Weicb0652e2014-03-12 18:29:36 -07002348status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002349 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002350 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002351 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002352
Zhijun He7ef20392014-04-21 16:04:17 -07002353 {
2354 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002355
2356 // b/116514106 "disconnect()" can get called twice for the same device. The
2357 // camera device will not be initialized during the second run.
2358 if (mStatus == STATUS_UNINITIALIZED) {
2359 return OK;
2360 }
2361
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002362 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002363 }
2364
Emilian Peev08dd2452017-04-06 16:55:14 +01002365 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002366}
2367
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002368status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002369 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2370}
2371
2372status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002373 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002374 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002375 Mutex::Autolock il(mInterfaceLock);
2376 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002377
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002378 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2379 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002380 CLOGE("Stream %d does not exist", streamId);
2381 return BAD_VALUE;
2382 }
2383
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002384 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002385 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002386 return BAD_VALUE;
2387 }
2388
2389 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002390 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002391 return BAD_VALUE;
2392 }
2393
Ruben Brunkc78ac262015-08-13 17:58:46 -07002394 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002395}
2396
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002397status_t Camera3Device::tearDown(int streamId) {
2398 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002399 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002400 Mutex::Autolock il(mInterfaceLock);
2401 Mutex::Autolock l(mLock);
2402
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002403 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2404 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002405 CLOGE("Stream %d does not exist", streamId);
2406 return BAD_VALUE;
2407 }
2408
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002409 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2410 CLOGE("Stream %d is a target of a in-progress request", streamId);
2411 return BAD_VALUE;
2412 }
2413
2414 return stream->tearDown();
2415}
2416
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002417status_t Camera3Device::addBufferListenerForStream(int streamId,
2418 wp<Camera3StreamBufferListener> listener) {
2419 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002420 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002421 Mutex::Autolock il(mInterfaceLock);
2422 Mutex::Autolock l(mLock);
2423
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002424 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2425 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002426 CLOGE("Stream %d does not exist", streamId);
2427 return BAD_VALUE;
2428 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002429 stream->addBufferListener(listener);
2430
2431 return OK;
2432}
2433
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002434/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002435 * Methods called by subclasses
2436 */
2437
2438void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002439 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002440 {
2441 // Need mLock to safely update state and synchronize to current
2442 // state of methods in flight.
2443 Mutex::Autolock l(mLock);
2444 // We can get various system-idle notices from the status tracker
2445 // while starting up. Only care about them if we've actually sent
2446 // in some requests recently.
2447 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2448 return;
2449 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002450 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2451 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002452 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002453
2454 // Skip notifying listener if we're doing some user-transparent
2455 // state changes
2456 if (mPauseStateNotify) return;
2457 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002458
2459 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002460 {
2461 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002462 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002463 }
2464 if (idle && listener != NULL) {
2465 listener->notifyIdle();
2466 }
2467}
2468
Shuzhen Wang758c2152017-01-10 18:26:18 -08002469status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002470 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002471 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002472 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2473 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002474
2475 if (surfaceIds == nullptr) {
2476 return BAD_VALUE;
2477 }
2478
Zhijun He5d677d12016-05-29 16:52:39 -07002479 Mutex::Autolock il(mInterfaceLock);
2480 Mutex::Autolock l(mLock);
2481
Shuzhen Wang758c2152017-01-10 18:26:18 -08002482 if (consumers.size() == 0) {
2483 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002484 return BAD_VALUE;
2485 }
2486
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002487 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2488 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002489 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002490 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002491 }
Shuzhen Wang758c2152017-01-10 18:26:18 -08002492 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002493 if (res != OK) {
2494 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2495 return res;
2496 }
2497
Emilian Peev40ead602017-09-26 15:46:36 +01002498 for (auto &consumer : consumers) {
2499 int id = stream->getSurfaceId(consumer);
2500 if (id < 0) {
2501 CLOGE("Invalid surface id!");
2502 return BAD_VALUE;
2503 }
2504 surfaceIds->push_back(id);
2505 }
2506
Shuzhen Wang0129d522016-10-30 22:43:41 -07002507 if (stream->isConsumerConfigurationDeferred()) {
2508 if (!stream->isConfiguring()) {
2509 CLOGE("Stream %d was already fully configured.", streamId);
2510 return INVALID_OPERATION;
2511 }
Zhijun He5d677d12016-05-29 16:52:39 -07002512
Shuzhen Wang0129d522016-10-30 22:43:41 -07002513 res = stream->finishConfiguration();
2514 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002515 // If finishConfiguration fails due to abandoned surface, do not set
2516 // device to error state.
2517 bool isSurfaceAbandoned =
2518 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2519 if (!isSurfaceAbandoned) {
2520 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2521 stream->getId(), strerror(-res), res);
2522 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002523 return res;
2524 }
Zhijun He5d677d12016-05-29 16:52:39 -07002525 }
2526
2527 return OK;
2528}
2529
Emilian Peev40ead602017-09-26 15:46:36 +01002530status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2531 const std::vector<OutputStreamInfo> &outputInfo,
2532 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2533 Mutex::Autolock il(mInterfaceLock);
2534 Mutex::Autolock l(mLock);
2535
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002536 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2537 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002538 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002539 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002540 }
2541
2542 for (const auto &it : removedSurfaceIds) {
2543 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2544 CLOGE("Shared surface still part of a pending request!");
2545 return -EBUSY;
2546 }
2547 }
2548
Emilian Peev40ead602017-09-26 15:46:36 +01002549 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2550 if (res != OK) {
2551 CLOGE("Stream %d failed to update stream (error %d %s) ",
2552 streamId, res, strerror(-res));
2553 if (res == UNKNOWN_ERROR) {
2554 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2555 __FUNCTION__);
2556 }
2557 return res;
2558 }
2559
2560 return res;
2561}
2562
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002563status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2564 Mutex::Autolock il(mInterfaceLock);
2565 Mutex::Autolock l(mLock);
2566
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002567 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2568 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002569 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2570 return BAD_VALUE;
2571 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002572 return stream->dropBuffers(dropping);
2573}
2574
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002575/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002576 * Camera3Device private methods
2577 */
2578
2579sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002580 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002581 ATRACE_CALL();
2582 status_t res;
2583
2584 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002585 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002586
2587 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002588 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002589 if (inputStreams.count > 0) {
2590 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002591 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002592 CLOGE("Request references unknown input stream %d",
2593 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002594 return NULL;
2595 }
2596 // Lazy completion of stream configuration (allocation/registration)
2597 // on first use
2598 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002599 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002600 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002601 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002602 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002603 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002604 return NULL;
2605 }
2606 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002607 // Check if stream prepare is blocking requests.
2608 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002609 CLOGE("Request references an input stream that's being prepared!");
2610 return NULL;
2611 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002612
2613 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002614 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002615 }
2616
2617 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002618 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002619 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002620 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002621 return NULL;
2622 }
2623
2624 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002625 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2626 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002627 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002628 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002629 return NULL;
2630 }
Zhijun He5d677d12016-05-29 16:52:39 -07002631 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002632 auto iter = surfaceMap.find(streams.data.i32[i]);
2633 if (iter != surfaceMap.end()) {
2634 const std::vector<size_t>& surfaces = iter->second;
2635 for (const auto& surface : surfaces) {
2636 if (stream->isConsumerConfigurationDeferred(surface)) {
2637 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2638 "due to deferred consumer", stream->getId(), surface);
2639 return NULL;
2640 }
2641 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002642 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002643 }
2644
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002645 // Lazy completion of stream configuration (allocation/registration)
2646 // on first use
2647 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002648 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002649 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002650 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2651 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002652 return NULL;
2653 }
2654 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002655 // Check if stream prepare is blocking requests.
2656 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002657 CLOGE("Request references an output stream that's being prepared!");
2658 return NULL;
2659 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002660
2661 newRequest->mOutputStreams.push(stream);
2662 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002663 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002664 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002665
2666 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002667}
2668
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002669bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2670 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2671 Size size = mSupportedOpaqueInputSizes[i];
2672 if (size.width == width && size.height == height) {
2673 return true;
2674 }
2675 }
2676
2677 return false;
2678}
2679
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002680void Camera3Device::cancelStreamsConfigurationLocked() {
2681 int res = OK;
2682 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2683 res = mInputStream->cancelConfiguration();
2684 if (res != OK) {
2685 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2686 mInputStream->getId(), strerror(-res), res);
2687 }
2688 }
2689
2690 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002691 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002692 if (outputStream->isConfiguring()) {
2693 res = outputStream->cancelConfiguration();
2694 if (res != OK) {
2695 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2696 outputStream->getId(), strerror(-res), res);
2697 }
2698 }
2699 }
2700
2701 // Return state to that at start of call, so that future configures
2702 // properly clean things up
2703 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2704 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002705
2706 res = mPreparerThread->resume();
2707 if (res != OK) {
2708 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2709 }
2710}
2711
2712bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2713 ATRACE_CALL();
2714 bool ret = false;
2715
2716 Mutex::Autolock il(mInterfaceLock);
2717 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2718
2719 Mutex::Autolock l(mLock);
2720 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2721 if (rc == NO_ERROR) {
2722 mNeedConfig = true;
2723 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2724 if (rc == NO_ERROR) {
2725 ret = true;
2726 mPauseStateNotify = false;
2727 //Moving to active state while holding 'mLock' is important.
2728 //There could be pending calls to 'create-/deleteStream' which
2729 //will trigger another stream configuration while the already
2730 //present streams end up with outstanding buffers that will
2731 //not get drained.
2732 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002733 } else if (rc == DEAD_OBJECT) {
2734 // DEAD_OBJECT can be returned if either the consumer surface is
2735 // abandoned, or the HAL has died.
2736 // - If the HAL has died, configureStreamsLocked call will set
2737 // device to error state,
2738 // - If surface is abandoned, we should not set device to error
2739 // state.
2740 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002741 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002742 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002743 }
2744 } else {
2745 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2746 }
2747
2748 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002749}
2750
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002751status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002752 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002753 ATRACE_CALL();
2754 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002755
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002756 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002757 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002758 return INVALID_OPERATION;
2759 }
2760
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002761 if (operatingMode < 0) {
2762 CLOGE("Invalid operating mode: %d", operatingMode);
2763 return BAD_VALUE;
2764 }
2765
2766 bool isConstrainedHighSpeed =
2767 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2768 operatingMode;
2769
2770 if (mOperatingMode != operatingMode) {
2771 mNeedConfig = true;
2772 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2773 mOperatingMode = operatingMode;
2774 }
2775
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002776 if (!mNeedConfig) {
2777 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2778 return OK;
2779 }
2780
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002781 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2782 // adding a dummy stream instead.
2783 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2784 if (mOutputStreams.size() == 0) {
2785 addDummyStreamLocked();
2786 } else {
2787 tryRemoveDummyStreamLocked();
2788 }
2789
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002790 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002791 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002792
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002793 mPreparerThread->pause();
2794
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002795 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002796 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002797 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2798
2799 Vector<camera3_stream_t*> streams;
2800 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002801 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002802
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002803
2804 if (mInputStream != NULL) {
2805 camera3_stream_t *inputStream;
2806 inputStream = mInputStream->startConfiguration();
2807 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002808 CLOGE("Can't start input stream configuration");
2809 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002810 return INVALID_OPERATION;
2811 }
2812 streams.add(inputStream);
2813 }
2814
2815 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002816
2817 // Don't configure bidi streams twice, nor add them twice to the list
2818 if (mOutputStreams[i].get() ==
2819 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2820
2821 config.num_streams--;
2822 continue;
2823 }
2824
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002825 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002826 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002827 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002828 CLOGE("Can't start output stream configuration");
2829 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002830 return INVALID_OPERATION;
2831 }
2832 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002833
2834 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2835 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002836 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2837 // always occupy the initial entry.
2838 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002839 getJpegBufferSize(outputStream->width, outputStream->height));
2840 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002841 }
2842
2843 config.streams = streams.editArray();
2844
2845 // Do the HAL configuration; will potentially touch stream
2846 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002847
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002848 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002849 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002850 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002851
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002852 if (res == BAD_VALUE) {
2853 // HAL rejected this set of streams as unsupported, clean up config
2854 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002855 CLOGE("Set of requested inputs/outputs not supported by HAL");
2856 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002857 return BAD_VALUE;
2858 } else if (res != OK) {
2859 // Some other kind of error from configure_streams - this is not
2860 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002861 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2862 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002863 return res;
2864 }
2865
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002866 // Finish all stream configuration immediately.
2867 // TODO: Try to relax this later back to lazy completion, which should be
2868 // faster
2869
Igor Murashkin073f8572013-05-02 14:59:28 -07002870 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002871 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002872 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002873 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002874 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002875 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002876 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2877 return DEAD_OBJECT;
2878 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002879 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002880 }
2881 }
2882
2883 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002884 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002885 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002886 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002887 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002888 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002889 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002890 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002891 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2892 return DEAD_OBJECT;
2893 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002894 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002895 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002896 }
2897 }
2898
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002899 // Request thread needs to know to avoid using repeat-last-settings protocol
2900 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002901 if (notifyRequestThread) {
2902 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2903 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002904
Zhijun He90f7c372016-08-16 16:19:43 -07002905 char value[PROPERTY_VALUE_MAX];
2906 property_get("camera.fifo.disable", value, "0");
2907 int32_t disableFifo = atoi(value);
2908 if (disableFifo != 1) {
2909 // Boost priority of request thread to SCHED_FIFO.
2910 pid_t requestThreadTid = mRequestThread->getTid();
2911 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002912 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002913 if (res != OK) {
2914 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2915 strerror(-res), res);
2916 } else {
2917 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2918 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002919 }
2920
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002921 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002922 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2923 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2924 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2925 sessionParams.unlock(newSessionParams);
2926 mSessionParams.unlock(currentSessionParams);
2927 if (updateSessionParams) {
2928 mSessionParams = sessionParams;
2929 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002930
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002931 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002932
Ruben Brunk183f0562015-08-12 12:55:02 -07002933 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2934 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002935
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002936 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002937
Zhijun He0a210512014-07-24 13:45:15 -07002938 // tear down the deleted streams after configure streams.
2939 mDeletedStreams.clear();
2940
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002941 auto rc = mPreparerThread->resume();
2942 if (rc != OK) {
2943 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2944 return rc;
2945 }
2946
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002947 if (mDummyStreamId == NO_STREAM) {
2948 mRequestBufferSM.onStreamsConfigured();
2949 }
2950
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002951 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002952}
2953
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002954status_t Camera3Device::addDummyStreamLocked() {
2955 ATRACE_CALL();
2956 status_t res;
2957
2958 if (mDummyStreamId != NO_STREAM) {
2959 // Should never be adding a second dummy stream when one is already
2960 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002961 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2962 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002963 return INVALID_OPERATION;
2964 }
2965
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002966 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002967
2968 sp<Camera3OutputStreamInterface> dummyStream =
2969 new Camera3DummyStream(mNextStreamId);
2970
2971 res = mOutputStreams.add(mNextStreamId, dummyStream);
2972 if (res < 0) {
2973 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2974 return res;
2975 }
2976
2977 mDummyStreamId = mNextStreamId;
2978 mNextStreamId++;
2979
2980 return OK;
2981}
2982
2983status_t Camera3Device::tryRemoveDummyStreamLocked() {
2984 ATRACE_CALL();
2985 status_t res;
2986
2987 if (mDummyStreamId == NO_STREAM) return OK;
2988 if (mOutputStreams.size() == 1) return OK;
2989
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002990 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002991
2992 // Ok, have a dummy stream and there's at least one other output stream,
2993 // so remove the dummy
2994
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002995 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
2996 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002997 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2998 return INVALID_OPERATION;
2999 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003000 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003001
3002 // Free up the stream endpoint so that it can be used by some other stream
3003 res = deletedStream->disconnect();
3004 if (res != OK) {
3005 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3006 // fall through since we want to still list the stream as deleted.
3007 }
3008 mDeletedStreams.add(deletedStream);
3009 mDummyStreamId = NO_STREAM;
3010
3011 return res;
3012}
3013
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003014void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003015 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003016 Mutex::Autolock l(mLock);
3017 va_list args;
3018 va_start(args, fmt);
3019
3020 setErrorStateLockedV(fmt, args);
3021
3022 va_end(args);
3023}
3024
3025void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003026 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003027 Mutex::Autolock l(mLock);
3028 setErrorStateLockedV(fmt, args);
3029}
3030
3031void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3032 va_list args;
3033 va_start(args, fmt);
3034
3035 setErrorStateLockedV(fmt, args);
3036
3037 va_end(args);
3038}
3039
3040void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003041 // Print out all error messages to log
3042 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003043 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003044
3045 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003046 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003047
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003048 mErrorCause = errorCause;
3049
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003050 if (mRequestThread != nullptr) {
3051 mRequestThread->setPaused(true);
3052 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003053 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003054
3055 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003056 sp<NotificationListener> listener = mListener.promote();
3057 if (listener != NULL) {
3058 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003059 CaptureResultExtras());
3060 }
3061
3062 // Save stack trace. View by dumping it later.
3063 CameraTraces::saveTrace();
3064 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003065}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003066
3067/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003068 * In-flight request management
3069 */
3070
Jianing Weicb0652e2014-03-12 18:29:36 -07003071status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003072 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003073 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003074 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003075 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003076 ATRACE_CALL();
3077 Mutex::Autolock l(mInFlightLock);
3078
3079 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003080 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003081 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3082 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003083 if (res < 0) return res;
3084
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003085 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003086 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3087 // avoid a deadlock during reprocess requests.
3088 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003089 if (mStatusTracker != nullptr) {
3090 mStatusTracker->markComponentActive(mInFlightStatusId);
3091 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003092 }
3093
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003094 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003095 return OK;
3096}
3097
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003098void Camera3Device::returnOutputBuffers(
3099 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003100 nsecs_t timestamp, bool timestampIncreasing,
3101 const SurfaceMap& outputSurfaces,
3102 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003103
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003104 for (size_t i = 0; i < numBuffers; i++)
3105 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003106 if (outputBuffers[i].buffer == nullptr) {
3107 if (!mUseHalBufManager) {
3108 // With HAL buffer management API, HAL sometimes will have to return buffers that
3109 // has not got a output buffer handle filled yet. This is though illegal if HAL
3110 // buffer management API is not being used.
3111 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3112 }
3113 continue;
3114 }
3115
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003116 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3117 int streamId = stream->getId();
3118 const auto& it = outputSurfaces.find(streamId);
3119 status_t res = OK;
3120 if (it != outputSurfaces.end()) {
3121 res = stream->returnBuffer(
3122 outputBuffers[i], timestamp, timestampIncreasing, it->second);
3123 } else {
3124 res = stream->returnBuffer(
3125 outputBuffers[i], timestamp, timestampIncreasing);
3126 }
3127
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003128 // Note: stream may be deallocated at this point, if this buffer was
3129 // the last reference to it.
3130 if (res != OK) {
3131 ALOGE("Can't return buffer to its stream: %s (%d)",
3132 strerror(-res), res);
3133 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003134
3135 // Long processing consumers can cause returnBuffer timeout for shared stream
3136 // If that happens, cancel the buffer and send a buffer error to client
3137 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3138 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3139 // cancel the buffer
3140 camera3_stream_buffer_t sb = outputBuffers[i];
3141 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
3142 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing);
3143
3144 // notify client buffer error
3145 sp<NotificationListener> listener;
3146 {
3147 Mutex::Autolock l(mOutputLock);
3148 listener = mListener.promote();
3149 }
3150
3151 if (listener != nullptr) {
3152 CaptureResultExtras extras = inResultExtras;
3153 extras.errorStreamId = streamId;
3154 listener->notifyError(
3155 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3156 extras);
3157 }
3158 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003159 }
3160}
3161
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003162void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003163 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003164 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003165 mInFlightMap.removeItemsAt(idx, 1);
3166
3167 // Indicate idle inFlightMap to the status tracker
3168 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003169 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003170 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3171 // avoid a deadlock during reprocess requests.
3172 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003173 if (mStatusTracker != nullptr) {
3174 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3175 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003176 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003177 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003178}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003179
3180void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3181
3182 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3183 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3184
3185 nsecs_t sensorTimestamp = request.sensorTimestamp;
3186 nsecs_t shutterTimestamp = request.shutterTimestamp;
3187
3188 // Check if it's okay to remove the request from InFlightMap:
3189 // In the case of a successful request:
3190 // all input and output buffers, all result metadata, shutter callback
3191 // arrived.
3192 // In the case of a unsuccessful request:
3193 // all input and output buffers arrived.
3194 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003195 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003196 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003197 if (request.stillCapture) {
3198 ATRACE_ASYNC_END("still capture", frameNumber);
3199 }
3200
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003201 ATRACE_ASYNC_END("frame capture", frameNumber);
3202
Shuzhen Wang403044a2017-02-26 23:29:04 -08003203 // Sanity check - if sensor timestamp matches shutter timestamp in the
3204 // case of request having callback.
3205 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003206 sensorTimestamp != shutterTimestamp) {
3207 SET_ERR("sensor timestamp (%" PRId64
3208 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3209 sensorTimestamp, frameNumber, shutterTimestamp);
3210 }
3211
3212 // for an unsuccessful request, it may have pending output buffers to
3213 // return.
3214 assert(request.requestStatus != OK ||
3215 request.pendingOutputBuffers.size() == 0);
3216 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003217 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3218 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003219
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003220 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003221 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3222 }
3223
3224 // Sanity check - if we have too many in-flight frames, something has
3225 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003226 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003227 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003228 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3229 kInFlightWarnLimitHighSpeed) {
3230 CLOGE("In-flight list too large for high speed configuration: %zu",
3231 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003232 }
3233}
3234
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003235void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003236 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003237 { // First return buffers cached in mInFlightMap
3238 Mutex::Autolock l(mInFlightLock);
3239 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3240 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3241 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003242 request.pendingOutputBuffers.size(), 0,
3243 /*timestampIncreasing*/true, request.outputSurfaces,
3244 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003245 }
3246 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003247 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003248 }
3249
3250 // Then return all inflight buffers not returned by HAL
3251 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3252 mInterface->getInflightBufferKeys(&inflightKeys);
3253
3254 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3255 for (auto& pair : inflightKeys) {
3256 int32_t frameNumber = pair.first;
3257 int32_t streamId = pair.second;
3258 buffer_handle_t* buffer;
3259 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3260 if (res != OK) {
3261 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3262 __FUNCTION__, frameNumber, streamId);
3263 continue;
3264 }
3265
3266 camera3_stream_buffer_t streamBuffer;
3267 streamBuffer.buffer = buffer;
3268 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3269 streamBuffer.acquire_fence = -1;
3270 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003271
3272 // First check if the buffer belongs to deleted stream
3273 bool streamDeleted = false;
3274 for (auto& stream : mDeletedStreams) {
3275 if (streamId == stream->getId()) {
3276 streamDeleted = true;
3277 // Return buffer to deleted stream
3278 camera3_stream* halStream = stream->asHalStream();
3279 streamBuffer.stream = halStream;
3280 switch (halStream->stream_type) {
3281 case CAMERA3_STREAM_OUTPUT:
3282 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
3283 if (res != OK) {
3284 ALOGE("%s: Can't return output buffer for frame %d to"
3285 " stream %d: %s (%d)", __FUNCTION__,
3286 frameNumber, streamId, strerror(-res), res);
3287 }
3288 break;
3289 case CAMERA3_STREAM_INPUT:
3290 res = stream->returnInputBuffer(streamBuffer);
3291 if (res != OK) {
3292 ALOGE("%s: Can't return input buffer for frame %d to"
3293 " stream %d: %s (%d)", __FUNCTION__,
3294 frameNumber, streamId, strerror(-res), res);
3295 }
3296 break;
3297 default: // Bi-direcitonal stream is deprecated
3298 ALOGE("%s: stream %d has unknown stream type %d",
3299 __FUNCTION__, streamId, halStream->stream_type);
3300 break;
3301 }
3302 break;
3303 }
3304 }
3305 if (streamDeleted) {
3306 continue;
3307 }
3308
3309 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003310 if (streamId == inputStreamId) {
3311 streamBuffer.stream = mInputStream->asHalStream();
3312 res = mInputStream->returnInputBuffer(streamBuffer);
3313 if (res != OK) {
3314 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003315 " stream %d: %s (%d)", __FUNCTION__,
3316 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003317 }
3318 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003319 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3320 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003321 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3322 continue;
3323 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003324 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003325 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3326 }
3327 }
3328}
3329
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003330void Camera3Device::insertResultLocked(CaptureResult *result,
3331 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003332 if (result == nullptr) return;
3333
Emilian Peev71c73a22017-03-21 16:35:51 +00003334 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3335 result->mMetadata.getAndLock());
3336 set_camera_metadata_vendor_id(meta, mVendorTagId);
3337 result->mMetadata.unlock(meta);
3338
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003339 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3340 (int32_t*)&frameNumber, 1) != OK) {
3341 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3342 return;
3343 }
3344
3345 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3346 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3347 return;
3348 }
3349
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003350 // Valid result, insert into queue
3351 List<CaptureResult>::iterator queuedResult =
3352 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3353 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3354 ", burstId = %" PRId32, __FUNCTION__,
3355 queuedResult->mResultExtras.requestId,
3356 queuedResult->mResultExtras.frameNumber,
3357 queuedResult->mResultExtras.burstId);
3358
3359 mResultSignal.signal();
3360}
3361
3362
3363void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003364 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003365 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003366 Mutex::Autolock l(mOutputLock);
3367
3368 CaptureResult captureResult;
3369 captureResult.mResultExtras = resultExtras;
3370 captureResult.mMetadata = partialResult;
3371
Shuzhen Wang268a1362018-10-16 16:32:59 -07003372 // Fix up result metadata for monochrome camera.
3373 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3374 if (res != OK) {
3375 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3376 return;
3377 }
3378
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003379 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003380}
3381
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003382
3383void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3384 CaptureResultExtras &resultExtras,
3385 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003386 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003387 bool reprocess,
3388 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003389 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003390 if (pendingMetadata.isEmpty())
3391 return;
3392
3393 Mutex::Autolock l(mOutputLock);
3394
3395 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003396 if (reprocess) {
3397 if (frameNumber < mNextReprocessResultFrameNumber) {
3398 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003399 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003400 frameNumber, mNextReprocessResultFrameNumber);
3401 return;
3402 }
3403 mNextReprocessResultFrameNumber = frameNumber + 1;
3404 } else {
3405 if (frameNumber < mNextResultFrameNumber) {
3406 SET_ERR("Out-of-order capture result metadata submitted! "
3407 "(got frame number %d, expecting %d)",
3408 frameNumber, mNextResultFrameNumber);
3409 return;
3410 }
3411 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003412 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003413
3414 CaptureResult captureResult;
3415 captureResult.mResultExtras = resultExtras;
3416 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003417 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003418
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003419 // Append any previous partials to form a complete result
3420 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3421 captureResult.mMetadata.append(collectedPartialResult);
3422 }
3423
3424 captureResult.mMetadata.sort();
3425
3426 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003427 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3428 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003429 SET_ERR("No timestamp provided by HAL for frame %d!",
3430 frameNumber);
3431 return;
3432 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003433 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3434 camera_metadata_entry timestamp =
3435 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3436 if (timestamp.count == 0) {
3437 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3438 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3439 return;
3440 }
3441 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003442
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003443 // Fix up some result metadata to account for HAL-level distortion correction
3444 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3445 if (res != OK) {
3446 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3447 frameNumber, strerror(res), res);
3448 return;
3449 }
Shuzhen Wang268a1362018-10-16 16:32:59 -07003450 // Fix up result metadata for monochrome camera.
3451 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3452 if (res != OK) {
3453 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3454 return;
3455 }
3456 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3457 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3458 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3459 physicalMetadata.mPhysicalCameraMetadata);
3460 if (res != OK) {
3461 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3462 return;
3463 }
3464 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003465
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003466 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3467 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3468
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003469 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003470}
3471
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003472/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003473 * Camera HAL device callback methods
3474 */
3475
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003476void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003477 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003478
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003479 status_t res;
3480
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003481 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003482 if (result->result == NULL && result->num_output_buffers == 0 &&
3483 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003484 SET_ERR("No result data provided by HAL for frame %d",
3485 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003486 return;
3487 }
Zhijun He204e3292014-07-14 17:09:23 -07003488
Zhijun He204e3292014-07-14 17:09:23 -07003489 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003490 result->result != NULL &&
3491 result->partial_result != 1) {
3492 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3493 " if partial result is not supported",
3494 frameNumber, result->partial_result);
3495 return;
3496 }
3497
3498 bool isPartialResult = false;
3499 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003500 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003501
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003502 // Get shutter timestamp and resultExtras from list of in-flight requests,
3503 // where it was added by the shutter notification for this frame. If the
3504 // shutter timestamp isn't received yet, append the output buffers to the
3505 // in-flight request and they will be returned when the shutter timestamp
3506 // arrives. Update the in-flight status and remove the in-flight entry if
3507 // all result data and shutter timestamp have been received.
3508 nsecs_t shutterTimestamp = 0;
3509
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003510 {
3511 Mutex::Autolock l(mInFlightLock);
3512 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3513 if (idx == NAME_NOT_FOUND) {
3514 SET_ERR("Unknown frame number for capture result: %d",
3515 frameNumber);
3516 return;
3517 }
3518 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003519 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3520 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003521 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003522 __FUNCTION__, request.resultExtras.requestId,
3523 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003524 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003525 // Always update the partial count to the latest one if it's not 0
3526 // (buffers only). When framework aggregates adjacent partial results
3527 // into one, the latest partial count will be used.
3528 if (result->partial_result != 0)
3529 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003530
3531 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003532 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003533 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3534 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3535 " the range of [1, %d] when metadata is included in the result",
3536 frameNumber, result->partial_result, mNumPartialResults);
3537 return;
3538 }
3539 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003540 if (isPartialResult && result->num_physcam_metadata) {
3541 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3542 " physical camera result", frameNumber);
3543 return;
3544 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003545 if (isPartialResult) {
3546 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003547 }
3548
Shuzhen Wang4a472662017-02-26 23:29:04 -08003549 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003550 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003551 sendPartialCaptureResult(result->result, request.resultExtras,
3552 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003553 }
3554 }
3555
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003556 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003557 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003558
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003559 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003560 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003561 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3562 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3563 request.physicalCameraIds.size(), result->num_physcam_metadata);
3564 return;
3565 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003566 if (request.haveResultMetadata) {
3567 SET_ERR("Called multiple times with metadata for frame %d",
3568 frameNumber);
3569 return;
3570 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003571 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3572 String8 physicalId(result->physcam_ids[i]);
3573 std::set<String8>::iterator cameraIdIter =
3574 request.physicalCameraIds.find(physicalId);
3575 if (cameraIdIter != request.physicalCameraIds.end()) {
3576 request.physicalCameraIds.erase(cameraIdIter);
3577 } else {
3578 SET_ERR("Total result for frame %d has already returned for camera %s",
3579 frameNumber, physicalId.c_str());
3580 return;
3581 }
3582 }
Zhijun He204e3292014-07-14 17:09:23 -07003583 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003584 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003585 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003586 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003587 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003588 request.haveResultMetadata = true;
3589 }
3590
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003591 uint32_t numBuffersReturned = result->num_output_buffers;
3592 if (result->input_buffer != NULL) {
3593 if (hasInputBufferInRequest) {
3594 numBuffersReturned += 1;
3595 } else {
3596 ALOGW("%s: Input buffer should be NULL if there is no input"
3597 " buffer sent in the request",
3598 __FUNCTION__);
3599 }
3600 }
3601 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003602 if (request.numBuffersLeft < 0) {
3603 SET_ERR("Too many buffers returned for frame %d",
3604 frameNumber);
3605 return;
3606 }
3607
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003608 camera_metadata_ro_entry_t entry;
3609 res = find_camera_metadata_ro_entry(result->result,
3610 ANDROID_SENSOR_TIMESTAMP, &entry);
3611 if (res == OK && entry.count == 1) {
3612 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003613 }
3614
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003615 // If shutter event isn't received yet, append the output buffers to
3616 // the in-flight request. Otherwise, return the output buffers to
3617 // streams.
3618 if (shutterTimestamp == 0) {
3619 request.pendingOutputBuffers.appendArray(result->output_buffers,
3620 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003621 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003622 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003623 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003624 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3625 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003626 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003627
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003628 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003629 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3630 CameraMetadata physicalMetadata;
3631 physicalMetadata.append(result->physcam_metadata[i]);
3632 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3633 physicalMetadata});
3634 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003635 if (shutterTimestamp == 0) {
3636 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003637 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003638 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003639 CameraMetadata metadata;
3640 metadata = result->result;
3641 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003642 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003643 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003644 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003645 }
3646
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003647 removeInFlightRequestIfReadyLocked(idx);
3648 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003649
Zhijun Hef0d962a2014-06-30 10:24:11 -07003650 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003651 if (hasInputBufferInRequest) {
3652 Camera3Stream *stream =
3653 Camera3Stream::cast(result->input_buffer->stream);
3654 res = stream->returnInputBuffer(*(result->input_buffer));
3655 // Note: stream may be deallocated at this point, if this buffer was the
3656 // last reference to it.
3657 if (res != OK) {
3658 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3659 " its stream:%s (%d)", __FUNCTION__,
3660 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003661 }
3662 } else {
3663 ALOGW("%s: Input buffer should be NULL if there is no input"
3664 " buffer sent in the request, skipping input buffer return.",
3665 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003666 }
3667 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003668}
3669
3670void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003671 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003672 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003673 {
3674 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003675 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003676 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003677
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003678 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003679 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003680 return;
3681 }
3682
3683 switch (msg->type) {
3684 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003685 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003686 break;
3687 }
3688 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003689 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003690 break;
3691 }
3692 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003693 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003694 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003695 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003696}
3697
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003698void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003699 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003700 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003701 // Map camera HAL error codes to ICameraDeviceCallback error codes
3702 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003703 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003704 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003705 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003706 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003707 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003708 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003709 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003710 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003711 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003712 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003713 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003714 };
3715
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003716 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003717 ((msg.error_code >= 0) &&
3718 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3719 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003720 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003721
3722 int streamId = 0;
3723 if (msg.error_stream != NULL) {
3724 Camera3Stream *stream =
3725 Camera3Stream::cast(msg.error_stream);
3726 streamId = stream->getId();
3727 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003728 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3729 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003730 streamId, msg.error_code);
3731
3732 CaptureResultExtras resultExtras;
3733 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003734 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003735 // SET_ERR calls notifyError
3736 SET_ERR("Camera HAL reported serious device error");
3737 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003738 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3739 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3740 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003741 {
3742 Mutex::Autolock l(mInFlightLock);
3743 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3744 if (idx >= 0) {
3745 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3746 r.requestStatus = msg.error_code;
3747 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003748 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3749 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3750 errorCode) {
3751 r.skipResultMetadata = true;
3752 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003753 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3754 errorCode) {
3755 // In case of missing result check whether the buffers
3756 // returned. If they returned, then remove inflight
3757 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003758 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3759 // otherwise we are depending on HAL to send the buffers back after
3760 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003761 removeInFlightRequestIfReadyLocked(idx);
3762 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003763 } else {
3764 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003765 ALOGE("Camera %s: %s: cannot find in-flight request on "
3766 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003767 resultExtras.frameNumber);
3768 }
3769 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003770 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003771 if (listener != NULL) {
3772 listener->notifyError(errorCode, resultExtras);
3773 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003774 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003775 }
3776 break;
3777 default:
3778 // SET_ERR calls notifyError
3779 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3780 break;
3781 }
3782}
3783
3784void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003785 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003786 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003787 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003788
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003789 // Set timestamp for the request in the in-flight tracking
3790 // and get the request ID to send upstream
3791 {
3792 Mutex::Autolock l(mInFlightLock);
3793 idx = mInFlightMap.indexOfKey(msg.frame_number);
3794 if (idx >= 0) {
3795 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003796
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003797 // Verify ordering of shutter notifications
3798 {
3799 Mutex::Autolock l(mOutputLock);
3800 // TODO: need to track errors for tighter bounds on expected frame number.
3801 if (r.hasInputBuffer) {
3802 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3803 SET_ERR("Shutter notification out-of-order. Expected "
3804 "notification for frame %d, got frame %d",
3805 mNextReprocessShutterFrameNumber, msg.frame_number);
3806 return;
3807 }
3808 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3809 } else {
3810 if (msg.frame_number < mNextShutterFrameNumber) {
3811 SET_ERR("Shutter notification out-of-order. Expected "
3812 "notification for frame %d, got frame %d",
3813 mNextShutterFrameNumber, msg.frame_number);
3814 return;
3815 }
3816 mNextShutterFrameNumber = msg.frame_number + 1;
3817 }
3818 }
3819
Shuzhen Wang4a472662017-02-26 23:29:04 -08003820 r.shutterTimestamp = msg.timestamp;
3821 if (r.hasCallback) {
3822 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003823 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003824 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003825 // Call listener, if any
3826 if (listener != NULL) {
3827 listener->notifyShutter(r.resultExtras, msg.timestamp);
3828 }
3829 // send pending result and buffers
3830 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3831 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003832 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003833 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003834 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003835 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003836 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3837 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003838 r.pendingOutputBuffers.clear();
3839
3840 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003841 }
3842 }
3843 if (idx < 0) {
3844 SET_ERR("Shutter notification for non-existent frame number %d",
3845 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003846 }
3847}
3848
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003849CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003850 ALOGV("%s", __FUNCTION__);
3851
Igor Murashkin1e479c02013-09-06 16:55:14 -07003852 CameraMetadata retVal;
3853
3854 if (mRequestThread != NULL) {
3855 retVal = mRequestThread->getLatestRequest();
3856 }
3857
Igor Murashkin1e479c02013-09-06 16:55:14 -07003858 return retVal;
3859}
3860
Jianing Weicb0652e2014-03-12 18:29:36 -07003861
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003862void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3863 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3864 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3865}
3866
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003867/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003868 * HalInterface inner class methods
3869 */
3870
Yifan Hongf79b5542017-04-11 14:44:25 -07003871Camera3Device::HalInterface::HalInterface(
3872 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003873 std::shared_ptr<RequestMetadataQueue> queue,
3874 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003875 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003876 mRequestMetadataQueue(queue),
3877 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003878 // Check with hardware service manager if we can downcast these interfaces
3879 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003880 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3881 if (castResult_3_5.isOk()) {
3882 mHidlSession_3_5 = castResult_3_5;
3883 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003884 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3885 if (castResult_3_4.isOk()) {
3886 mHidlSession_3_4 = castResult_3_4;
3887 }
3888 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3889 if (castResult_3_3.isOk()) {
3890 mHidlSession_3_3 = castResult_3_3;
3891 }
3892}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003893
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003894Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003895
3896Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003897 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003898 mRequestMetadataQueue(other.mRequestMetadataQueue),
3899 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003900
3901bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003902 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003903}
3904
3905void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003906 mHidlSession_3_4.clear();
3907 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003908 mHidlSession.clear();
3909}
3910
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003911bool Camera3Device::HalInterface::supportBatchRequest() {
3912 return mHidlSession != nullptr;
3913}
3914
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003915status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3916 camera3_request_template_t templateId,
3917 /*out*/ camera_metadata_t **requestTemplate) {
3918 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3919 if (!valid()) return INVALID_OPERATION;
3920 status_t res = OK;
3921
Emilian Peev31abd0a2017-05-11 18:37:46 +01003922 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003923
3924 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003925 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003926 status = s;
3927 if (status == common::V1_0::Status::OK) {
3928 const camera_metadata *r =
3929 reinterpret_cast<const camera_metadata_t*>(request.data());
3930 size_t expectedSize = request.size();
3931 int ret = validate_camera_metadata_structure(r, &expectedSize);
3932 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3933 *requestTemplate = clone_camera_metadata(r);
3934 if (*requestTemplate == nullptr) {
3935 ALOGE("%s: Unable to clone camera metadata received from HAL",
3936 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003937 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003938 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003939 } else {
3940 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3941 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003942 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003943 }
3944 };
3945 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003946 RequestTemplate id;
3947 switch (templateId) {
3948 case CAMERA3_TEMPLATE_PREVIEW:
3949 id = RequestTemplate::PREVIEW;
3950 break;
3951 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3952 id = RequestTemplate::STILL_CAPTURE;
3953 break;
3954 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3955 id = RequestTemplate::VIDEO_RECORD;
3956 break;
3957 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3958 id = RequestTemplate::VIDEO_SNAPSHOT;
3959 break;
3960 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3961 id = RequestTemplate::ZERO_SHUTTER_LAG;
3962 break;
3963 case CAMERA3_TEMPLATE_MANUAL:
3964 id = RequestTemplate::MANUAL;
3965 break;
3966 default:
3967 // Unknown template ID, or this HAL is too old to support it
3968 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003969 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003970 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003971
Emilian Peev31abd0a2017-05-11 18:37:46 +01003972 if (!err.isOk()) {
3973 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3974 res = DEAD_OBJECT;
3975 } else {
3976 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003977 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003978
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003979 return res;
3980}
3981
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003982status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003983 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003984 ATRACE_NAME("CameraHal::configureStreams");
3985 if (!valid()) return INVALID_OPERATION;
3986 status_t res = OK;
3987
Emilian Peev31abd0a2017-05-11 18:37:46 +01003988 // Convert stream config to HIDL
3989 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003990 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3991 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3992 requestedConfiguration3_2.streams.resize(config->num_streams);
3993 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003994 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003995 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3996 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003997 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003998
Emilian Peev31abd0a2017-05-11 18:37:46 +01003999 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4000 cam3stream->setBufferFreedListener(this);
4001 int streamId = cam3stream->getId();
4002 StreamType streamType;
4003 switch (src->stream_type) {
4004 case CAMERA3_STREAM_OUTPUT:
4005 streamType = StreamType::OUTPUT;
4006 break;
4007 case CAMERA3_STREAM_INPUT:
4008 streamType = StreamType::INPUT;
4009 break;
4010 default:
4011 ALOGE("%s: Stream %d: Unsupported stream type %d",
4012 __FUNCTION__, streamId, config->streams[i]->stream_type);
4013 return BAD_VALUE;
4014 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004015 dst3_2.id = streamId;
4016 dst3_2.streamType = streamType;
4017 dst3_2.width = src->width;
4018 dst3_2.height = src->height;
4019 dst3_2.format = mapToPixelFormat(src->format);
4020 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
4021 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4022 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
4023 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004024 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004025 if (src->physical_camera_id != nullptr) {
4026 dst3_4.physicalCameraId = src->physical_camera_id;
4027 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004028
4029 activeStreams.insert(streamId);
4030 // Create Buffer ID map if necessary
4031 if (mBufferIdMaps.count(streamId) == 0) {
4032 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4033 }
4034 }
4035 // remove BufferIdMap for deleted streams
4036 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4037 int streamId = it->first;
4038 bool active = activeStreams.count(streamId) > 0;
4039 if (!active) {
4040 it = mBufferIdMaps.erase(it);
4041 } else {
4042 ++it;
4043 }
4044 }
4045
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004046 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004047 res = mapToStreamConfigurationMode(
4048 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004049 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004050 if (res != OK) {
4051 return res;
4052 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004053 requestedConfiguration3_2.operationMode = operationMode;
4054 requestedConfiguration3_4.operationMode = operationMode;
4055 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004056 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4057 get_camera_metadata_size(sessionParams));
4058
Emilian Peev31abd0a2017-05-11 18:37:46 +01004059 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004060 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004061 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004062 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004063
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004064 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004065 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4066 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004067 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004068 };
4069
4070 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4071 (hardware::Return<void>& err) -> status_t {
4072 if (!err.isOk()) {
4073 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4074 return DEAD_OBJECT;
4075 }
4076 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4077 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4078 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4079 }
4080 return OK;
4081 };
4082
4083 // See if we have v3.4 or v3.3 HAL
4084 if (mHidlSession_3_5 != nullptr) {
4085 ALOGV("%s: v3.5 device found", __FUNCTION__);
4086 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4087 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4088 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4089 auto err = mHidlSession_3_5->configureStreams_3_5(
4090 requestedConfiguration3_5, configStream34Cb);
4091 res = postprocConfigStream34(err);
4092 if (res != OK) {
4093 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004094 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004095 } else if (mHidlSession_3_4 != nullptr) {
4096 // We do; use v3.4 for the call
4097 ALOGV("%s: v3.4 device found", __FUNCTION__);
4098 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
4099 auto err = mHidlSession_3_4->configureStreams_3_4(
4100 requestedConfiguration3_4, configStream34Cb);
4101 res = postprocConfigStream34(err);
4102 if (res != OK) {
4103 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004104 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004105 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004106 // We do; use v3.3 for the call
4107 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004108 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004109 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004110 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004111 finalConfiguration = halConfiguration;
4112 status = s;
4113 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004114 if (!err.isOk()) {
4115 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4116 return DEAD_OBJECT;
4117 }
4118 } else {
4119 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4120 ALOGV("%s: v3.2 device found", __FUNCTION__);
4121 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004122 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004123 [&status, &finalConfiguration_3_2]
4124 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4125 finalConfiguration_3_2 = halConfiguration;
4126 status = s;
4127 });
4128 if (!err.isOk()) {
4129 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4130 return DEAD_OBJECT;
4131 }
4132 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4133 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4134 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4135 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004136 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004137 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004138 }
4139
4140 if (status != common::V1_0::Status::OK ) {
4141 return CameraProviderManager::mapToStatusT(status);
4142 }
4143
4144 // And convert output stream configuration from HIDL
4145
4146 for (size_t i = 0; i < config->num_streams; i++) {
4147 camera3_stream_t *dst = config->streams[i];
4148 int streamId = Camera3Stream::cast(dst)->getId();
4149
4150 // Start scan at i, with the assumption that the stream order matches
4151 size_t realIdx = i;
4152 bool found = false;
4153 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004154 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004155 found = true;
4156 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004157 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004158 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4159 }
4160 if (!found) {
4161 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4162 __FUNCTION__, streamId);
4163 return INVALID_OPERATION;
4164 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004165 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004166
Emilian Peev710c1422017-08-30 11:19:38 +01004167 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4168 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004169 dstStream->setDataSpaceOverride(false);
4170 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4171 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4172
Emilian Peev31abd0a2017-05-11 18:37:46 +01004173 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4174 if (dst->format != overrideFormat) {
4175 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4176 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004177 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004178 if (dst->data_space != overrideDataSpace) {
4179 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4180 streamId, dst->format);
4181 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004182 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004183 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004184 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4185
Emilian Peev31abd0a2017-05-11 18:37:46 +01004186 // Override allowed with IMPLEMENTATION_DEFINED
4187 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004188 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004189 }
4190
Emilian Peev31abd0a2017-05-11 18:37:46 +01004191 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004192 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004193 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004194 __FUNCTION__, streamId);
4195 return INVALID_OPERATION;
4196 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004197 dstStream->setUsage(
4198 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004199 } else {
4200 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004201 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004202 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4203 __FUNCTION__, streamId);
4204 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004205 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004206 dstStream->setUsage(
4207 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004208 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004209 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004210 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004211
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004212 return res;
4213}
4214
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004215status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004216 /*out*/device::V3_2::CaptureRequest* captureRequest,
4217 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004218 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004219 if (captureRequest == nullptr || handlesCreated == nullptr) {
4220 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4221 __FUNCTION__, captureRequest, handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004222 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004223 }
4224
4225 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004226
4227 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004228
4229 {
4230 std::lock_guard<std::mutex> lock(mInflightLock);
4231 if (request->input_buffer != nullptr) {
4232 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4233 buffer_handle_t buf = *(request->input_buffer->buffer);
4234 auto pair = getBufferId(buf, streamId);
4235 bool isNewBuffer = pair.first;
4236 uint64_t bufferId = pair.second;
4237 captureRequest->inputBuffer.streamId = streamId;
4238 captureRequest->inputBuffer.bufferId = bufferId;
4239 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4240 captureRequest->inputBuffer.status = BufferStatus::OK;
4241 native_handle_t *acquireFence = nullptr;
4242 if (request->input_buffer->acquire_fence != -1) {
4243 acquireFence = native_handle_create(1,0);
4244 acquireFence->data[0] = request->input_buffer->acquire_fence;
4245 handlesCreated->push_back(acquireFence);
4246 }
4247 captureRequest->inputBuffer.acquireFence = acquireFence;
4248 captureRequest->inputBuffer.releaseFence = nullptr;
4249
4250 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4251 request->input_buffer->buffer,
4252 request->input_buffer->acquire_fence);
4253 } else {
4254 captureRequest->inputBuffer.streamId = -1;
4255 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4256 }
4257
4258 captureRequest->outputBuffers.resize(request->num_output_buffers);
4259 for (size_t i = 0; i < request->num_output_buffers; i++) {
4260 const camera3_stream_buffer_t *src = request->output_buffers + i;
4261 StreamBuffer &dst = captureRequest->outputBuffers[i];
4262 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004263 if (src->buffer != nullptr) {
4264 buffer_handle_t buf = *(src->buffer);
4265 auto pair = getBufferId(buf, streamId);
4266 bool isNewBuffer = pair.first;
4267 dst.bufferId = pair.second;
4268 dst.buffer = isNewBuffer ? buf : nullptr;
4269 native_handle_t *acquireFence = nullptr;
4270 if (src->acquire_fence != -1) {
4271 acquireFence = native_handle_create(1,0);
4272 acquireFence->data[0] = src->acquire_fence;
4273 handlesCreated->push_back(acquireFence);
4274 }
4275 dst.acquireFence = acquireFence;
4276 } else if (mUseHalBufManager) {
4277 // HAL buffer management path
4278 dst.bufferId = BUFFER_ID_NO_BUFFER;
4279 dst.buffer = nullptr;
4280 dst.acquireFence = nullptr;
4281 } else {
4282 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4283 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004284 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004285 dst.streamId = streamId;
4286 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004287 dst.releaseFence = nullptr;
4288
4289 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4290 src->buffer, src->acquire_fence);
4291 }
4292 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004293 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004294}
4295
4296status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4297 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4298 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4299 if (!valid()) return INVALID_OPERATION;
4300
Emilian Peevaebbe412018-01-15 13:53:24 +00004301 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4302 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4303 if (castResult_3_4.isOk()) {
4304 hidlSession_3_4 = castResult_3_4;
4305 }
4306
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004307 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004308 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004309 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004310 if (hidlSession_3_4 != nullptr) {
4311 captureRequests_3_4.resize(batchSize);
4312 } else {
4313 captureRequests.resize(batchSize);
4314 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004315 std::vector<native_handle_t*> handlesCreated;
4316
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004317 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004318 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004319 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004320 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Emilian Peevaebbe412018-01-15 13:53:24 +00004321 /*out*/&handlesCreated);
4322 } else {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004323 res = wrapAsHidlRequest(requests[i],
4324 /*out*/&captureRequests[i], /*out*/&handlesCreated);
4325 }
4326 if (res != OK) {
4327 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004328 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004329 }
4330
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004331 std::vector<device::V3_2::BufferCache> cachesToRemove;
4332 {
4333 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4334 for (auto& pair : mFreedBuffers) {
4335 // The stream might have been removed since onBufferFreed
4336 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4337 cachesToRemove.push_back({pair.first, pair.second});
4338 }
4339 }
4340 mFreedBuffers.clear();
4341 }
4342
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004343 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4344 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004345
4346 // Write metadata to FMQ.
4347 for (size_t i = 0; i < batchSize; i++) {
4348 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004349 device::V3_2::CaptureRequest* captureRequest;
4350 if (hidlSession_3_4 != nullptr) {
4351 captureRequest = &captureRequests_3_4[i].v3_2;
4352 } else {
4353 captureRequest = &captureRequests[i];
4354 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004355
4356 if (request->settings != nullptr) {
4357 size_t settingsSize = get_camera_metadata_size(request->settings);
4358 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4359 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4360 captureRequest->settings.resize(0);
4361 captureRequest->fmqSettingsSize = settingsSize;
4362 } else {
4363 if (mRequestMetadataQueue != nullptr) {
4364 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4365 }
4366 captureRequest->settings.setToExternal(
4367 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4368 get_camera_metadata_size(request->settings));
4369 captureRequest->fmqSettingsSize = 0u;
4370 }
4371 } else {
4372 // A null request settings maps to a size-0 CameraMetadata
4373 captureRequest->settings.resize(0);
4374 captureRequest->fmqSettingsSize = 0u;
4375 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004376
4377 if (hidlSession_3_4 != nullptr) {
4378 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4379 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004380 if (request->physcam_settings != nullptr) {
4381 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4382 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4383 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4384 settingsSize)) {
4385 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4386 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4387 settingsSize;
4388 } else {
4389 if (mRequestMetadataQueue != nullptr) {
4390 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4391 }
4392 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4393 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4394 request->physcam_settings[j])),
4395 get_camera_metadata_size(request->physcam_settings[j]));
4396 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004397 }
Emilian Peev00420d22018-02-05 21:33:13 +00004398 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004399 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004400 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004401 }
4402 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4403 request->physcam_id[j];
4404 }
4405 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004406 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004407
4408 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004409 auto resultCallback =
4410 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4411 status = s;
4412 *numRequestProcessed = n;
4413 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004414 if (hidlSession_3_4 != nullptr) {
4415 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004416 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004417 } else {
4418 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004419 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004420 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004421 if (!err.isOk()) {
4422 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4423 return DEAD_OBJECT;
4424 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004425 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4426 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4427 __FUNCTION__, *numRequestProcessed, batchSize);
4428 status = common::V1_0::Status::INTERNAL_ERROR;
4429 }
4430
4431 for (auto& handle : handlesCreated) {
4432 native_handle_delete(handle);
4433 }
4434 return CameraProviderManager::mapToStatusT(status);
4435}
4436
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004437status_t Camera3Device::HalInterface::processCaptureRequest(
4438 camera3_capture_request_t *request) {
4439 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004440 if (!valid()) return INVALID_OPERATION;
4441 status_t res = OK;
4442
Emilian Peev31abd0a2017-05-11 18:37:46 +01004443 uint32_t numRequestProcessed = 0;
4444 std::vector<camera3_capture_request_t*> requests(1);
4445 requests[0] = request;
4446 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4447
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004448 return res;
4449}
4450
4451status_t Camera3Device::HalInterface::flush() {
4452 ATRACE_NAME("CameraHal::flush");
4453 if (!valid()) return INVALID_OPERATION;
4454 status_t res = OK;
4455
Emilian Peev31abd0a2017-05-11 18:37:46 +01004456 auto err = mHidlSession->flush();
4457 if (!err.isOk()) {
4458 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4459 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004460 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004461 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004462 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004463
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004464 return res;
4465}
4466
Emilian Peev31abd0a2017-05-11 18:37:46 +01004467status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004468 ATRACE_NAME("CameraHal::dump");
4469 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004470
Emilian Peev31abd0a2017-05-11 18:37:46 +01004471 // Handled by CameraProviderManager::dump
4472
4473 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004474}
4475
4476status_t Camera3Device::HalInterface::close() {
4477 ATRACE_NAME("CameraHal::close()");
4478 if (!valid()) return INVALID_OPERATION;
4479 status_t res = OK;
4480
Emilian Peev31abd0a2017-05-11 18:37:46 +01004481 auto err = mHidlSession->close();
4482 // Interface will be dead shortly anyway, so don't log errors
4483 if (!err.isOk()) {
4484 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004485 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004486
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004487 return res;
4488}
4489
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004490void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4491 ATRACE_NAME("CameraHal::signalPipelineDrain");
4492 if (!valid() || mHidlSession_3_5 == nullptr) {
4493 ALOGE("%s called on invalid camera!", __FUNCTION__);
4494 return;
4495 }
4496
4497 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter);
4498 if (!err.isOk()) {
4499 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4500 return;
4501 }
4502}
4503
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004504void Camera3Device::HalInterface::getInflightBufferKeys(
4505 std::vector<std::pair<int32_t, int32_t>>* out) {
4506 std::lock_guard<std::mutex> lock(mInflightLock);
4507 out->clear();
4508 out->reserve(mInflightBufferMap.size());
4509 for (auto& pair : mInflightBufferMap) {
4510 uint64_t key = pair.first;
4511 int32_t streamId = key & 0xFFFFFFFF;
4512 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4513 out->push_back(std::make_pair(frameNumber, streamId));
4514 }
4515 return;
4516}
4517
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004518status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004519 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004520 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004521 auto pair = std::make_pair(buffer, acquireFence);
4522 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004523 return OK;
4524}
4525
4526status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004527 int32_t frameNumber, int32_t streamId,
4528 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004529 std::lock_guard<std::mutex> lock(mInflightLock);
4530
4531 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4532 auto it = mInflightBufferMap.find(key);
4533 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004534 auto pair = it->second;
4535 *buffer = pair.first;
4536 int acquireFence = pair.second;
4537 if (acquireFence > 0) {
4538 ::close(acquireFence);
4539 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004540 mInflightBufferMap.erase(it);
4541 return OK;
4542}
4543
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004544status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4545 uint64_t bufferId, buffer_handle_t* buf) {
4546 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4547 auto pair = mRequestedBuffers.insert({bufferId, buf});
4548 if (!pair.second) {
4549 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4550 __FUNCTION__, bufferId);
4551 return BAD_VALUE;
4552 }
4553 return OK;
4554}
4555
4556// Find and pop a buffer_handle_t based on bufferId
4557status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4558 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4559 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4560 auto it = mRequestedBuffers.find(bufferId);
4561 if (it == mRequestedBuffers.end()) {
4562 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4563 __FUNCTION__, bufferId);
4564 return BAD_VALUE;
4565 }
4566 *buffer = it->second;
4567 mRequestedBuffers.erase(it);
4568 return OK;
4569}
4570
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004571std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4572 const buffer_handle_t& buf, int streamId) {
4573 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4574
4575 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4576 auto it = bIdMap.find(buf);
4577 if (it == bIdMap.end()) {
4578 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004579 ALOGV("stream %d now have %zu buffer caches, buf %p",
4580 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004581 return std::make_pair(true, mNextBufferId - 1);
4582 } else {
4583 return std::make_pair(false, it->second);
4584 }
4585}
4586
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004587void Camera3Device::HalInterface::onBufferFreed(
4588 int streamId, const native_handle_t* handle) {
4589 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4590 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4591 auto mapIt = mBufferIdMaps.find(streamId);
4592 if (mapIt == mBufferIdMaps.end()) {
4593 // streamId might be from a deleted stream here
4594 ALOGI("%s: stream %d has been removed",
4595 __FUNCTION__, streamId);
4596 return;
4597 }
4598 BufferIdMap& bIdMap = mapIt->second;
4599 auto it = bIdMap.find(handle);
4600 if (it == bIdMap.end()) {
4601 ALOGW("%s: cannot find buffer %p in stream %d",
4602 __FUNCTION__, handle, streamId);
4603 return;
4604 } else {
4605 bufferId = it->second;
4606 bIdMap.erase(it);
4607 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4608 __FUNCTION__, streamId, bIdMap.size(), handle);
4609 }
4610 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4611}
4612
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004613/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004614 * RequestThread inner class methods
4615 */
4616
4617Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004618 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004619 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4620 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004621 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004622 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004623 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004624 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004625 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004626 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004627 mReconfigured(false),
4628 mDoPause(false),
4629 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004630 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004631 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004632 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004633 mCurrentAfTriggerId(0),
4634 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004635 mRepeatingLastFrameNumber(
4636 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004637 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004638 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004639 mRequestLatency(kRequestLatencyBinSize),
4640 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004641 mLatestSessionParams(sessionParamKeys.size()),
4642 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004643 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004644}
4645
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004646Camera3Device::RequestThread::~RequestThread() {}
4647
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004648void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004649 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004650 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004651 Mutex::Autolock l(mRequestLock);
4652 mListener = listener;
4653}
4654
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004655void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4656 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004657 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004658 Mutex::Autolock l(mRequestLock);
4659 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004660 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004661 // Prepare video stream for high speed recording.
4662 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004663 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004664}
4665
Jianing Wei90e59c92014-03-12 18:29:36 -07004666status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004667 List<sp<CaptureRequest> > &requests,
4668 /*out*/
4669 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004670 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004671 Mutex::Autolock l(mRequestLock);
4672 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4673 ++it) {
4674 mRequestQueue.push_back(*it);
4675 }
4676
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004677 if (lastFrameNumber != NULL) {
4678 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4679 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4680 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4681 *lastFrameNumber);
4682 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004683
Jianing Wei90e59c92014-03-12 18:29:36 -07004684 unpauseForNewRequests();
4685
4686 return OK;
4687}
4688
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004689
4690status_t Camera3Device::RequestThread::queueTrigger(
4691 RequestTrigger trigger[],
4692 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004693 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004694 Mutex::Autolock l(mTriggerMutex);
4695 status_t ret;
4696
4697 for (size_t i = 0; i < count; ++i) {
4698 ret = queueTriggerLocked(trigger[i]);
4699
4700 if (ret != OK) {
4701 return ret;
4702 }
4703 }
4704
4705 return OK;
4706}
4707
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004708const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4709 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004710 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004711 if (d != nullptr) return d->mId;
4712 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004713}
4714
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004715status_t Camera3Device::RequestThread::queueTriggerLocked(
4716 RequestTrigger trigger) {
4717
4718 uint32_t tag = trigger.metadataTag;
4719 ssize_t index = mTriggerMap.indexOfKey(tag);
4720
4721 switch (trigger.getTagType()) {
4722 case TYPE_BYTE:
4723 // fall-through
4724 case TYPE_INT32:
4725 break;
4726 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004727 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4728 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004729 return INVALID_OPERATION;
4730 }
4731
4732 /**
4733 * Collect only the latest trigger, since we only have 1 field
4734 * in the request settings per trigger tag, and can't send more than 1
4735 * trigger per request.
4736 */
4737 if (index != NAME_NOT_FOUND) {
4738 mTriggerMap.editValueAt(index) = trigger;
4739 } else {
4740 mTriggerMap.add(tag, trigger);
4741 }
4742
4743 return OK;
4744}
4745
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004746status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004747 const RequestList &requests,
4748 /*out*/
4749 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004750 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004751 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004752 if (lastFrameNumber != NULL) {
4753 *lastFrameNumber = mRepeatingLastFrameNumber;
4754 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004755 mRepeatingRequests.clear();
4756 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4757 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004758
4759 unpauseForNewRequests();
4760
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004761 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004762 return OK;
4763}
4764
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004765bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004766 if (mRepeatingRequests.empty()) {
4767 return false;
4768 }
4769 int32_t requestId = requestIn->mResultExtras.requestId;
4770 const RequestList &repeatRequests = mRepeatingRequests;
4771 // All repeating requests are guaranteed to have same id so only check first quest
4772 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4773 return (firstRequest->mResultExtras.requestId == requestId);
4774}
4775
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004776status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004777 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004778 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004779 return clearRepeatingRequestsLocked(lastFrameNumber);
4780
4781}
4782
4783status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004784 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004785 if (lastFrameNumber != NULL) {
4786 *lastFrameNumber = mRepeatingLastFrameNumber;
4787 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004788 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004789 return OK;
4790}
4791
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004792status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004793 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004794 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004795 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004796 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004797
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004798 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004799
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004800 // Send errors for all requests pending in the request queue, including
4801 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004802 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004803 if (listener != NULL) {
4804 for (RequestList::iterator it = mRequestQueue.begin();
4805 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004806 // Abort the input buffers for reprocess requests.
4807 if ((*it)->mInputStream != NULL) {
4808 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004809 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4810 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004811 if (res != OK) {
4812 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4813 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4814 } else {
4815 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4816 if (res != OK) {
4817 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4818 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4819 }
4820 }
4821 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004822 // Set the frame number this request would have had, if it
4823 // had been submitted; this frame number will not be reused.
4824 // The requestId and burstId fields were set when the request was
4825 // submitted originally (in convertMetadataListToRequestListLocked)
4826 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004827 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004828 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004829 }
4830 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004831 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004832
4833 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004834 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004835 if (lastFrameNumber != NULL) {
4836 *lastFrameNumber = mRepeatingLastFrameNumber;
4837 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004838 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004839 return OK;
4840}
4841
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004842status_t Camera3Device::RequestThread::flush() {
4843 ATRACE_CALL();
4844 Mutex::Autolock l(mFlushLock);
4845
Emilian Peev08dd2452017-04-06 16:55:14 +01004846 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004847}
4848
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004849void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004850 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004851 Mutex::Autolock l(mPauseLock);
4852 mDoPause = paused;
4853 mDoPauseSignal.signal();
4854}
4855
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004856status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4857 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004858 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004859 Mutex::Autolock l(mLatestRequestMutex);
4860 status_t res;
4861 while (mLatestRequestId != requestId) {
4862 nsecs_t startTime = systemTime();
4863
4864 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4865 if (res != OK) return res;
4866
4867 timeout -= (systemTime() - startTime);
4868 }
4869
4870 return OK;
4871}
4872
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004873void Camera3Device::RequestThread::requestExit() {
4874 // Call parent to set up shutdown
4875 Thread::requestExit();
4876 // The exit from any possible waits
4877 mDoPauseSignal.signal();
4878 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004879
4880 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4881 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004882}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004883
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004884void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004885 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004886 bool surfaceAbandoned = false;
4887 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004888 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004889 {
4890 Mutex::Autolock l(mRequestLock);
4891 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4892 // repeating requests.
4893 for (const auto& request : mRepeatingRequests) {
4894 for (const auto& s : request->mOutputStreams) {
4895 if (s->isAbandoned()) {
4896 surfaceAbandoned = true;
4897 clearRepeatingRequestsLocked(&lastFrameNumber);
4898 break;
4899 }
4900 }
4901 if (surfaceAbandoned) {
4902 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004903 }
4904 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004905 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004906 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004907
4908 if (listener != NULL && surfaceAbandoned) {
4909 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004910 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004911}
4912
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004913bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004914 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004915 status_t res;
4916 size_t batchSize = mNextRequests.size();
4917 std::vector<camera3_capture_request_t*> requests(batchSize);
4918 uint32_t numRequestProcessed = 0;
4919 for (size_t i = 0; i < batchSize; i++) {
4920 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004921 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004922 }
4923
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004924 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4925
4926 bool triggerRemoveFailed = false;
4927 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4928 for (size_t i = 0; i < numRequestProcessed; i++) {
4929 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4930 nextRequest.submitted = true;
4931
4932
4933 // Update the latest request sent to HAL
4934 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4935 Mutex::Autolock al(mLatestRequestMutex);
4936
4937 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4938 mLatestRequest.acquire(cloned);
4939
4940 sp<Camera3Device> parent = mParent.promote();
4941 if (parent != NULL) {
4942 parent->monitorMetadata(TagMonitor::REQUEST,
4943 nextRequest.halRequest.frame_number,
4944 0, mLatestRequest);
4945 }
4946 }
4947
4948 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004949 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4950 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004951 }
4952
Emilian Peevaebbe412018-01-15 13:53:24 +00004953 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4954
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004955 if (!triggerRemoveFailed) {
4956 // Remove any previously queued triggers (after unlock)
4957 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4958 if (removeTriggerRes != OK) {
4959 triggerRemoveFailed = true;
4960 triggerFailedRequest = nextRequest;
4961 }
4962 }
4963 }
4964
4965 if (triggerRemoveFailed) {
4966 SET_ERR("RequestThread: Unable to remove triggers "
4967 "(capture request %d, HAL device: %s (%d)",
4968 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4969 cleanUpFailedRequests(/*sendRequestError*/ false);
4970 return false;
4971 }
4972
4973 if (res != OK) {
4974 // Should only get a failure here for malformed requests or device-level
4975 // errors, so consider all errors fatal. Bad metadata failures should
4976 // come through notify.
4977 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4978 mNextRequests[numRequestProcessed].halRequest.frame_number,
4979 strerror(-res), res);
4980 cleanUpFailedRequests(/*sendRequestError*/ false);
4981 return false;
4982 }
4983 return true;
4984}
4985
4986bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4987 status_t res;
4988
4989 for (auto& nextRequest : mNextRequests) {
4990 // Submit request and block until ready for next one
4991 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4992 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4993
4994 if (res != OK) {
4995 // Should only get a failure here for malformed requests or device-level
4996 // errors, so consider all errors fatal. Bad metadata failures should
4997 // come through notify.
4998 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4999 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
5000 res);
5001 cleanUpFailedRequests(/*sendRequestError*/ false);
5002 return false;
5003 }
5004
5005 // Mark that the request has be submitted successfully.
5006 nextRequest.submitted = true;
5007
5008 // Update the latest request sent to HAL
5009 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5010 Mutex::Autolock al(mLatestRequestMutex);
5011
5012 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5013 mLatestRequest.acquire(cloned);
5014
5015 sp<Camera3Device> parent = mParent.promote();
5016 if (parent != NULL) {
5017 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
5018 0, mLatestRequest);
5019 }
5020 }
5021
5022 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005023 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5024 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005025 }
5026
Emilian Peevaebbe412018-01-15 13:53:24 +00005027 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5028
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005029 // Remove any previously queued triggers (after unlock)
5030 res = removeTriggers(mPrevRequest);
5031 if (res != OK) {
5032 SET_ERR("RequestThread: Unable to remove triggers "
5033 "(capture request %d, HAL device: %s (%d)",
5034 nextRequest.halRequest.frame_number, strerror(-res), res);
5035 cleanUpFailedRequests(/*sendRequestError*/ false);
5036 return false;
5037 }
5038 }
5039 return true;
5040}
5041
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005042nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5043 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5044 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5045 find_camera_metadata_ro_entry(request,
5046 ANDROID_CONTROL_AE_MODE,
5047 &e);
5048 if (e.count == 0) return maxExpectedDuration;
5049
5050 switch (e.data.u8[0]) {
5051 case ANDROID_CONTROL_AE_MODE_OFF:
5052 find_camera_metadata_ro_entry(request,
5053 ANDROID_SENSOR_EXPOSURE_TIME,
5054 &e);
5055 if (e.count > 0) {
5056 maxExpectedDuration = e.data.i64[0];
5057 }
5058 find_camera_metadata_ro_entry(request,
5059 ANDROID_SENSOR_FRAME_DURATION,
5060 &e);
5061 if (e.count > 0) {
5062 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5063 }
5064 break;
5065 default:
5066 find_camera_metadata_ro_entry(request,
5067 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5068 &e);
5069 if (e.count > 1) {
5070 maxExpectedDuration = 1e9 / e.data.u8[0];
5071 }
5072 break;
5073 }
5074
5075 return maxExpectedDuration;
5076}
5077
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005078bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5079 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5080 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5081 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5082 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5083 return true;
5084 }
5085
5086 return false;
5087}
5088
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005089bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5090 ATRACE_CALL();
5091 bool updatesDetected = false;
5092
5093 for (auto tag : mSessionParamKeys) {
5094 camera_metadata_ro_entry entry = settings.find(tag);
5095 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
5096
5097 if (entry.count > 0) {
5098 bool isDifferent = false;
5099 if (lastEntry.count > 0) {
5100 // Have a last value, compare to see if changed
5101 if (lastEntry.type == entry.type &&
5102 lastEntry.count == entry.count) {
5103 // Same type and count, compare values
5104 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5105 size_t entryBytes = bytesPerValue * lastEntry.count;
5106 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5107 if (cmp != 0) {
5108 isDifferent = true;
5109 }
5110 } else {
5111 // Count or type has changed
5112 isDifferent = true;
5113 }
5114 } else {
5115 // No last entry, so always consider to be different
5116 isDifferent = true;
5117 }
5118
5119 if (isDifferent) {
5120 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005121 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5122 updatesDetected = true;
5123 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005124 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005125 }
5126 } else if (lastEntry.count > 0) {
5127 // Value has been removed
5128 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
5129 mLatestSessionParams.erase(tag);
5130 updatesDetected = true;
5131 }
5132 }
5133
5134 return updatesDetected;
5135}
5136
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005137bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005138 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005139 status_t res;
5140
5141 // Handle paused state.
5142 if (waitIfPaused()) {
5143 return true;
5144 }
5145
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005146 // Wait for the next batch of requests.
5147 waitForNextRequestBatch();
5148 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005149 return true;
5150 }
5151
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005152 // Get the latest request ID, if any
5153 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005154 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005155 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005156 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005157 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005158 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005159 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5160 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005161 }
5162
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005163 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5164 // or a single request from streaming or burst. In either case the first element
5165 // should contain the latest camera settings that we need to check for any session
5166 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005167 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005168 res = OK;
5169
5170 //Input stream buffers are already acquired at this point so an input stream
5171 //will not be able to move to idle state unless we force it.
5172 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5173 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5174 if (res != OK) {
5175 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5176 cleanUpFailedRequests(/*sendRequestError*/ false);
5177 return false;
5178 }
5179 }
5180
5181 if (res == OK) {
5182 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5183 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005184 sp<Camera3Device> parent = mParent.promote();
5185 if (parent != nullptr) {
5186 parent->pauseStateNotify(true);
5187 }
5188
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005189 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5190
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005191 if (parent != nullptr) {
5192 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5193 }
5194
5195 statusTracker->markComponentActive(mStatusId);
5196 setPaused(false);
5197 }
5198
5199 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5200 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5201 if (res != OK) {
5202 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5203 cleanUpFailedRequests(/*sendRequestError*/ false);
5204 return false;
5205 }
5206 }
5207 }
5208 }
5209
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005210 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005211 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005212 if (res == TIMED_OUT) {
5213 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005214 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005215 // Check if any stream is abandoned.
5216 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005217 return true;
5218 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005219 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005220 return false;
5221 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005222
Zhijun Hecc27e112013-10-03 16:12:43 -07005223 // Inform waitUntilRequestProcessed thread of a new request ID
5224 {
5225 Mutex::Autolock al(mLatestRequestMutex);
5226
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005227 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005228 mLatestRequestSignal.signal();
5229 }
5230
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005231 // Submit a batch of requests to HAL.
5232 // Use flush lock only when submitting multilple requests in a batch.
5233 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5234 // which may take a long time to finish so synchronizing flush() and
5235 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5236 // For now, only synchronize for high speed recording and we should figure something out for
5237 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005238 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005239
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005240 if (useFlushLock) {
5241 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005242 }
5243
Zhijun Hef0645c12016-08-02 00:58:11 -07005244 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005245 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005246
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005247 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005248 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005249 if (mInterface->supportBatchRequest()) {
5250 submitRequestSuccess = sendRequestsBatch();
5251 } else {
5252 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005253 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005254 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5255 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005256
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005257 if (submitRequestSuccess) {
5258 sp<Camera3Device> parent = mParent.promote();
5259 if (parent != nullptr) {
5260 parent->mRequestBufferSM.onRequestSubmitted();
5261 }
5262 }
5263
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005264 if (useFlushLock) {
5265 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005266 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005267
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005268 // Unset as current request
5269 {
5270 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005271 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005272 }
5273
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005274 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005275}
5276
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005277status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005278 ATRACE_CALL();
5279
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005280 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005281 for (size_t i = 0; i < mNextRequests.size(); i++) {
5282 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005283 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5284 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5285 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5286
5287 // Prepare a request to HAL
5288 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5289
5290 // Insert any queued triggers (before metadata is locked)
5291 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005292 if (res < 0) {
5293 SET_ERR("RequestThread: Unable to insert triggers "
5294 "(capture request %d, HAL device: %s (%d)",
5295 halRequest->frame_number, strerror(-res), res);
5296 return INVALID_OPERATION;
5297 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005298
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005299 int triggerCount = res;
5300 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5301 mPrevTriggers = triggerCount;
5302
5303 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005304 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5305 // Request settings are all the same within one batch, so only treat the first
5306 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005307 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005308 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005309 /**
5310 * HAL workaround:
5311 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5312 */
5313 res = addDummyTriggerIds(captureRequest);
5314 if (res != OK) {
5315 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5316 "(capture request %d, HAL device: %s (%d)",
5317 halRequest->frame_number, strerror(-res), res);
5318 return INVALID_OPERATION;
5319 }
5320
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005321 {
5322 // Correct metadata regions for distortion correction if enabled
5323 sp<Camera3Device> parent = mParent.promote();
5324 if (parent != nullptr) {
5325 res = parent->mDistortionMapper.correctCaptureRequest(
5326 &(captureRequest->mSettingsList.begin()->metadata));
5327 if (res != OK) {
5328 SET_ERR("RequestThread: Unable to correct capture requests "
5329 "for lens distortion for request %d: %s (%d)",
5330 halRequest->frame_number, strerror(-res), res);
5331 return INVALID_OPERATION;
5332 }
5333 }
5334 }
5335
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005336 /**
5337 * The request should be presorted so accesses in HAL
5338 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5339 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005340 captureRequest->mSettingsList.begin()->metadata.sort();
5341 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005342 mPrevRequest = captureRequest;
5343 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5344
5345 IF_ALOGV() {
5346 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5347 find_camera_metadata_ro_entry(
5348 halRequest->settings,
5349 ANDROID_CONTROL_AF_TRIGGER,
5350 &e
5351 );
5352 if (e.count > 0) {
5353 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5354 __FUNCTION__,
5355 halRequest->frame_number,
5356 e.data.u8[0]);
5357 }
5358 }
5359 } else {
5360 // leave request.settings NULL to indicate 'reuse latest given'
5361 ALOGVV("%s: Request settings are REUSED",
5362 __FUNCTION__);
5363 }
5364
Emilian Peevaebbe412018-01-15 13:53:24 +00005365 if (captureRequest->mSettingsList.size() > 1) {
5366 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5367 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005368 if (newRequest) {
5369 halRequest->physcam_settings =
5370 new const camera_metadata* [halRequest->num_physcam_settings];
5371 } else {
5372 halRequest->physcam_settings = nullptr;
5373 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005374 auto it = ++captureRequest->mSettingsList.begin();
5375 size_t i = 0;
5376 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5377 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005378 if (newRequest) {
5379 it->metadata.sort();
5380 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5381 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005382 }
5383 }
5384
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005385 uint32_t totalNumBuffers = 0;
5386
5387 // Fill in buffers
5388 if (captureRequest->mInputStream != NULL) {
5389 halRequest->input_buffer = &captureRequest->mInputBuffer;
5390 totalNumBuffers += 1;
5391 } else {
5392 halRequest->input_buffer = NULL;
5393 }
5394
5395 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5396 captureRequest->mOutputStreams.size());
5397 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005398 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005399
5400 sp<Camera3Device> parent = mParent.promote();
5401 if (parent == NULL) {
5402 // Should not happen, and nowhere to send errors to, so just log it
5403 CLOGE("RequestThread: Parent is gone");
5404 return INVALID_OPERATION;
5405 }
5406 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5407
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005408 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005409 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005410 sp<Camera3OutputStreamInterface> outputStream =
5411 captureRequest->mOutputStreams.editItemAt(j);
5412 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005413
5414 // Prepare video buffers for high speed recording on the first video request.
5415 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5416 // Only try to prepare video stream on the first video request.
5417 mPrepareVideoStream = false;
5418
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005419 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5420 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005421 while (res == NOT_ENOUGH_DATA) {
5422 res = outputStream->prepareNextBuffer();
5423 }
5424 if (res != OK) {
5425 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5426 __FUNCTION__, strerror(-res), res);
5427 outputStream->cancelPrepare();
5428 }
5429 }
5430
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005431 std::vector<size_t> uniqueSurfaceIds;
5432 res = outputStream->getUniqueSurfaceIds(
5433 captureRequest->mOutputSurfaces[streamId],
5434 &uniqueSurfaceIds);
5435 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5436 if (res != OK && res != INVALID_OPERATION) {
5437 ALOGE("%s: failed to query stream %d unique surface IDs",
5438 __FUNCTION__, streamId);
5439 return res;
5440 }
5441 if (res == OK) {
5442 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5443 }
5444
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005445 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005446 if (outputStream->isAbandoned()) {
5447 ALOGE("%s: stream %d is abandoned.", __FUNCTION__, streamId);
5448 return TIMED_OUT;
5449 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005450 // HAL will request buffer through requestStreamBuffer API
5451 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5452 buffer.stream = outputStream->asHalStream();
5453 buffer.buffer = nullptr;
5454 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5455 buffer.acquire_fence = -1;
5456 buffer.release_fence = -1;
5457 } else {
5458 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5459 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005460 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005461 if (res != OK) {
5462 // Can't get output buffer from gralloc queue - this could be due to
5463 // abandoned queue or other consumer misbehavior, so not a fatal
5464 // error
5465 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5466 " %s (%d)", strerror(-res), res);
5467
5468 return TIMED_OUT;
5469 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005470 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005471
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005472 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5473
5474 if (!physicalCameraId.isEmpty()) {
5475 // Physical stream isn't supported for input request.
5476 if (halRequest->input_buffer) {
5477 CLOGE("Physical stream is not supported for input request");
5478 return INVALID_OPERATION;
5479 }
5480 requestedPhysicalCameras.insert(physicalCameraId);
5481 }
5482 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005483 }
5484 totalNumBuffers += halRequest->num_output_buffers;
5485
5486 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005487 // If this request list is for constrained high speed recording (not
5488 // preview), and the current request is not the last one in the batch,
5489 // do not send callback to the app.
5490 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005491 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005492 hasCallback = false;
5493 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005494 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005495 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005496 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5497 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5498 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5499 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5500 isStillCapture = true;
5501 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5502 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005503
5504 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5505 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5506 isZslCapture = true;
5507 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005508 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005509 res = parent->registerInFlight(halRequest->frame_number,
5510 totalNumBuffers, captureRequest->mResultExtras,
5511 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005512 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005513 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005514 requestedPhysicalCameras, isStillCapture, isZslCapture,
5515 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5516 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005517 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5518 ", burstId = %" PRId32 ".",
5519 __FUNCTION__,
5520 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5521 captureRequest->mResultExtras.burstId);
5522 if (res != OK) {
5523 SET_ERR("RequestThread: Unable to register new in-flight request:"
5524 " %s (%d)", strerror(-res), res);
5525 return INVALID_OPERATION;
5526 }
5527 }
5528
5529 return OK;
5530}
5531
Igor Murashkin1e479c02013-09-06 16:55:14 -07005532CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005533 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005534 Mutex::Autolock al(mLatestRequestMutex);
5535
5536 ALOGV("RequestThread::%s", __FUNCTION__);
5537
5538 return mLatestRequest;
5539}
5540
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005541bool Camera3Device::RequestThread::isStreamPending(
5542 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005543 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005544 Mutex::Autolock l(mRequestLock);
5545
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005546 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005547 if (!nextRequest.submitted) {
5548 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5549 if (stream == s) return true;
5550 }
5551 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005552 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005553 }
5554
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005555 for (const auto& request : mRequestQueue) {
5556 for (const auto& s : request->mOutputStreams) {
5557 if (stream == s) return true;
5558 }
5559 if (stream == request->mInputStream) return true;
5560 }
5561
5562 for (const auto& request : mRepeatingRequests) {
5563 for (const auto& s : request->mOutputStreams) {
5564 if (stream == s) return true;
5565 }
5566 if (stream == request->mInputStream) return true;
5567 }
5568
5569 return false;
5570}
Jianing Weicb0652e2014-03-12 18:29:36 -07005571
Emilian Peev40ead602017-09-26 15:46:36 +01005572bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5573 ATRACE_CALL();
5574 Mutex::Autolock l(mRequestLock);
5575
5576 for (const auto& nextRequest : mNextRequests) {
5577 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5578 if (s.first == streamId) {
5579 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5580 if (it != s.second.end()) {
5581 return true;
5582 }
5583 }
5584 }
5585 }
5586
5587 for (const auto& request : mRequestQueue) {
5588 for (const auto& s : request->mOutputSurfaces) {
5589 if (s.first == streamId) {
5590 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5591 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005592 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005593 }
5594 }
5595 }
5596 }
5597
5598 for (const auto& request : mRepeatingRequests) {
5599 for (const auto& s : request->mOutputSurfaces) {
5600 if (s.first == streamId) {
5601 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5602 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005603 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005604 }
5605 }
5606 }
5607 }
5608
5609 return false;
5610}
5611
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005612void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5613 if (!mUseHalBufManager) {
5614 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5615 return;
5616 }
5617
5618 Mutex::Autolock pl(mPauseLock);
5619 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005620 mInterface->signalPipelineDrain(streamIds);
5621 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005622 }
5623 // If request thread is still busy, wait until paused then notify HAL
5624 mNotifyPipelineDrain = true;
5625 mStreamIdsToBeDrained = streamIds;
5626}
5627
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005628nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005629 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005630 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005631 return mExpectedInflightDuration > kMinInflightDuration ?
5632 mExpectedInflightDuration : kMinInflightDuration;
5633}
5634
Emilian Peevaebbe412018-01-15 13:53:24 +00005635void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5636 camera3_capture_request_t *halRequest) {
5637 if ((request == nullptr) || (halRequest == nullptr)) {
5638 ALOGE("%s: Invalid request!", __FUNCTION__);
5639 return;
5640 }
5641
5642 if (halRequest->num_physcam_settings > 0) {
5643 if (halRequest->physcam_id != nullptr) {
5644 delete [] halRequest->physcam_id;
5645 halRequest->physcam_id = nullptr;
5646 }
5647 if (halRequest->physcam_settings != nullptr) {
5648 auto it = ++(request->mSettingsList.begin());
5649 size_t i = 0;
5650 for (; it != request->mSettingsList.end(); it++, i++) {
5651 it->metadata.unlock(halRequest->physcam_settings[i]);
5652 }
5653 delete [] halRequest->physcam_settings;
5654 halRequest->physcam_settings = nullptr;
5655 }
5656 }
5657}
5658
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005659void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5660 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005661 return;
5662 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005663
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005664 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005665 // Skip the ones that have been submitted successfully.
5666 if (nextRequest.submitted) {
5667 continue;
5668 }
5669
5670 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5671 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5672 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5673
5674 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005675 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005676 }
5677
Emilian Peevaebbe412018-01-15 13:53:24 +00005678 cleanupPhysicalSettings(captureRequest, halRequest);
5679
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005680 if (captureRequest->mInputStream != NULL) {
5681 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5682 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5683 }
5684
5685 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005686 //Buffers that failed processing could still have
5687 //valid acquire fence.
5688 int acquireFence = (*outputBuffers)[i].acquire_fence;
5689 if (0 <= acquireFence) {
5690 close(acquireFence);
5691 outputBuffers->editItemAt(i).acquire_fence = -1;
5692 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005693 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5694 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5695 }
5696
5697 if (sendRequestError) {
5698 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005699 sp<NotificationListener> listener = mListener.promote();
5700 if (listener != NULL) {
5701 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005702 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005703 captureRequest->mResultExtras);
5704 }
5705 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005706
5707 // Remove yet-to-be submitted inflight request from inflightMap
5708 {
5709 sp<Camera3Device> parent = mParent.promote();
5710 if (parent != NULL) {
5711 Mutex::Autolock l(parent->mInFlightLock);
5712 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5713 if (idx >= 0) {
5714 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5715 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5716 parent->removeInFlightMapEntryLocked(idx);
5717 }
5718 }
5719 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005720 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005721
5722 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005723 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005724}
5725
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005726void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005727 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005728 // Optimized a bit for the simple steady-state case (single repeating
5729 // request), to avoid putting that request in the queue temporarily.
5730 Mutex::Autolock l(mRequestLock);
5731
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005732 assert(mNextRequests.empty());
5733
5734 NextRequest nextRequest;
5735 nextRequest.captureRequest = waitForNextRequestLocked();
5736 if (nextRequest.captureRequest == nullptr) {
5737 return;
5738 }
5739
5740 nextRequest.halRequest = camera3_capture_request_t();
5741 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005742 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005743
5744 // Wait for additional requests
5745 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5746
5747 for (size_t i = 1; i < batchSize; i++) {
5748 NextRequest additionalRequest;
5749 additionalRequest.captureRequest = waitForNextRequestLocked();
5750 if (additionalRequest.captureRequest == nullptr) {
5751 break;
5752 }
5753
5754 additionalRequest.halRequest = camera3_capture_request_t();
5755 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005756 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005757 }
5758
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005759 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005760 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005761 mNextRequests.size(), batchSize);
5762 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005763 }
5764
5765 return;
5766}
5767
5768sp<Camera3Device::CaptureRequest>
5769 Camera3Device::RequestThread::waitForNextRequestLocked() {
5770 status_t res;
5771 sp<CaptureRequest> nextRequest;
5772
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005773 while (mRequestQueue.empty()) {
5774 if (!mRepeatingRequests.empty()) {
5775 // Always atomically enqueue all requests in a repeating request
5776 // list. Guarantees a complete in-sequence set of captures to
5777 // application.
5778 const RequestList &requests = mRepeatingRequests;
5779 RequestList::const_iterator firstRequest =
5780 requests.begin();
5781 nextRequest = *firstRequest;
5782 mRequestQueue.insert(mRequestQueue.end(),
5783 ++firstRequest,
5784 requests.end());
5785 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005786
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005787 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005788
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005789 break;
5790 }
5791
5792 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5793
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005794 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5795 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005796 Mutex::Autolock pl(mPauseLock);
5797 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005798 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005799 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005800 // Let the tracker know
5801 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5802 if (statusTracker != 0) {
5803 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5804 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005805 if (mNotifyPipelineDrain) {
5806 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5807 mNotifyPipelineDrain = false;
5808 mStreamIdsToBeDrained.clear();
5809 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005810 sp<Camera3Device> parent = mParent.promote();
5811 if (parent != nullptr) {
5812 parent->mRequestBufferSM.onRequestThreadPaused();
5813 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005814 }
5815 // Stop waiting for now and let thread management happen
5816 return NULL;
5817 }
5818 }
5819
5820 if (nextRequest == NULL) {
5821 // Don't have a repeating request already in hand, so queue
5822 // must have an entry now.
5823 RequestList::iterator firstRequest =
5824 mRequestQueue.begin();
5825 nextRequest = *firstRequest;
5826 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005827 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5828 sp<NotificationListener> listener = mListener.promote();
5829 if (listener != NULL) {
5830 listener->notifyRequestQueueEmpty();
5831 }
5832 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005833 }
5834
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005835 // In case we've been unpaused by setPaused clearing mDoPause, need to
5836 // update internal pause state (capture/setRepeatingRequest unpause
5837 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005838 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005839 if (mPaused) {
5840 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5841 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5842 if (statusTracker != 0) {
5843 statusTracker->markComponentActive(mStatusId);
5844 }
5845 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005846 mPaused = false;
5847
5848 // Check if we've reconfigured since last time, and reset the preview
5849 // request if so. Can't use 'NULL request == repeat' across configure calls.
5850 if (mReconfigured) {
5851 mPrevRequest.clear();
5852 mReconfigured = false;
5853 }
5854
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005855 if (nextRequest != NULL) {
5856 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005857 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5858 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005859
5860 // Since RequestThread::clear() removes buffers from the input stream,
5861 // get the right buffer here before unlocking mRequestLock
5862 if (nextRequest->mInputStream != NULL) {
5863 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5864 if (res != OK) {
5865 // Can't get input buffer from gralloc queue - this could be due to
5866 // disconnected queue or other producer misbehavior, so not a fatal
5867 // error
5868 ALOGE("%s: Can't get input buffer, skipping request:"
5869 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005870
5871 sp<NotificationListener> listener = mListener.promote();
5872 if (listener != NULL) {
5873 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005874 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005875 nextRequest->mResultExtras);
5876 }
5877 return NULL;
5878 }
5879 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005880 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005881
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005882 return nextRequest;
5883}
5884
5885bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005886 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005887 status_t res;
5888 Mutex::Autolock l(mPauseLock);
5889 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005890 if (mPaused == false) {
5891 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005892 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5893 // Let the tracker know
5894 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5895 if (statusTracker != 0) {
5896 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5897 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005898 if (mNotifyPipelineDrain) {
5899 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5900 mNotifyPipelineDrain = false;
5901 mStreamIdsToBeDrained.clear();
5902 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005903 sp<Camera3Device> parent = mParent.promote();
5904 if (parent != nullptr) {
5905 parent->mRequestBufferSM.onRequestThreadPaused();
5906 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005907 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005908
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005909 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005910 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005911 return true;
5912 }
5913 }
5914 // We don't set mPaused to false here, because waitForNextRequest needs
5915 // to further manage the paused state in case of starvation.
5916 return false;
5917}
5918
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005919void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005920 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005921 // With work to do, mark thread as unpaused.
5922 // If paused by request (setPaused), don't resume, to avoid
5923 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005924 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005925 Mutex::Autolock p(mPauseLock);
5926 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005927 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5928 if (mPaused) {
5929 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5930 if (statusTracker != 0) {
5931 statusTracker->markComponentActive(mStatusId);
5932 }
5933 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005934 mPaused = false;
5935 }
5936}
5937
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005938void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5939 sp<Camera3Device> parent = mParent.promote();
5940 if (parent != NULL) {
5941 va_list args;
5942 va_start(args, fmt);
5943
5944 parent->setErrorStateV(fmt, args);
5945
5946 va_end(args);
5947 }
5948}
5949
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005950status_t Camera3Device::RequestThread::insertTriggers(
5951 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005952 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005953 Mutex::Autolock al(mTriggerMutex);
5954
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005955 sp<Camera3Device> parent = mParent.promote();
5956 if (parent == NULL) {
5957 CLOGE("RequestThread: Parent is gone");
5958 return DEAD_OBJECT;
5959 }
5960
Emilian Peevaebbe412018-01-15 13:53:24 +00005961 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005962 size_t count = mTriggerMap.size();
5963
5964 for (size_t i = 0; i < count; ++i) {
5965 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005966 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005967
5968 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5969 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5970 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005971 if (isAeTrigger) {
5972 request->mResultExtras.precaptureTriggerId = triggerId;
5973 mCurrentPreCaptureTriggerId = triggerId;
5974 } else {
5975 request->mResultExtras.afTriggerId = triggerId;
5976 mCurrentAfTriggerId = triggerId;
5977 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005978 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005979 }
5980
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005981 camera_metadata_entry entry = metadata.find(tag);
5982
5983 if (entry.count > 0) {
5984 /**
5985 * Already has an entry for this trigger in the request.
5986 * Rewrite it with our requested trigger value.
5987 */
5988 RequestTrigger oldTrigger = trigger;
5989
5990 oldTrigger.entryValue = entry.data.u8[0];
5991
5992 mTriggerReplacedMap.add(tag, oldTrigger);
5993 } else {
5994 /**
5995 * More typical, no trigger entry, so we just add it
5996 */
5997 mTriggerRemovedMap.add(tag, trigger);
5998 }
5999
6000 status_t res;
6001
6002 switch (trigger.getTagType()) {
6003 case TYPE_BYTE: {
6004 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6005 res = metadata.update(tag,
6006 &entryValue,
6007 /*count*/1);
6008 break;
6009 }
6010 case TYPE_INT32:
6011 res = metadata.update(tag,
6012 &trigger.entryValue,
6013 /*count*/1);
6014 break;
6015 default:
6016 ALOGE("%s: Type not supported: 0x%x",
6017 __FUNCTION__,
6018 trigger.getTagType());
6019 return INVALID_OPERATION;
6020 }
6021
6022 if (res != OK) {
6023 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6024 ", value %d", __FUNCTION__, trigger.getTagName(),
6025 trigger.entryValue);
6026 return res;
6027 }
6028
6029 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6030 trigger.getTagName(),
6031 trigger.entryValue);
6032 }
6033
6034 mTriggerMap.clear();
6035
6036 return count;
6037}
6038
6039status_t Camera3Device::RequestThread::removeTriggers(
6040 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006041 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006042 Mutex::Autolock al(mTriggerMutex);
6043
Emilian Peevaebbe412018-01-15 13:53:24 +00006044 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006045
6046 /**
6047 * Replace all old entries with their old values.
6048 */
6049 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6050 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6051
6052 status_t res;
6053
6054 uint32_t tag = trigger.metadataTag;
6055 switch (trigger.getTagType()) {
6056 case TYPE_BYTE: {
6057 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6058 res = metadata.update(tag,
6059 &entryValue,
6060 /*count*/1);
6061 break;
6062 }
6063 case TYPE_INT32:
6064 res = metadata.update(tag,
6065 &trigger.entryValue,
6066 /*count*/1);
6067 break;
6068 default:
6069 ALOGE("%s: Type not supported: 0x%x",
6070 __FUNCTION__,
6071 trigger.getTagType());
6072 return INVALID_OPERATION;
6073 }
6074
6075 if (res != OK) {
6076 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6077 ", trigger value %d", __FUNCTION__,
6078 trigger.getTagName(), trigger.entryValue);
6079 return res;
6080 }
6081 }
6082 mTriggerReplacedMap.clear();
6083
6084 /**
6085 * Remove all new entries.
6086 */
6087 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6088 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6089 status_t res = metadata.erase(trigger.metadataTag);
6090
6091 if (res != OK) {
6092 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6093 ", trigger value %d", __FUNCTION__,
6094 trigger.getTagName(), trigger.entryValue);
6095 return res;
6096 }
6097 }
6098 mTriggerRemovedMap.clear();
6099
6100 return OK;
6101}
6102
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006103status_t Camera3Device::RequestThread::addDummyTriggerIds(
6104 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006105 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006106 static const int32_t dummyTriggerId = 1;
6107 status_t res;
6108
Emilian Peevaebbe412018-01-15 13:53:24 +00006109 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006110
6111 // If AF trigger is active, insert a dummy AF trigger ID if none already
6112 // exists
6113 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6114 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6115 if (afTrigger.count > 0 &&
6116 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6117 afId.count == 0) {
6118 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6119 if (res != OK) return res;
6120 }
6121
6122 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6123 // if none already exists
6124 camera_metadata_entry pcTrigger =
6125 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6126 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6127 if (pcTrigger.count > 0 &&
6128 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6129 pcId.count == 0) {
6130 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6131 &dummyTriggerId, 1);
6132 if (res != OK) return res;
6133 }
6134
6135 return OK;
6136}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006137
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006138/**
6139 * PreparerThread inner class methods
6140 */
6141
6142Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006143 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006144 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006145}
6146
6147Camera3Device::PreparerThread::~PreparerThread() {
6148 Thread::requestExitAndWait();
6149 if (mCurrentStream != nullptr) {
6150 mCurrentStream->cancelPrepare();
6151 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6152 mCurrentStream.clear();
6153 }
6154 clear();
6155}
6156
Ruben Brunkc78ac262015-08-13 17:58:46 -07006157status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006158 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006159 status_t res;
6160
6161 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006162 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006163
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006164 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006165 if (res == OK) {
6166 // No preparation needed, fire listener right off
6167 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006168 if (listener != NULL) {
6169 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006170 }
6171 return OK;
6172 } else if (res != NOT_ENOUGH_DATA) {
6173 return res;
6174 }
6175
6176 // Need to prepare, start up thread if necessary
6177 if (!mActive) {
6178 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6179 // isn't running
6180 Thread::requestExitAndWait();
6181 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6182 if (res != OK) {
6183 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006184 if (listener != NULL) {
6185 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006186 }
6187 return res;
6188 }
6189 mCancelNow = false;
6190 mActive = true;
6191 ALOGV("%s: Preparer stream started", __FUNCTION__);
6192 }
6193
6194 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006195 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006196 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6197
6198 return OK;
6199}
6200
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006201void Camera3Device::PreparerThread::pause() {
6202 ATRACE_CALL();
6203
6204 Mutex::Autolock l(mLock);
6205
6206 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6207 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6208 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6209 int currentMaxCount = mCurrentMaxCount;
6210 mPendingStreams.clear();
6211 mCancelNow = true;
6212 while (mActive) {
6213 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6214 if (res == TIMED_OUT) {
6215 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6216 return;
6217 } else if (res != OK) {
6218 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6219 return;
6220 }
6221 }
6222
6223 //Check whether the prepare thread was able to complete the current
6224 //stream. In case work is still pending emplace it along with the rest
6225 //of the streams in the pending list.
6226 if (currentStream != nullptr) {
6227 if (!mCurrentPrepareComplete) {
6228 pendingStreams.emplace(currentMaxCount, currentStream);
6229 }
6230 }
6231
6232 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6233 for (const auto& it : mPendingStreams) {
6234 it.second->cancelPrepare();
6235 }
6236}
6237
6238status_t Camera3Device::PreparerThread::resume() {
6239 ATRACE_CALL();
6240 status_t res;
6241
6242 Mutex::Autolock l(mLock);
6243 sp<NotificationListener> listener = mListener.promote();
6244
6245 if (mActive) {
6246 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6247 return NO_INIT;
6248 }
6249
6250 auto it = mPendingStreams.begin();
6251 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006252 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006253 if (res == OK) {
6254 if (listener != NULL) {
6255 listener->notifyPrepared(it->second->getId());
6256 }
6257 it = mPendingStreams.erase(it);
6258 } else if (res != NOT_ENOUGH_DATA) {
6259 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6260 res, strerror(-res));
6261 it = mPendingStreams.erase(it);
6262 } else {
6263 it++;
6264 }
6265 }
6266
6267 if (mPendingStreams.empty()) {
6268 return OK;
6269 }
6270
6271 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6272 if (res != OK) {
6273 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6274 __FUNCTION__, res, strerror(-res));
6275 return res;
6276 }
6277 mCancelNow = false;
6278 mActive = true;
6279 ALOGV("%s: Preparer stream started", __FUNCTION__);
6280
6281 return OK;
6282}
6283
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006284status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006285 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006286 Mutex::Autolock l(mLock);
6287
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006288 for (const auto& it : mPendingStreams) {
6289 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006290 }
6291 mPendingStreams.clear();
6292 mCancelNow = true;
6293
6294 return OK;
6295}
6296
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006297void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006298 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006299 Mutex::Autolock l(mLock);
6300 mListener = listener;
6301}
6302
6303bool Camera3Device::PreparerThread::threadLoop() {
6304 status_t res;
6305 {
6306 Mutex::Autolock l(mLock);
6307 if (mCurrentStream == nullptr) {
6308 // End thread if done with work
6309 if (mPendingStreams.empty()) {
6310 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6311 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6312 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6313 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006314 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006315 return false;
6316 }
6317
6318 // Get next stream to prepare
6319 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006320 mCurrentStream = it->second;
6321 mCurrentMaxCount = it->first;
6322 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006323 mPendingStreams.erase(it);
6324 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6325 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6326 } else if (mCancelNow) {
6327 mCurrentStream->cancelPrepare();
6328 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6329 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6330 mCurrentStream.clear();
6331 mCancelNow = false;
6332 return true;
6333 }
6334 }
6335
6336 res = mCurrentStream->prepareNextBuffer();
6337 if (res == NOT_ENOUGH_DATA) return true;
6338 if (res != OK) {
6339 // Something bad happened; try to recover by cancelling prepare and
6340 // signalling listener anyway
6341 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6342 mCurrentStream->getId(), res, strerror(-res));
6343 mCurrentStream->cancelPrepare();
6344 }
6345
6346 // This stream has finished, notify listener
6347 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006348 sp<NotificationListener> listener = mListener.promote();
6349 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006350 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6351 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006352 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006353 }
6354
6355 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6356 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006357 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006358
6359 return true;
6360}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006361
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006362status_t Camera3Device::RequestBufferStateMachine::initialize(
6363 sp<camera3::StatusTracker> statusTracker) {
6364 if (statusTracker == nullptr) {
6365 ALOGE("%s: statusTracker is null", __FUNCTION__);
6366 return BAD_VALUE;
6367 }
6368
6369 std::lock_guard<std::mutex> lock(mLock);
6370 mStatusTracker = statusTracker;
6371 mRequestBufferStatusId = statusTracker->addComponent();
6372 return OK;
6373}
6374
6375bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6376 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006377 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006378 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006379 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006380 return true;
6381 }
6382 return false;
6383}
6384
6385void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6386 std::lock_guard<std::mutex> lock(mLock);
6387 if (!mRequestBufferOngoing) {
6388 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6389 return;
6390 }
6391 mRequestBufferOngoing = false;
6392 if (mStatus == RB_STATUS_PENDING_STOP) {
6393 checkSwitchToStopLocked();
6394 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006395 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006396}
6397
6398void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6399 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006400 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006401 return;
6402}
6403
6404void Camera3Device::RequestBufferStateMachine::onRequestSubmitted() {
6405 std::lock_guard<std::mutex> lock(mLock);
6406 mRequestThreadPaused = false;
6407 mInflightMapEmpty = false;
6408 if (mStatus == RB_STATUS_STOPPED) {
6409 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006410 }
6411 return;
6412}
6413
6414void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6415 std::lock_guard<std::mutex> lock(mLock);
6416 mRequestThreadPaused = true;
6417 if (mStatus == RB_STATUS_PENDING_STOP) {
6418 checkSwitchToStopLocked();
6419 }
6420 return;
6421}
6422
6423void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6424 std::lock_guard<std::mutex> lock(mLock);
6425 mInflightMapEmpty = true;
6426 if (mStatus == RB_STATUS_PENDING_STOP) {
6427 checkSwitchToStopLocked();
6428 }
6429 return;
6430}
6431
6432void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6433 std::lock_guard<std::mutex> lock(mLock);
6434 if (!checkSwitchToStopLocked()) {
6435 mStatus = RB_STATUS_PENDING_STOP;
6436 }
6437 return;
6438}
6439
6440void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6441 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6442 if (statusTracker != nullptr) {
6443 if (active) {
6444 statusTracker->markComponentActive(mRequestBufferStatusId);
6445 } else {
6446 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6447 }
6448 }
6449}
6450
6451bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6452 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6453 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006454 return true;
6455 }
6456 return false;
6457}
6458
Shuzhen Wang268a1362018-10-16 16:32:59 -07006459status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6460 CameraMetadata& resultMetadata) {
6461 status_t res = OK;
6462 if (!mNeedFixupMonochromeTags) {
6463 return res;
6464 }
6465
6466 // Remove tags that are not applicable to monochrome camera.
6467 int32_t tagsToRemove[] = {
6468 ANDROID_SENSOR_GREEN_SPLIT,
6469 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6470 ANDROID_COLOR_CORRECTION_MODE,
6471 ANDROID_COLOR_CORRECTION_TRANSFORM,
6472 ANDROID_COLOR_CORRECTION_GAINS,
6473 };
6474 for (auto tag : tagsToRemove) {
6475 res = resultMetadata.erase(tag);
6476 if (res != OK) {
6477 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6478 return res;
6479 }
6480 }
6481
6482 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6483 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6484 for (size_t i = 1; i < blEntry.count; i++) {
6485 blEntry.data.f[i] = blEntry.data.f[0];
6486 }
6487
6488 // ANDROID_SENSOR_NOISE_PROFILE
6489 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6490 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6491 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6492 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6493 if (res != OK) {
6494 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6495 __FUNCTION__, strerror(-res), res);
6496 return res;
6497 }
6498 }
6499
6500 // ANDROID_STATISTICS_LENS_SHADING_MAP
6501 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6502 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6503 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6504 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6505 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6506 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6507 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6508 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6509 }
6510 }
6511
6512 // ANDROID_TONEMAP_CURVE_BLUE
6513 // ANDROID_TONEMAP_CURVE_GREEN
6514 // ANDROID_TONEMAP_CURVE_RED
6515 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6516 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6517 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6518 if (tcbEntry.count > 0
6519 && tcbEntry.count == tcgEntry.count
6520 && tcbEntry.count == tcrEntry.count) {
6521 for (size_t i = 0; i < tcbEntry.count; i++) {
6522 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6523 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6524 }
6525 }
6526
6527 return res;
6528}
6529
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006530}; // namespace android