blob: 99b804394ac6a61b3916b9712d59b57dbeea1746 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Shuzhen Wang5c22c152017-12-31 17:12:25 -080042#include <utility>
43
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080044#include <utils/Log.h>
45#include <utils/Trace.h>
46#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070047#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070048
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080049#include <android/hardware/camera2/ICameraDeviceUser.h>
50
Igor Murashkinff3e31d2013-10-23 16:40:06 -070051#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070052#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "device3/Camera3Device.h"
54#include "device3/Camera3OutputStream.h"
55#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070056#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070057#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070058#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070059#include "utils/CameraThreadState.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080060
61using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080062using namespace android::hardware::camera;
63using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080064
65namespace android {
66
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080067Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080068 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080069 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070070 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070071 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070072 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070073 mUsePartialResult(false),
74 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080075 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070076 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070077 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070078 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070079 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000080 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010081 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070082 mLastTemplateId(-1),
83 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080084{
85 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080086 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080087}
88
89Camera3Device::~Camera3Device()
90{
91 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080092 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -070093 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080094}
95
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080096const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080097 return mId;
98}
99
Emilian Peevbd8c5032018-02-14 23:05:40 +0000100status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ATRACE_CALL();
102 Mutex::Autolock il(mInterfaceLock);
103 Mutex::Autolock l(mLock);
104
105 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
106 if (mStatus != STATUS_UNINITIALIZED) {
107 CLOGE("Already initialized!");
108 return INVALID_OPERATION;
109 }
110 if (manager == nullptr) return INVALID_OPERATION;
111
112 sp<ICameraDeviceSession> session;
113 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800114 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115 /*out*/ &session);
116 ATRACE_END();
117 if (res != OK) {
118 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
119 return res;
120 }
121
Steven Moreland5ff9c912017-03-09 23:13:00 -0800122 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700124 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125 session->close();
126 return res;
127 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800128
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700129 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700130 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700131 if (isLogical) {
132 for (auto& physicalId : physicalCameraIds) {
133 res = manager->getCameraCharacteristics(physicalId, &mPhysicalDeviceInfoMap[physicalId]);
134 if (res != OK) {
135 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
136 physicalId.c_str(), strerror(-res), res);
137 session->close();
138 return res;
139 }
140 }
141 }
142
Yifan Hongf79b5542017-04-11 14:44:25 -0700143 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700144 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
145 [&queue](const auto& descriptor) {
146 queue = std::make_shared<RequestMetadataQueue>(descriptor);
147 if (!queue->isValid() || queue->availableToWrite() <= 0) {
148 ALOGE("HAL returns empty request metadata fmq, not use it");
149 queue = nullptr;
150 // don't use the queue onwards.
151 }
152 });
153 if (!requestQueueRet.isOk()) {
154 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
155 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700156 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700157 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700158
159 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700160 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700161 [&resQueue](const auto& descriptor) {
162 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
163 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700164 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700165 resQueue = nullptr;
166 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700167 }
168 });
169 if (!resultQueueRet.isOk()) {
170 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
171 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700172 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700173 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700174 IF_ALOGV() {
175 session->interfaceChain([](
176 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
177 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800178 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700179 ALOGV(" %s", iface.c_str());
180 }
181 });
182 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700183
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800184 camera_metadata_entry bufMgrMode =
185 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
186 if (bufMgrMode.count > 0) {
187 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
188 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
189 }
190
191 mInterface = new HalInterface(session, queue, mUseHalBufManager);
Emilian Peev71c73a22017-03-21 16:35:51 +0000192 std::string providerType;
193 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000194 mTagMonitor.initialize(mVendorTagId);
195 if (!monitorTags.isEmpty()) {
196 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
197 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800198
Shuzhen Wang268a1362018-10-16 16:32:59 -0700199 // Metadata tags needs fixup for monochrome camera device version less
200 // than 3.5.
201 hardware::hidl_version maxVersion{0,0};
202 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
203 if (res != OK) {
204 ALOGE("%s: Error in getting camera device version id: %s (%d)",
205 __FUNCTION__, strerror(-res), res);
206 return res;
207 }
208 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
209 maxVersion.get_major(), maxVersion.get_minor());
210
211 bool isMonochrome = false;
212 camera_metadata_entry_t entry = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
213 for (size_t i = 0; i < entry.count; i++) {
214 uint8_t capability = entry.data.u8[i];
215 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
216 isMonochrome = true;
217 }
218 }
219 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
220
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800221 return initializeCommonLocked();
222}
223
224status_t Camera3Device::initializeCommonLocked() {
225
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700226 /** Start up status tracker thread */
227 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800228 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700229 if (res != OK) {
230 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
231 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800232 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700233 mStatusTracker.clear();
234 return res;
235 }
236
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700237 /** Register in-flight map to the status tracker */
238 mInFlightStatusId = mStatusTracker->addComponent();
239
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700240 if (mUseHalBufManager) {
241 res = mRequestBufferSM.initialize(mStatusTracker);
242 if (res != OK) {
243 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
244 strerror(-res), res);
245 mInterface->close();
246 mStatusTracker.clear();
247 return res;
248 }
249 }
250
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800251 /** Create buffer manager */
252 mBufferManager = new Camera3BufferManager();
253
254 Vector<int32_t> sessionParamKeys;
255 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
256 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
257 if (sessionKeysEntry.count > 0) {
258 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
259 }
260
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700261 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700262 mRequestThread = new RequestThread(
263 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800264 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800265 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700266 SET_ERR_L("Unable to start request queue thread: %s (%d)",
267 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800268 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800269 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800270 return res;
271 }
272
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700273 mPreparerThread = new PreparerThread();
274
Ruben Brunk183f0562015-08-12 12:55:02 -0700275 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800276 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700277 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700278 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700279 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800280
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800281 // Measure the clock domain offset between camera and video/hw_composer
282 camera_metadata_entry timestampSource =
283 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
284 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
285 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
286 mTimestampOffset = getMonoToBoottimeOffset();
287 }
288
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700289 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100290 camera_metadata_entry partialResultsCount =
291 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
292 if (partialResultsCount.count > 0) {
293 mNumPartialResults = partialResultsCount.data.i32[0];
294 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700295 }
296
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700297 camera_metadata_entry configs =
298 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
299 for (uint32_t i = 0; i < configs.count; i += 4) {
300 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
301 configs.data.i32[i + 3] ==
302 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
303 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
304 configs.data.i32[i + 2]));
305 }
306 }
307
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700308 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
309 res = mDistortionMapper.setupStaticInfo(mDeviceInfo);
310 if (res != OK) {
311 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
312 return res;
313 }
314 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800315 return OK;
316}
317
318status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700319 return disconnectImpl();
320}
321
322status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800323 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700324 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800325
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700326 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800327
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700328 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700329 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700330 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700331 {
332 Mutex::Autolock l(mLock);
333 if (mStatus == STATUS_UNINITIALIZED) return res;
334
335 if (mStatus == STATUS_ACTIVE ||
336 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
337 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700338 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700339 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700340 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700341 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700342 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700343 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700344 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
345 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700346 // Continue to close device even in case of error
347 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700348 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800349 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800350
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700351 if (mStatus == STATUS_ERROR) {
352 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700353 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700354
355 if (mStatusTracker != NULL) {
356 mStatusTracker->requestExit();
357 }
358
359 if (mRequestThread != NULL) {
360 mRequestThread->requestExit();
361 }
362
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700363 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
364 for (size_t i = 0; i < mOutputStreams.size(); i++) {
365 streams.push_back(mOutputStreams[i]);
366 }
367 if (mInputStream != nullptr) {
368 streams.push_back(mInputStream);
369 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700370 }
371
372 // Joining done without holding mLock, otherwise deadlocks may ensue
373 // as the threads try to access parent state
374 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
375 // HAL may be in a bad state, so waiting for request thread
376 // (which may be stuck in the HAL processCaptureRequest call)
377 // could be dangerous.
378 mRequestThread->join();
379 }
380
381 if (mStatusTracker != NULL) {
382 mStatusTracker->join();
383 }
384
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800385 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700386 {
387 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800388 mRequestThread.clear();
Emilian Peev2843c362018-09-26 08:49:40 +0100389 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700390 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800391 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700392 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800393
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700394 // Call close without internal mutex held, as the HAL close may need to
395 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800396 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700397
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700398 flushInflightRequests();
399
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700400 {
401 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800402 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700403 mOutputStreams.clear();
404 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700405 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700406 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700407 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700408 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800409
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700410 for (auto& weakStream : streams) {
411 sp<Camera3StreamInterface> stream = weakStream.promote();
412 if (stream != nullptr) {
413 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
414 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
415 }
416 }
417
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700418 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700419 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800420}
421
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700422// For dumping/debugging only -
423// try to acquire a lock a few times, eventually give up to proceed with
424// debug/dump operations
425bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
426 bool gotLock = false;
427 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
428 if (lock.tryLock() == NO_ERROR) {
429 gotLock = true;
430 break;
431 } else {
432 usleep(kDumpSleepDuration);
433 }
434 }
435 return gotLock;
436}
437
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700438Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
439 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100440 const int STREAM_CONFIGURATION_SIZE = 4;
441 const int STREAM_FORMAT_OFFSET = 0;
442 const int STREAM_WIDTH_OFFSET = 1;
443 const int STREAM_HEIGHT_OFFSET = 2;
444 const int STREAM_IS_INPUT_OFFSET = 3;
445 camera_metadata_ro_entry_t availableStreamConfigs =
446 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
447 if (availableStreamConfigs.count == 0 ||
448 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
449 return Size(0, 0);
450 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700451
Emilian Peev08dd2452017-04-06 16:55:14 +0100452 // Get max jpeg size (area-wise).
453 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
454 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
455 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
456 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
457 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
458 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
459 && format == HAL_PIXEL_FORMAT_BLOB &&
460 (width * height > maxJpegWidth * maxJpegHeight)) {
461 maxJpegWidth = width;
462 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700463 }
464 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100465
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700466 return Size(maxJpegWidth, maxJpegHeight);
467}
468
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800469nsecs_t Camera3Device::getMonoToBoottimeOffset() {
470 // try three times to get the clock offset, choose the one
471 // with the minimum gap in measurements.
472 const int tries = 3;
473 nsecs_t bestGap, measured;
474 for (int i = 0; i < tries; ++i) {
475 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
476 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
477 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
478 const nsecs_t gap = tmono2 - tmono;
479 if (i == 0 || gap < bestGap) {
480 bestGap = gap;
481 measured = tbase - ((tmono + tmono2) >> 1);
482 }
483 }
484 return measured;
485}
486
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800487hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
488 int frameworkFormat) {
489 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
490}
491
492DataspaceFlags Camera3Device::mapToHidlDataspace(
493 android_dataspace dataSpace) {
494 return dataSpace;
495}
496
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700497BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100498 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700499 return usage;
500}
501
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800502StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
503 switch (rotation) {
504 case CAMERA3_STREAM_ROTATION_0:
505 return StreamRotation::ROTATION_0;
506 case CAMERA3_STREAM_ROTATION_90:
507 return StreamRotation::ROTATION_90;
508 case CAMERA3_STREAM_ROTATION_180:
509 return StreamRotation::ROTATION_180;
510 case CAMERA3_STREAM_ROTATION_270:
511 return StreamRotation::ROTATION_270;
512 }
513 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
514 return StreamRotation::ROTATION_0;
515}
516
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800517status_t Camera3Device::mapToStreamConfigurationMode(
518 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
519 if (mode == nullptr) return BAD_VALUE;
520 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
521 switch(operationMode) {
522 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
523 *mode = StreamConfigurationMode::NORMAL_MODE;
524 break;
525 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
526 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
527 break;
528 default:
529 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
530 return BAD_VALUE;
531 }
532 } else {
533 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800535 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800536}
537
538camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
539 switch (status) {
540 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
541 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
542 }
543 return CAMERA3_BUFFER_STATUS_ERROR;
544}
545
546int Camera3Device::mapToFrameworkFormat(
547 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
548 return static_cast<uint32_t>(pixelFormat);
549}
550
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700551android_dataspace Camera3Device::mapToFrameworkDataspace(
552 DataspaceFlags dataSpace) {
553 return static_cast<android_dataspace>(dataSpace);
554}
555
Emilian Peev050f5dc2017-05-18 14:43:56 +0100556uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700557 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700558 return usage;
559}
560
Emilian Peev050f5dc2017-05-18 14:43:56 +0100561uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700562 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700563 return usage;
564}
565
Zhijun Hef7da0962014-04-24 13:27:56 -0700566ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700567 // Get max jpeg size (area-wise).
568 Size maxJpegResolution = getMaxJpegResolution();
569 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800570 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
571 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700572 return BAD_VALUE;
573 }
574
Zhijun Hef7da0962014-04-24 13:27:56 -0700575 // Get max jpeg buffer size
576 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700577 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
578 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800579 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
580 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700581 return BAD_VALUE;
582 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700583 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800584 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700585
586 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700587 float scaleFactor = ((float) (width * height)) /
588 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800589 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
590 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700591 if (jpegBufferSize > maxJpegBufferSize) {
592 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700593 }
594
595 return jpegBufferSize;
596}
597
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700598ssize_t Camera3Device::getPointCloudBufferSize() const {
599 const int FLOATS_PER_POINT=4;
600 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
601 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800602 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
603 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700604 return BAD_VALUE;
605 }
606 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
607 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
608 return maxBytesForPointCloud;
609}
610
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800611ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800612 const int PER_CONFIGURATION_SIZE = 3;
613 const int WIDTH_OFFSET = 0;
614 const int HEIGHT_OFFSET = 1;
615 const int SIZE_OFFSET = 2;
616 camera_metadata_ro_entry rawOpaqueSizes =
617 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800618 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800619 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800620 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
621 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800622 return BAD_VALUE;
623 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700624
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800625 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
626 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
627 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
628 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
629 }
630 }
631
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800632 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
633 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800634 return BAD_VALUE;
635}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700636
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800637status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
638 ATRACE_CALL();
639 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700640
641 // Try to lock, but continue in case of failure (to avoid blocking in
642 // deadlocks)
643 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
644 bool gotLock = tryLockSpinRightRound(mLock);
645
646 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800647 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
648 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700649 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800650 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
651 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700652
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800653 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700654
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800655 String16 templatesOption("-t");
656 int n = args.size();
657 for (int i = 0; i < n; i++) {
658 if (args[i] == templatesOption) {
659 dumpTemplates = true;
660 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000661 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700662 if (i + 1 < n) {
663 String8 monitorTags = String8(args[i + 1]);
664 if (monitorTags == "off") {
665 mTagMonitor.disableMonitoring();
666 } else {
667 mTagMonitor.parseTagsToMonitor(monitorTags);
668 }
669 } else {
670 mTagMonitor.disableMonitoring();
671 }
672 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800673 }
674
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800675 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800676
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800677 const char *status =
678 mStatus == STATUS_ERROR ? "ERROR" :
679 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700680 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
681 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800682 mStatus == STATUS_ACTIVE ? "ACTIVE" :
683 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700684
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800685 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700686 if (mStatus == STATUS_ERROR) {
687 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
688 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800689 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800690 const char *mode =
691 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
692 mOperatingMode == static_cast<int>(
693 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
694 "CUSTOM";
695 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800696
697 if (mInputStream != NULL) {
698 write(fd, lines.string(), lines.size());
699 mInputStream->dump(fd, args);
700 } else {
701 lines.appendFormat(" No input stream.\n");
702 write(fd, lines.string(), lines.size());
703 }
704 for (size_t i = 0; i < mOutputStreams.size(); i++) {
705 mOutputStreams[i]->dump(fd,args);
706 }
707
Zhijun He431503c2016-03-07 17:30:16 -0800708 if (mBufferManager != NULL) {
709 lines = String8(" Camera3 Buffer Manager:\n");
710 write(fd, lines.string(), lines.size());
711 mBufferManager->dump(fd, args);
712 }
Zhijun He125684a2015-12-26 15:07:30 -0800713
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700714 lines = String8(" In-flight requests:\n");
715 if (mInFlightMap.size() == 0) {
716 lines.append(" None\n");
717 } else {
718 for (size_t i = 0; i < mInFlightMap.size(); i++) {
719 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700720 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700721 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800722 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700723 r.numBuffersLeft);
724 }
725 }
726 write(fd, lines.string(), lines.size());
727
Shuzhen Wang686f6442017-06-20 16:16:04 -0700728 if (mRequestThread != NULL) {
729 mRequestThread->dumpCaptureRequestLatency(fd,
730 " ProcessCaptureRequest latency histogram:");
731 }
732
Igor Murashkin1e479c02013-09-06 16:55:14 -0700733 {
734 lines = String8(" Last request sent:\n");
735 write(fd, lines.string(), lines.size());
736
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700737 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700738 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
739 }
740
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800741 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800742 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800743 "TEMPLATE_PREVIEW",
744 "TEMPLATE_STILL_CAPTURE",
745 "TEMPLATE_VIDEO_RECORD",
746 "TEMPLATE_VIDEO_SNAPSHOT",
747 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800748 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800749 };
750
751 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800752 camera_metadata_t *templateRequest = nullptr;
753 mInterface->constructDefaultRequestSettings(
754 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800755 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800756 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800757 lines.append(" Not supported\n");
758 write(fd, lines.string(), lines.size());
759 } else {
760 write(fd, lines.string(), lines.size());
761 dump_indented_camera_metadata(templateRequest,
762 fd, /*verbosity*/2, /*indentation*/8);
763 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800764 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800765 }
766 }
767
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700768 mTagMonitor.dumpMonitoredMetadata(fd);
769
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800770 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800771 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800772 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800773 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800774 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800775
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700776 if (gotLock) mLock.unlock();
777 if (gotInterfaceLock) mInterfaceLock.unlock();
778
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800779 return OK;
780}
781
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700782const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800783 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800784 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
785 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700786 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800787 mStatus == STATUS_ERROR ?
788 "when in error state" : "before init");
789 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700790 if (physicalId.isEmpty()) {
791 return mDeviceInfo;
792 } else {
793 std::string id(physicalId.c_str());
794 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
795 return mPhysicalDeviceInfoMap.at(id);
796 } else {
797 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
798 return mDeviceInfo;
799 }
800 }
801}
802
803const CameraMetadata& Camera3Device::info() const {
804 String8 emptyId;
805 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800806}
807
Jianing Wei90e59c92014-03-12 18:29:36 -0700808status_t Camera3Device::checkStatusOkToCaptureLocked() {
809 switch (mStatus) {
810 case STATUS_ERROR:
811 CLOGE("Device has encountered a serious error");
812 return INVALID_OPERATION;
813 case STATUS_UNINITIALIZED:
814 CLOGE("Device not initialized");
815 return INVALID_OPERATION;
816 case STATUS_UNCONFIGURED:
817 case STATUS_CONFIGURED:
818 case STATUS_ACTIVE:
819 // OK
820 break;
821 default:
822 SET_ERR_L("Unexpected status: %d", mStatus);
823 return INVALID_OPERATION;
824 }
825 return OK;
826}
827
828status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000829 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700830 const std::list<const SurfaceMap> &surfaceMaps,
831 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700832 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700833 if (requestList == NULL) {
834 CLOGE("requestList cannot be NULL.");
835 return BAD_VALUE;
836 }
837
Jianing Weicb0652e2014-03-12 18:29:36 -0700838 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000839 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700840 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
841 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
842 ++metadataIt, ++surfaceMapIt) {
843 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700844 if (newRequest == 0) {
845 CLOGE("Can't create capture request");
846 return BAD_VALUE;
847 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700848
Shuzhen Wang9d066012016-09-30 11:30:20 -0700849 newRequest->mRepeating = repeating;
850
Jianing Weicb0652e2014-03-12 18:29:36 -0700851 // Setup burst Id and request Id
852 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000853 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
854 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700855 CLOGE("RequestID entry exists; but must not be empty in metadata");
856 return BAD_VALUE;
857 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000858 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
859 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700860 } else {
861 CLOGE("RequestID does not exist in metadata");
862 return BAD_VALUE;
863 }
864
Jianing Wei90e59c92014-03-12 18:29:36 -0700865 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700866
867 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700868 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700869 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
870 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
871 return BAD_VALUE;
872 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700873
874 // Setup batch size if this is a high speed video recording request.
875 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
876 auto firstRequest = requestList->begin();
877 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
878 if (outputStream->isVideoStream()) {
879 (*firstRequest)->mBatchSize = requestList->size();
880 break;
881 }
882 }
883 }
884
Jianing Wei90e59c92014-03-12 18:29:36 -0700885 return OK;
886}
887
Jianing Weicb0652e2014-03-12 18:29:36 -0700888status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800889 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800890
Emilian Peevaebbe412018-01-15 13:53:24 +0000891 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700892 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000893 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700894
Emilian Peevaebbe412018-01-15 13:53:24 +0000895 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700896}
897
Emilian Peevaebbe412018-01-15 13:53:24 +0000898void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700899 std::list<const SurfaceMap>& surfaceMaps,
900 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000901 PhysicalCameraSettingsList requestList;
902 requestList.push_back({std::string(getId().string()), request});
903 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700904
905 SurfaceMap surfaceMap;
906 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
907 // With no surface list passed in, stream and surface will have 1-to-1
908 // mapping. So the surface index is 0 for each stream in the surfaceMap.
909 for (size_t i = 0; i < streams.count; i++) {
910 surfaceMap[streams.data.i32[i]].push_back(0);
911 }
912 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800913}
914
Jianing Wei90e59c92014-03-12 18:29:36 -0700915status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000916 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700917 const std::list<const SurfaceMap> &surfaceMaps,
918 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700919 /*out*/
920 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700921 ATRACE_CALL();
922 Mutex::Autolock il(mInterfaceLock);
923 Mutex::Autolock l(mLock);
924
925 status_t res = checkStatusOkToCaptureLocked();
926 if (res != OK) {
927 // error logged by previous call
928 return res;
929 }
930
931 RequestList requestList;
932
Shuzhen Wang0129d522016-10-30 22:43:41 -0700933 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
934 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700935 if (res != OK) {
936 // error logged by previous call
937 return res;
938 }
939
940 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700941 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700942 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700943 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700944 }
945
946 if (res == OK) {
947 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
948 if (res != OK) {
949 SET_ERR_L("Can't transition to active in %f seconds!",
950 kActiveTimeout/1e9);
951 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800952 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700953 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700954 } else {
955 CLOGE("Cannot queue request. Impossible.");
956 return BAD_VALUE;
957 }
958
959 return res;
960}
961
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700962hardware::Return<void> Camera3Device::requestStreamBuffers(
963 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
964 requestStreamBuffers_cb _hidl_cb) {
965 using hardware::camera::device::V3_5::BufferRequestStatus;
966 using hardware::camera::device::V3_5::StreamBufferRet;
967 using hardware::camera::device::V3_5::StreamBufferRequestError;
968
969 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
970
971 hardware::hidl_vec<StreamBufferRet> bufRets;
972 if (!mUseHalBufManager) {
973 ALOGE("%s: Camera %s does not support HAL buffer management",
974 __FUNCTION__, mId.string());
975 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
976 return hardware::Void();
977 }
978
979 SortedVector<int32_t> streamIds;
980 ssize_t sz = streamIds.setCapacity(bufReqs.size());
981 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
982 ALOGE("%s: failed to allocate memory for %zu buffer requests",
983 __FUNCTION__, bufReqs.size());
984 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
985 return hardware::Void();
986 }
987
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700988 if (bufReqs.size() > mOutputStreams.size()) {
989 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
990 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
991 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
992 return hardware::Void();
993 }
994
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700995 // Check for repeated streamId
996 for (const auto& bufReq : bufReqs) {
997 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
998 ALOGE("%s: Stream %d appear multiple times in buffer requests",
999 __FUNCTION__, bufReq.streamId);
1000 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1001 return hardware::Void();
1002 }
1003 streamIds.add(bufReq.streamId);
1004 }
1005
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001006 if (!mRequestBufferSM.startRequestBuffer()) {
1007 ALOGE("%s: request buffer disallowed while camera service is configuring",
1008 __FUNCTION__);
1009 _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001010 return hardware::Void();
1011 }
1012
1013 bufRets.resize(bufReqs.size());
1014
1015 bool allReqsSucceeds = true;
1016 bool oneReqSucceeds = false;
1017 for (size_t i = 0; i < bufReqs.size(); i++) {
1018 const auto& bufReq = bufReqs[i];
1019 auto& bufRet = bufRets[i];
1020 int32_t streamId = bufReq.streamId;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001021 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
1022 if (outputStream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001023 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
1024 hardware::hidl_vec<StreamBufferRet> emptyBufRets;
1025 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001026 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001027 return hardware::Void();
1028 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001029
1030 bufRet.streamId = streamId;
1031 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
1032 size_t totalHandout = outputStream->getOutstandingBuffersCount() + numBuffersRequested;
1033 if (totalHandout > outputStream->asHalStream()->max_buffers) {
1034 // Not able to allocate enough buffer. Exit early for this stream
1035 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1036 allReqsSucceeds = false;
1037 continue;
1038 }
1039
1040 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1041 bool currentReqSucceeds = true;
1042 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1043 size_t numAllocatedBuffers = 0;
1044 size_t numPushedInflightBuffers = 0;
1045 for (size_t b = 0; b < numBuffersRequested; b++) {
1046 camera3_stream_buffer_t& sb = streamBuffers[b];
1047 // Since this method can run concurrently with request thread
1048 // We need to update the wait duration everytime we call getbuffer
1049 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1050 status_t res = outputStream->getBuffer(&sb, waitDuration);
1051 if (res != OK) {
1052 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1053 __FUNCTION__, streamId, strerror(-res), res);
1054 if (res == NO_INIT || res == DEAD_OBJECT) {
1055 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1056 } else if (res == TIMED_OUT || res == NO_MEMORY) {
1057 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1058 } else {
1059 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1060 }
1061 currentReqSucceeds = false;
1062 break;
1063 }
1064 numAllocatedBuffers++;
1065
1066 buffer_handle_t *buffer = sb.buffer;
1067 auto pair = mInterface->getBufferId(*buffer, streamId);
1068 bool isNewBuffer = pair.first;
1069 uint64_t bufferId = pair.second;
1070 StreamBuffer& hBuf = tmpRetBuffers[b];
1071
1072 hBuf.streamId = streamId;
1073 hBuf.bufferId = bufferId;
1074 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1075 hBuf.status = BufferStatus::OK;
1076 hBuf.releaseFence = nullptr;
1077
1078 native_handle_t *acquireFence = nullptr;
1079 if (sb.acquire_fence != -1) {
1080 acquireFence = native_handle_create(1,0);
1081 acquireFence->data[0] = sb.acquire_fence;
1082 }
1083 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1084 hBuf.releaseFence = nullptr;
1085
1086 res = mInterface->pushInflightRequestBuffer(bufferId, buffer);
1087 if (res != OK) {
1088 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1089 __FUNCTION__, streamId, strerror(-res), res);
1090 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1091 currentReqSucceeds = false;
1092 break;
1093 }
1094 numPushedInflightBuffers++;
1095 }
1096 if (currentReqSucceeds) {
1097 bufRet.val.buffers(std::move(tmpRetBuffers));
1098 oneReqSucceeds = true;
1099 } else {
1100 allReqsSucceeds = false;
1101 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1102 StreamBuffer& hBuf = tmpRetBuffers[b];
1103 buffer_handle_t* buffer;
1104 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1105 if (res != OK) {
1106 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1107 __FUNCTION__, streamId, strerror(-res), res);
1108 }
1109 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001110 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1111 camera3_stream_buffer_t& sb = streamBuffers[b];
1112 sb.acquire_fence = -1;
1113 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1114 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001115 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1116 }
1117 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001118
1119 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1120 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1121 BufferRequestStatus::FAILED_UNKNOWN,
1122 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001123 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001124 return hardware::Void();
1125}
1126
1127hardware::Return<void> Camera3Device::returnStreamBuffers(
1128 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1129 if (!mUseHalBufManager) {
1130 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1131 __FUNCTION__, mId.string());
1132 return hardware::Void();
1133 }
1134
1135 for (const auto& buf : buffers) {
1136 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1137 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1138 continue;
1139 }
1140
1141 buffer_handle_t* buffer;
1142 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1143
1144 if (res != OK) {
1145 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1146 __FUNCTION__, buf.bufferId, buf.streamId);
1147 continue;
1148 }
1149
1150 camera3_stream_buffer_t streamBuffer;
1151 streamBuffer.buffer = buffer;
1152 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1153 streamBuffer.acquire_fence = -1;
1154 streamBuffer.release_fence = -1;
1155
1156 if (buf.releaseFence == nullptr) {
1157 streamBuffer.release_fence = -1;
1158 } else if (buf.releaseFence->numFds == 1) {
1159 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1160 } else {
1161 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1162 __FUNCTION__, buf.releaseFence->numFds);
1163 continue;
1164 }
1165
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001166 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1167 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001168 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1169 continue;
1170 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001171 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001172 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1173 }
1174 return hardware::Void();
1175}
1176
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001177hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001178 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001179 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001180 // Ideally we should grab mLock, but that can lead to deadlock, and
1181 // it's not super important to get up to date value of mStatus for this
1182 // warning print, hence skipping the lock here
1183 if (mStatus == STATUS_ERROR) {
1184 // Per API contract, HAL should act as closed after device error
1185 // But mStatus can be set to error by framework as well, so just log
1186 // a warning here.
1187 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001188 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001189
1190 if (mProcessCaptureResultLock.tryLock() != OK) {
1191 // This should never happen; it indicates a wrong client implementation
1192 // that doesn't follow the contract. But, we can be tolerant here.
1193 ALOGE("%s: callback overlapped! waiting 1s...",
1194 __FUNCTION__);
1195 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1196 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1197 __FUNCTION__);
1198 // really don't know what to do, so bail out.
1199 return hardware::Void();
1200 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001201 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001202 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001203 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001204 }
1205 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001206 return hardware::Void();
1207}
1208
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001209// Only one processCaptureResult should be called at a time, so
1210// the locks won't block. The locks are present here simply to enforce this.
1211hardware::Return<void> Camera3Device::processCaptureResult(
1212 const hardware::hidl_vec<
1213 hardware::camera::device::V3_2::CaptureResult>& results) {
1214 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1215
1216 // Ideally we should grab mLock, but that can lead to deadlock, and
1217 // it's not super important to get up to date value of mStatus for this
1218 // warning print, hence skipping the lock here
1219 if (mStatus == STATUS_ERROR) {
1220 // Per API contract, HAL should act as closed after device error
1221 // But mStatus can be set to error by framework as well, so just log
1222 // a warning here.
1223 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1224 }
1225
1226 if (mProcessCaptureResultLock.tryLock() != OK) {
1227 // This should never happen; it indicates a wrong client implementation
1228 // that doesn't follow the contract. But, we can be tolerant here.
1229 ALOGE("%s: callback overlapped! waiting 1s...",
1230 __FUNCTION__);
1231 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1232 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1233 __FUNCTION__);
1234 // really don't know what to do, so bail out.
1235 return hardware::Void();
1236 }
1237 }
1238 for (const auto& result : results) {
1239 processOneCaptureResultLocked(result, noPhysMetadata);
1240 }
1241 mProcessCaptureResultLock.unlock();
1242 return hardware::Void();
1243}
1244
1245status_t Camera3Device::readOneCameraMetadataLocked(
1246 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1247 const hardware::camera::device::V3_2::CameraMetadata& result) {
1248 if (fmqResultSize > 0) {
1249 resultMetadata.resize(fmqResultSize);
1250 if (mResultMetadataQueue == nullptr) {
1251 return NO_MEMORY; // logged in initialize()
1252 }
1253 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1254 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1255 __FUNCTION__, fmqResultSize);
1256 return INVALID_OPERATION;
1257 }
1258 } else {
1259 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1260 result.size());
1261 }
1262
1263 if (resultMetadata.size() != 0) {
1264 status_t res;
1265 const camera_metadata_t* metadata =
1266 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1267 size_t expected_metadata_size = resultMetadata.size();
1268 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1269 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1270 __FUNCTION__, strerror(-res), res);
1271 return INVALID_OPERATION;
1272 }
1273 }
1274
1275 return OK;
1276}
1277
Yifan Honga640c5a2017-04-12 16:30:31 -07001278void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001279 const hardware::camera::device::V3_2::CaptureResult& result,
1280 const hardware::hidl_vec<
1281 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001282 camera3_capture_result r;
1283 status_t res;
1284 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001285
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001286 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001287 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001288 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1289 if (res != OK) {
1290 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1291 __FUNCTION__, result.frameNumber);
1292 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001293 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001294 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001295
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001296 // Read and validate physical camera metadata
1297 size_t physResultCount = physicalCameraMetadatas.size();
1298 std::vector<const char*> physCamIds(physResultCount);
1299 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1300 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1301 physResultMetadata.resize(physResultCount);
1302 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1303 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1304 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1305 if (res != OK) {
1306 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1307 __FUNCTION__, result.frameNumber,
1308 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001309 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001310 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001311 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1312 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1313 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001314 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001315 r.num_physcam_metadata = physResultCount;
1316 r.physcam_ids = physCamIds.data();
1317 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001318
1319 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1320 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1321 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1322 auto& bDst = outputBuffers[i];
1323 const StreamBuffer &bSrc = result.outputBuffers[i];
1324
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001325 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1326 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001327 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1328 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001329 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001330 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001331 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001332
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001333 bool noBufferReturned = false;
1334 buffer_handle_t *buffer = nullptr;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001335 if (mUseHalBufManager) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001336 // This is suspicious most of the time but can be correct during flush where HAL
1337 // has to return capture result before a buffer is requested
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001338 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001339 if (bSrc.status == BufferStatus::OK) {
1340 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1341 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1342 // Still proceeds so other buffers can be returned
1343 }
1344 noBufferReturned = true;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001345 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001346 if (noBufferReturned) {
1347 res = OK;
1348 } else {
1349 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1350 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001351 } else {
1352 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1353 }
1354
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001355 if (res != OK) {
1356 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1357 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001358 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001359 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001360
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001361 bDst.buffer = buffer;
1362 bDst.status = mapHidlBufferStatus(bSrc.status);
1363 bDst.acquire_fence = -1;
1364 if (bSrc.releaseFence == nullptr) {
1365 bDst.release_fence = -1;
1366 } else if (bSrc.releaseFence->numFds == 1) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001367 if (noBufferReturned) {
1368 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
1369 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001370 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1371 } else {
1372 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1373 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001374 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001375 }
1376 }
1377 r.num_output_buffers = outputBuffers.size();
1378 r.output_buffers = outputBuffers.data();
1379
1380 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001381 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001382 r.input_buffer = nullptr;
1383 } else {
1384 if (mInputStream->getId() != result.inputBuffer.streamId) {
1385 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1386 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001387 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001388 }
1389 inputBuffer.stream = mInputStream->asHalStream();
1390 buffer_handle_t *buffer;
1391 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1392 &buffer);
1393 if (res != OK) {
1394 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1395 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001396 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001397 }
1398 inputBuffer.buffer = buffer;
1399 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1400 inputBuffer.acquire_fence = -1;
1401 if (result.inputBuffer.releaseFence == nullptr) {
1402 inputBuffer.release_fence = -1;
1403 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1404 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1405 } else {
1406 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1407 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001408 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001409 }
1410 r.input_buffer = &inputBuffer;
1411 }
1412
1413 r.partial_result = result.partialResult;
1414
1415 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001416}
1417
1418hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001419 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001420 // Ideally we should grab mLock, but that can lead to deadlock, and
1421 // it's not super important to get up to date value of mStatus for this
1422 // warning print, hence skipping the lock here
1423 if (mStatus == STATUS_ERROR) {
1424 // Per API contract, HAL should act as closed after device error
1425 // But mStatus can be set to error by framework as well, so just log
1426 // a warning here.
1427 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001428 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001429
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001430 for (const auto& msg : msgs) {
1431 notify(msg);
1432 }
1433 return hardware::Void();
1434}
1435
1436void Camera3Device::notify(
1437 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1438
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001439 camera3_notify_msg m;
1440 switch (msg.type) {
1441 case MsgType::ERROR:
1442 m.type = CAMERA3_MSG_ERROR;
1443 m.message.error.frame_number = msg.msg.error.frameNumber;
1444 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001445 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1446 if (stream == nullptr) {
1447 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1448 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001449 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001450 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001451 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001452 } else {
1453 m.message.error.error_stream = nullptr;
1454 }
1455 switch (msg.msg.error.errorCode) {
1456 case ErrorCode::ERROR_DEVICE:
1457 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1458 break;
1459 case ErrorCode::ERROR_REQUEST:
1460 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1461 break;
1462 case ErrorCode::ERROR_RESULT:
1463 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1464 break;
1465 case ErrorCode::ERROR_BUFFER:
1466 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1467 break;
1468 }
1469 break;
1470 case MsgType::SHUTTER:
1471 m.type = CAMERA3_MSG_SHUTTER;
1472 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1473 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1474 break;
1475 }
1476 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001477}
1478
Emilian Peevaebbe412018-01-15 13:53:24 +00001479status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001480 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001481 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001482 ATRACE_CALL();
1483
Emilian Peevaebbe412018-01-15 13:53:24 +00001484 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001485}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001486
Jianing Weicb0652e2014-03-12 18:29:36 -07001487status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1488 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001489 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001490
Emilian Peevaebbe412018-01-15 13:53:24 +00001491 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001492 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001493 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001494
Emilian Peevaebbe412018-01-15 13:53:24 +00001495 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001496 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497}
1498
Emilian Peevaebbe412018-01-15 13:53:24 +00001499status_t Camera3Device::setStreamingRequestList(
1500 const List<const PhysicalCameraSettingsList> &requestsList,
1501 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001502 ATRACE_CALL();
1503
Emilian Peevaebbe412018-01-15 13:53:24 +00001504 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001505}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001506
1507sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001508 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001509 status_t res;
1510
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001511 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001512 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1513 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001514 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1515 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001516 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001517 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001518 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001519 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001520 } else if (mStatus == STATUS_UNCONFIGURED) {
1521 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001522 CLOGE("No streams configured");
1523 return NULL;
1524 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001525 }
1526
Shuzhen Wang0129d522016-10-30 22:43:41 -07001527 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001529}
1530
Jianing Weicb0652e2014-03-12 18:29:36 -07001531status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001532 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001533 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001535
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 switch (mStatus) {
1537 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001538 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 return INVALID_OPERATION;
1540 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001541 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001543 case STATUS_UNCONFIGURED:
1544 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 case STATUS_ACTIVE:
1546 // OK
1547 break;
1548 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001549 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001550 return INVALID_OPERATION;
1551 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001552 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001553
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001554 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001555}
1556
1557status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1558 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001559 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001560
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001561 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001562}
1563
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001564status_t Camera3Device::createInputStream(
1565 uint32_t width, uint32_t height, int format, int *id) {
1566 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001567 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001568 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001569 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001570 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1571 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001572
1573 status_t res;
1574 bool wasActive = false;
1575
1576 switch (mStatus) {
1577 case STATUS_ERROR:
1578 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1579 return INVALID_OPERATION;
1580 case STATUS_UNINITIALIZED:
1581 ALOGE("%s: Device not initialized", __FUNCTION__);
1582 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001583 case STATUS_UNCONFIGURED:
1584 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001585 // OK
1586 break;
1587 case STATUS_ACTIVE:
1588 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001589 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001590 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001591 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001592 return res;
1593 }
1594 wasActive = true;
1595 break;
1596 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001597 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001598 return INVALID_OPERATION;
1599 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001600 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001601
1602 if (mInputStream != 0) {
1603 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1604 return INVALID_OPERATION;
1605 }
1606
1607 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1608 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001609 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001610
1611 mInputStream = newStream;
1612
1613 *id = mNextStreamId++;
1614
1615 // Continue captures if active at start
1616 if (wasActive) {
1617 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001618 // Reuse current operating mode and session parameters for new stream config
1619 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001620 if (res != OK) {
1621 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1622 __FUNCTION__, mNextStreamId, strerror(-res), res);
1623 return res;
1624 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001625 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001626 }
1627
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001628 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001629 return OK;
1630}
1631
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001632status_t Camera3Device::StreamSet::add(
1633 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1634 if (stream == nullptr) {
1635 ALOGE("%s: cannot add null stream", __FUNCTION__);
1636 return BAD_VALUE;
1637 }
1638 std::lock_guard<std::mutex> lock(mLock);
1639 return mData.add(streamId, stream);
1640}
1641
1642ssize_t Camera3Device::StreamSet::remove(int streamId) {
1643 std::lock_guard<std::mutex> lock(mLock);
1644 return mData.removeItem(streamId);
1645}
1646
1647sp<camera3::Camera3OutputStreamInterface>
1648Camera3Device::StreamSet::get(int streamId) {
1649 std::lock_guard<std::mutex> lock(mLock);
1650 ssize_t idx = mData.indexOfKey(streamId);
1651 if (idx == NAME_NOT_FOUND) {
1652 return nullptr;
1653 }
1654 return mData.editValueAt(idx);
1655}
1656
1657sp<camera3::Camera3OutputStreamInterface>
1658Camera3Device::StreamSet::operator[] (size_t index) {
1659 std::lock_guard<std::mutex> lock(mLock);
1660 return mData.editValueAt(index);
1661}
1662
1663size_t Camera3Device::StreamSet::size() const {
1664 std::lock_guard<std::mutex> lock(mLock);
1665 return mData.size();
1666}
1667
1668void Camera3Device::StreamSet::clear() {
1669 std::lock_guard<std::mutex> lock(mLock);
1670 return mData.clear();
1671}
1672
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001673std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1674 std::lock_guard<std::mutex> lock(mLock);
1675 std::vector<int> streamIds(mData.size());
1676 for (size_t i = 0; i < mData.size(); i++) {
1677 streamIds[i] = mData.keyAt(i);
1678 }
1679 return streamIds;
1680}
1681
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001682status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001683 uint32_t width, uint32_t height, int format,
1684 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001685 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001686 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001687 ATRACE_CALL();
1688
1689 if (consumer == nullptr) {
1690 ALOGE("%s: consumer must not be null", __FUNCTION__);
1691 return BAD_VALUE;
1692 }
1693
1694 std::vector<sp<Surface>> consumers;
1695 consumers.push_back(consumer);
1696
1697 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001698 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1699 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001700}
1701
1702status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1703 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1704 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001705 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001706 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001707 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001708
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001709 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001710 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001711 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001712 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001713 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1714 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1715 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001716
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001717 status_t res;
1718 bool wasActive = false;
1719
1720 switch (mStatus) {
1721 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001722 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001723 return INVALID_OPERATION;
1724 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001725 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001726 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001727 case STATUS_UNCONFIGURED:
1728 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001729 // OK
1730 break;
1731 case STATUS_ACTIVE:
1732 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001733 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001734 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001735 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001736 return res;
1737 }
1738 wasActive = true;
1739 break;
1740 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001741 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001742 return INVALID_OPERATION;
1743 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001744 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001745
1746 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001747
Shuzhen Wang0129d522016-10-30 22:43:41 -07001748 if (consumers.size() == 0 && !hasDeferredConsumer) {
1749 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1750 return BAD_VALUE;
1751 }
Zhijun He5d677d12016-05-29 16:52:39 -07001752
Shuzhen Wang0129d522016-10-30 22:43:41 -07001753 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001754 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1755 return BAD_VALUE;
1756 }
1757
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001758 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001759 ssize_t blobBufferSize;
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(
Emilian Peev538c90e2018-12-17 18:03:19 +00003122 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3123 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003124 } else {
3125 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003126 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3127 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003128 }
3129
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003130 // Note: stream may be deallocated at this point, if this buffer was
3131 // the last reference to it.
3132 if (res != OK) {
3133 ALOGE("Can't return buffer to its stream: %s (%d)",
3134 strerror(-res), res);
3135 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003136
3137 // Long processing consumers can cause returnBuffer timeout for shared stream
3138 // If that happens, cancel the buffer and send a buffer error to client
3139 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3140 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3141 // cancel the buffer
3142 camera3_stream_buffer_t sb = outputBuffers[i];
3143 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003144 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3145 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003146
3147 // notify client buffer error
3148 sp<NotificationListener> listener;
3149 {
3150 Mutex::Autolock l(mOutputLock);
3151 listener = mListener.promote();
3152 }
3153
3154 if (listener != nullptr) {
3155 CaptureResultExtras extras = inResultExtras;
3156 extras.errorStreamId = streamId;
3157 listener->notifyError(
3158 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3159 extras);
3160 }
3161 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003162 }
3163}
3164
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003165void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003166 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003167 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003168 mInFlightMap.removeItemsAt(idx, 1);
3169
3170 // Indicate idle inFlightMap to the status tracker
3171 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003172 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003173 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3174 // avoid a deadlock during reprocess requests.
3175 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003176 if (mStatusTracker != nullptr) {
3177 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3178 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003179 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003180 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003181}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003182
3183void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3184
3185 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3186 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3187
3188 nsecs_t sensorTimestamp = request.sensorTimestamp;
3189 nsecs_t shutterTimestamp = request.shutterTimestamp;
3190
3191 // Check if it's okay to remove the request from InFlightMap:
3192 // In the case of a successful request:
3193 // all input and output buffers, all result metadata, shutter callback
3194 // arrived.
3195 // In the case of a unsuccessful request:
3196 // all input and output buffers arrived.
3197 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003198 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003199 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003200 if (request.stillCapture) {
3201 ATRACE_ASYNC_END("still capture", frameNumber);
3202 }
3203
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003204 ATRACE_ASYNC_END("frame capture", frameNumber);
3205
Shuzhen Wang403044a2017-02-26 23:29:04 -08003206 // Sanity check - if sensor timestamp matches shutter timestamp in the
3207 // case of request having callback.
3208 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003209 sensorTimestamp != shutterTimestamp) {
3210 SET_ERR("sensor timestamp (%" PRId64
3211 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3212 sensorTimestamp, frameNumber, shutterTimestamp);
3213 }
3214
3215 // for an unsuccessful request, it may have pending output buffers to
3216 // return.
3217 assert(request.requestStatus != OK ||
3218 request.pendingOutputBuffers.size() == 0);
3219 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003220 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3221 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003222
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003223 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003224 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3225 }
3226
3227 // Sanity check - if we have too many in-flight frames, something has
3228 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003229 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003230 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003231 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3232 kInFlightWarnLimitHighSpeed) {
3233 CLOGE("In-flight list too large for high speed configuration: %zu",
3234 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003235 }
3236}
3237
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003238void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003239 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003240 { // First return buffers cached in mInFlightMap
3241 Mutex::Autolock l(mInFlightLock);
3242 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3243 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3244 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003245 request.pendingOutputBuffers.size(), 0,
3246 /*timestampIncreasing*/true, request.outputSurfaces,
3247 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003248 }
3249 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003250 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003251 }
3252
3253 // Then return all inflight buffers not returned by HAL
3254 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3255 mInterface->getInflightBufferKeys(&inflightKeys);
3256
3257 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3258 for (auto& pair : inflightKeys) {
3259 int32_t frameNumber = pair.first;
3260 int32_t streamId = pair.second;
3261 buffer_handle_t* buffer;
3262 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3263 if (res != OK) {
3264 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3265 __FUNCTION__, frameNumber, streamId);
3266 continue;
3267 }
3268
3269 camera3_stream_buffer_t streamBuffer;
3270 streamBuffer.buffer = buffer;
3271 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3272 streamBuffer.acquire_fence = -1;
3273 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003274
3275 // First check if the buffer belongs to deleted stream
3276 bool streamDeleted = false;
3277 for (auto& stream : mDeletedStreams) {
3278 if (streamId == stream->getId()) {
3279 streamDeleted = true;
3280 // Return buffer to deleted stream
3281 camera3_stream* halStream = stream->asHalStream();
3282 streamBuffer.stream = halStream;
3283 switch (halStream->stream_type) {
3284 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003285 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3286 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003287 if (res != OK) {
3288 ALOGE("%s: Can't return output buffer for frame %d to"
3289 " stream %d: %s (%d)", __FUNCTION__,
3290 frameNumber, streamId, strerror(-res), res);
3291 }
3292 break;
3293 case CAMERA3_STREAM_INPUT:
3294 res = stream->returnInputBuffer(streamBuffer);
3295 if (res != OK) {
3296 ALOGE("%s: Can't return input buffer for frame %d to"
3297 " stream %d: %s (%d)", __FUNCTION__,
3298 frameNumber, streamId, strerror(-res), res);
3299 }
3300 break;
3301 default: // Bi-direcitonal stream is deprecated
3302 ALOGE("%s: stream %d has unknown stream type %d",
3303 __FUNCTION__, streamId, halStream->stream_type);
3304 break;
3305 }
3306 break;
3307 }
3308 }
3309 if (streamDeleted) {
3310 continue;
3311 }
3312
3313 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003314 if (streamId == inputStreamId) {
3315 streamBuffer.stream = mInputStream->asHalStream();
3316 res = mInputStream->returnInputBuffer(streamBuffer);
3317 if (res != OK) {
3318 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003319 " stream %d: %s (%d)", __FUNCTION__,
3320 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003321 }
3322 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003323 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3324 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003325 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3326 continue;
3327 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003328 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003329 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3330 }
3331 }
3332}
3333
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003334void Camera3Device::insertResultLocked(CaptureResult *result,
3335 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003336 if (result == nullptr) return;
3337
Emilian Peev71c73a22017-03-21 16:35:51 +00003338 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3339 result->mMetadata.getAndLock());
3340 set_camera_metadata_vendor_id(meta, mVendorTagId);
3341 result->mMetadata.unlock(meta);
3342
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003343 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3344 (int32_t*)&frameNumber, 1) != OK) {
3345 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3346 return;
3347 }
3348
3349 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3350 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3351 return;
3352 }
3353
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003354 // Valid result, insert into queue
3355 List<CaptureResult>::iterator queuedResult =
3356 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3357 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3358 ", burstId = %" PRId32, __FUNCTION__,
3359 queuedResult->mResultExtras.requestId,
3360 queuedResult->mResultExtras.frameNumber,
3361 queuedResult->mResultExtras.burstId);
3362
3363 mResultSignal.signal();
3364}
3365
3366
3367void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003368 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003369 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003370 Mutex::Autolock l(mOutputLock);
3371
3372 CaptureResult captureResult;
3373 captureResult.mResultExtras = resultExtras;
3374 captureResult.mMetadata = partialResult;
3375
Shuzhen Wang268a1362018-10-16 16:32:59 -07003376 // Fix up result metadata for monochrome camera.
3377 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3378 if (res != OK) {
3379 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3380 return;
3381 }
3382
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003383 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003384}
3385
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003386
3387void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3388 CaptureResultExtras &resultExtras,
3389 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003390 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003391 bool reprocess,
3392 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003393 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003394 if (pendingMetadata.isEmpty())
3395 return;
3396
3397 Mutex::Autolock l(mOutputLock);
3398
3399 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003400 if (reprocess) {
3401 if (frameNumber < mNextReprocessResultFrameNumber) {
3402 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003403 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003404 frameNumber, mNextReprocessResultFrameNumber);
3405 return;
3406 }
3407 mNextReprocessResultFrameNumber = frameNumber + 1;
3408 } else {
3409 if (frameNumber < mNextResultFrameNumber) {
3410 SET_ERR("Out-of-order capture result metadata submitted! "
3411 "(got frame number %d, expecting %d)",
3412 frameNumber, mNextResultFrameNumber);
3413 return;
3414 }
3415 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003416 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003417
3418 CaptureResult captureResult;
3419 captureResult.mResultExtras = resultExtras;
3420 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003421 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003422
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003423 // Append any previous partials to form a complete result
3424 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3425 captureResult.mMetadata.append(collectedPartialResult);
3426 }
3427
3428 captureResult.mMetadata.sort();
3429
3430 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003431 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3432 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003433 SET_ERR("No timestamp provided by HAL for frame %d!",
3434 frameNumber);
3435 return;
3436 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003437 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3438 camera_metadata_entry timestamp =
3439 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3440 if (timestamp.count == 0) {
3441 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3442 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3443 return;
3444 }
3445 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003446
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003447 // Fix up some result metadata to account for HAL-level distortion correction
3448 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3449 if (res != OK) {
3450 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3451 frameNumber, strerror(res), res);
3452 return;
3453 }
Shuzhen Wang268a1362018-10-16 16:32:59 -07003454 // Fix up result metadata for monochrome camera.
3455 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3456 if (res != OK) {
3457 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3458 return;
3459 }
3460 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3461 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3462 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3463 physicalMetadata.mPhysicalCameraMetadata);
3464 if (res != OK) {
3465 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3466 return;
3467 }
3468 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003469
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003470 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3471 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3472
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003473 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003474}
3475
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003476/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003477 * Camera HAL device callback methods
3478 */
3479
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003480void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003481 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003482
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003483 status_t res;
3484
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003485 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003486 if (result->result == NULL && result->num_output_buffers == 0 &&
3487 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003488 SET_ERR("No result data provided by HAL for frame %d",
3489 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003490 return;
3491 }
Zhijun He204e3292014-07-14 17:09:23 -07003492
Zhijun He204e3292014-07-14 17:09:23 -07003493 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003494 result->result != NULL &&
3495 result->partial_result != 1) {
3496 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3497 " if partial result is not supported",
3498 frameNumber, result->partial_result);
3499 return;
3500 }
3501
3502 bool isPartialResult = false;
3503 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003504 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003505
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003506 // Get shutter timestamp and resultExtras from list of in-flight requests,
3507 // where it was added by the shutter notification for this frame. If the
3508 // shutter timestamp isn't received yet, append the output buffers to the
3509 // in-flight request and they will be returned when the shutter timestamp
3510 // arrives. Update the in-flight status and remove the in-flight entry if
3511 // all result data and shutter timestamp have been received.
3512 nsecs_t shutterTimestamp = 0;
3513
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003514 {
3515 Mutex::Autolock l(mInFlightLock);
3516 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3517 if (idx == NAME_NOT_FOUND) {
3518 SET_ERR("Unknown frame number for capture result: %d",
3519 frameNumber);
3520 return;
3521 }
3522 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003523 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3524 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003525 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003526 __FUNCTION__, request.resultExtras.requestId,
3527 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003528 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003529 // Always update the partial count to the latest one if it's not 0
3530 // (buffers only). When framework aggregates adjacent partial results
3531 // into one, the latest partial count will be used.
3532 if (result->partial_result != 0)
3533 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003534
3535 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003536 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003537 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3538 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3539 " the range of [1, %d] when metadata is included in the result",
3540 frameNumber, result->partial_result, mNumPartialResults);
3541 return;
3542 }
3543 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003544 if (isPartialResult && result->num_physcam_metadata) {
3545 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3546 " physical camera result", frameNumber);
3547 return;
3548 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003549 if (isPartialResult) {
3550 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003551 }
3552
Shuzhen Wang4a472662017-02-26 23:29:04 -08003553 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003554 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003555 sendPartialCaptureResult(result->result, request.resultExtras,
3556 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003557 }
3558 }
3559
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003560 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003561 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003562
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003563 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003564 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003565 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3566 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3567 request.physicalCameraIds.size(), result->num_physcam_metadata);
3568 return;
3569 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003570 if (request.haveResultMetadata) {
3571 SET_ERR("Called multiple times with metadata for frame %d",
3572 frameNumber);
3573 return;
3574 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003575 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3576 String8 physicalId(result->physcam_ids[i]);
3577 std::set<String8>::iterator cameraIdIter =
3578 request.physicalCameraIds.find(physicalId);
3579 if (cameraIdIter != request.physicalCameraIds.end()) {
3580 request.physicalCameraIds.erase(cameraIdIter);
3581 } else {
3582 SET_ERR("Total result for frame %d has already returned for camera %s",
3583 frameNumber, physicalId.c_str());
3584 return;
3585 }
3586 }
Zhijun He204e3292014-07-14 17:09:23 -07003587 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003588 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003589 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003590 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003591 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003592 request.haveResultMetadata = true;
3593 }
3594
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003595 uint32_t numBuffersReturned = result->num_output_buffers;
3596 if (result->input_buffer != NULL) {
3597 if (hasInputBufferInRequest) {
3598 numBuffersReturned += 1;
3599 } else {
3600 ALOGW("%s: Input buffer should be NULL if there is no input"
3601 " buffer sent in the request",
3602 __FUNCTION__);
3603 }
3604 }
3605 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003606 if (request.numBuffersLeft < 0) {
3607 SET_ERR("Too many buffers returned for frame %d",
3608 frameNumber);
3609 return;
3610 }
3611
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003612 camera_metadata_ro_entry_t entry;
3613 res = find_camera_metadata_ro_entry(result->result,
3614 ANDROID_SENSOR_TIMESTAMP, &entry);
3615 if (res == OK && entry.count == 1) {
3616 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003617 }
3618
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003619 // If shutter event isn't received yet, append the output buffers to
3620 // the in-flight request. Otherwise, return the output buffers to
3621 // streams.
3622 if (shutterTimestamp == 0) {
3623 request.pendingOutputBuffers.appendArray(result->output_buffers,
3624 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003625 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003626 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003627 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003628 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3629 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003630 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003631
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003632 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003633 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3634 CameraMetadata physicalMetadata;
3635 physicalMetadata.append(result->physcam_metadata[i]);
3636 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3637 physicalMetadata});
3638 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003639 if (shutterTimestamp == 0) {
3640 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003641 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003642 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003643 CameraMetadata metadata;
3644 metadata = result->result;
3645 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003646 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003647 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003648 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003649 }
3650
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003651 removeInFlightRequestIfReadyLocked(idx);
3652 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003653
Zhijun Hef0d962a2014-06-30 10:24:11 -07003654 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003655 if (hasInputBufferInRequest) {
3656 Camera3Stream *stream =
3657 Camera3Stream::cast(result->input_buffer->stream);
3658 res = stream->returnInputBuffer(*(result->input_buffer));
3659 // Note: stream may be deallocated at this point, if this buffer was the
3660 // last reference to it.
3661 if (res != OK) {
3662 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3663 " its stream:%s (%d)", __FUNCTION__,
3664 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003665 }
3666 } else {
3667 ALOGW("%s: Input buffer should be NULL if there is no input"
3668 " buffer sent in the request, skipping input buffer return.",
3669 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003670 }
3671 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003672}
3673
3674void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003675 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003676 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003677 {
3678 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003679 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003680 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003681
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003682 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003683 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003684 return;
3685 }
3686
3687 switch (msg->type) {
3688 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003689 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003690 break;
3691 }
3692 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003693 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003694 break;
3695 }
3696 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003697 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003698 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003699 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003700}
3701
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003702void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003703 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003704 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003705 // Map camera HAL error codes to ICameraDeviceCallback error codes
3706 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003707 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003708 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003709 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003710 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003711 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003712 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003713 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003714 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003715 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003716 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003717 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003718 };
3719
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003720 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003721 ((msg.error_code >= 0) &&
3722 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3723 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003724 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003725
3726 int streamId = 0;
3727 if (msg.error_stream != NULL) {
3728 Camera3Stream *stream =
3729 Camera3Stream::cast(msg.error_stream);
3730 streamId = stream->getId();
3731 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003732 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3733 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003734 streamId, msg.error_code);
3735
3736 CaptureResultExtras resultExtras;
3737 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003738 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003739 // SET_ERR calls notifyError
3740 SET_ERR("Camera HAL reported serious device error");
3741 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003742 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3743 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3744 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003745 {
3746 Mutex::Autolock l(mInFlightLock);
3747 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3748 if (idx >= 0) {
3749 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3750 r.requestStatus = msg.error_code;
3751 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003752 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3753 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3754 errorCode) {
3755 r.skipResultMetadata = true;
3756 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003757 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3758 errorCode) {
3759 // In case of missing result check whether the buffers
3760 // returned. If they returned, then remove inflight
3761 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003762 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3763 // otherwise we are depending on HAL to send the buffers back after
3764 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003765 removeInFlightRequestIfReadyLocked(idx);
3766 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003767 } else {
3768 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003769 ALOGE("Camera %s: %s: cannot find in-flight request on "
3770 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003771 resultExtras.frameNumber);
3772 }
3773 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003774 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003775 if (listener != NULL) {
3776 listener->notifyError(errorCode, resultExtras);
3777 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003778 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003779 }
3780 break;
3781 default:
3782 // SET_ERR calls notifyError
3783 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3784 break;
3785 }
3786}
3787
3788void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003789 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003790 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003791 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003792
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003793 // Set timestamp for the request in the in-flight tracking
3794 // and get the request ID to send upstream
3795 {
3796 Mutex::Autolock l(mInFlightLock);
3797 idx = mInFlightMap.indexOfKey(msg.frame_number);
3798 if (idx >= 0) {
3799 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003800
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003801 // Verify ordering of shutter notifications
3802 {
3803 Mutex::Autolock l(mOutputLock);
3804 // TODO: need to track errors for tighter bounds on expected frame number.
3805 if (r.hasInputBuffer) {
3806 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3807 SET_ERR("Shutter notification out-of-order. Expected "
3808 "notification for frame %d, got frame %d",
3809 mNextReprocessShutterFrameNumber, msg.frame_number);
3810 return;
3811 }
3812 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3813 } else {
3814 if (msg.frame_number < mNextShutterFrameNumber) {
3815 SET_ERR("Shutter notification out-of-order. Expected "
3816 "notification for frame %d, got frame %d",
3817 mNextShutterFrameNumber, msg.frame_number);
3818 return;
3819 }
3820 mNextShutterFrameNumber = msg.frame_number + 1;
3821 }
3822 }
3823
Shuzhen Wang4a472662017-02-26 23:29:04 -08003824 r.shutterTimestamp = msg.timestamp;
3825 if (r.hasCallback) {
3826 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003827 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003828 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003829 // Call listener, if any
3830 if (listener != NULL) {
3831 listener->notifyShutter(r.resultExtras, msg.timestamp);
3832 }
3833 // send pending result and buffers
3834 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3835 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003836 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003837 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003838 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003839 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003840 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3841 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003842 r.pendingOutputBuffers.clear();
3843
3844 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003845 }
3846 }
3847 if (idx < 0) {
3848 SET_ERR("Shutter notification for non-existent frame number %d",
3849 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003850 }
3851}
3852
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003853CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003854 ALOGV("%s", __FUNCTION__);
3855
Igor Murashkin1e479c02013-09-06 16:55:14 -07003856 CameraMetadata retVal;
3857
3858 if (mRequestThread != NULL) {
3859 retVal = mRequestThread->getLatestRequest();
3860 }
3861
Igor Murashkin1e479c02013-09-06 16:55:14 -07003862 return retVal;
3863}
3864
Jianing Weicb0652e2014-03-12 18:29:36 -07003865
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003866void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3867 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3868 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3869}
3870
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003871/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003872 * HalInterface inner class methods
3873 */
3874
Yifan Hongf79b5542017-04-11 14:44:25 -07003875Camera3Device::HalInterface::HalInterface(
3876 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003877 std::shared_ptr<RequestMetadataQueue> queue,
3878 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003879 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003880 mRequestMetadataQueue(queue),
3881 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003882 // Check with hardware service manager if we can downcast these interfaces
3883 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003884 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3885 if (castResult_3_5.isOk()) {
3886 mHidlSession_3_5 = castResult_3_5;
3887 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003888 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3889 if (castResult_3_4.isOk()) {
3890 mHidlSession_3_4 = castResult_3_4;
3891 }
3892 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3893 if (castResult_3_3.isOk()) {
3894 mHidlSession_3_3 = castResult_3_3;
3895 }
3896}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003897
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003898Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003899
3900Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003901 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003902 mRequestMetadataQueue(other.mRequestMetadataQueue),
3903 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003904
3905bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003906 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003907}
3908
3909void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00003910 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003911 mHidlSession_3_4.clear();
3912 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003913 mHidlSession.clear();
3914}
3915
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003916bool Camera3Device::HalInterface::supportBatchRequest() {
3917 return mHidlSession != nullptr;
3918}
3919
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003920status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3921 camera3_request_template_t templateId,
3922 /*out*/ camera_metadata_t **requestTemplate) {
3923 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3924 if (!valid()) return INVALID_OPERATION;
3925 status_t res = OK;
3926
Emilian Peev31abd0a2017-05-11 18:37:46 +01003927 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003928
3929 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003930 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003931 status = s;
3932 if (status == common::V1_0::Status::OK) {
3933 const camera_metadata *r =
3934 reinterpret_cast<const camera_metadata_t*>(request.data());
3935 size_t expectedSize = request.size();
3936 int ret = validate_camera_metadata_structure(r, &expectedSize);
3937 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3938 *requestTemplate = clone_camera_metadata(r);
3939 if (*requestTemplate == nullptr) {
3940 ALOGE("%s: Unable to clone camera metadata received from HAL",
3941 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003942 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003943 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003944 } else {
3945 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3946 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003947 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003948 }
3949 };
3950 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003951 RequestTemplate id;
3952 switch (templateId) {
3953 case CAMERA3_TEMPLATE_PREVIEW:
3954 id = RequestTemplate::PREVIEW;
3955 break;
3956 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3957 id = RequestTemplate::STILL_CAPTURE;
3958 break;
3959 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3960 id = RequestTemplate::VIDEO_RECORD;
3961 break;
3962 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3963 id = RequestTemplate::VIDEO_SNAPSHOT;
3964 break;
3965 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3966 id = RequestTemplate::ZERO_SHUTTER_LAG;
3967 break;
3968 case CAMERA3_TEMPLATE_MANUAL:
3969 id = RequestTemplate::MANUAL;
3970 break;
3971 default:
3972 // Unknown template ID, or this HAL is too old to support it
3973 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003974 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003975 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003976
Emilian Peev31abd0a2017-05-11 18:37:46 +01003977 if (!err.isOk()) {
3978 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3979 res = DEAD_OBJECT;
3980 } else {
3981 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003982 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003983
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003984 return res;
3985}
3986
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003987status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003988 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003989 ATRACE_NAME("CameraHal::configureStreams");
3990 if (!valid()) return INVALID_OPERATION;
3991 status_t res = OK;
3992
Emilian Peev31abd0a2017-05-11 18:37:46 +01003993 // Convert stream config to HIDL
3994 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003995 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3996 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3997 requestedConfiguration3_2.streams.resize(config->num_streams);
3998 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003999 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004000 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4001 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004002 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004003
Emilian Peev31abd0a2017-05-11 18:37:46 +01004004 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4005 cam3stream->setBufferFreedListener(this);
4006 int streamId = cam3stream->getId();
4007 StreamType streamType;
4008 switch (src->stream_type) {
4009 case CAMERA3_STREAM_OUTPUT:
4010 streamType = StreamType::OUTPUT;
4011 break;
4012 case CAMERA3_STREAM_INPUT:
4013 streamType = StreamType::INPUT;
4014 break;
4015 default:
4016 ALOGE("%s: Stream %d: Unsupported stream type %d",
4017 __FUNCTION__, streamId, config->streams[i]->stream_type);
4018 return BAD_VALUE;
4019 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004020 dst3_2.id = streamId;
4021 dst3_2.streamType = streamType;
4022 dst3_2.width = src->width;
4023 dst3_2.height = src->height;
4024 dst3_2.format = mapToPixelFormat(src->format);
4025 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
4026 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4027 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
4028 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004029 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004030 if (src->physical_camera_id != nullptr) {
4031 dst3_4.physicalCameraId = src->physical_camera_id;
4032 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004033
4034 activeStreams.insert(streamId);
4035 // Create Buffer ID map if necessary
4036 if (mBufferIdMaps.count(streamId) == 0) {
4037 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4038 }
4039 }
4040 // remove BufferIdMap for deleted streams
4041 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4042 int streamId = it->first;
4043 bool active = activeStreams.count(streamId) > 0;
4044 if (!active) {
4045 it = mBufferIdMaps.erase(it);
4046 } else {
4047 ++it;
4048 }
4049 }
4050
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004051 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004052 res = mapToStreamConfigurationMode(
4053 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004054 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004055 if (res != OK) {
4056 return res;
4057 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004058 requestedConfiguration3_2.operationMode = operationMode;
4059 requestedConfiguration3_4.operationMode = operationMode;
4060 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004061 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4062 get_camera_metadata_size(sessionParams));
4063
Emilian Peev31abd0a2017-05-11 18:37:46 +01004064 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004065 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004066 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004067 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004068
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004069 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004070 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4071 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004072 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004073 };
4074
4075 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4076 (hardware::Return<void>& err) -> status_t {
4077 if (!err.isOk()) {
4078 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4079 return DEAD_OBJECT;
4080 }
4081 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4082 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4083 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4084 }
4085 return OK;
4086 };
4087
4088 // See if we have v3.4 or v3.3 HAL
4089 if (mHidlSession_3_5 != nullptr) {
4090 ALOGV("%s: v3.5 device found", __FUNCTION__);
4091 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4092 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4093 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4094 auto err = mHidlSession_3_5->configureStreams_3_5(
4095 requestedConfiguration3_5, configStream34Cb);
4096 res = postprocConfigStream34(err);
4097 if (res != OK) {
4098 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004099 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004100 } else if (mHidlSession_3_4 != nullptr) {
4101 // We do; use v3.4 for the call
4102 ALOGV("%s: v3.4 device found", __FUNCTION__);
4103 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
4104 auto err = mHidlSession_3_4->configureStreams_3_4(
4105 requestedConfiguration3_4, configStream34Cb);
4106 res = postprocConfigStream34(err);
4107 if (res != OK) {
4108 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004109 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004110 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004111 // We do; use v3.3 for the call
4112 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004113 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004114 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004115 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004116 finalConfiguration = halConfiguration;
4117 status = s;
4118 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004119 if (!err.isOk()) {
4120 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4121 return DEAD_OBJECT;
4122 }
4123 } else {
4124 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4125 ALOGV("%s: v3.2 device found", __FUNCTION__);
4126 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004127 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004128 [&status, &finalConfiguration_3_2]
4129 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4130 finalConfiguration_3_2 = halConfiguration;
4131 status = s;
4132 });
4133 if (!err.isOk()) {
4134 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4135 return DEAD_OBJECT;
4136 }
4137 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4138 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4139 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4140 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004141 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004142 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004143 }
4144
4145 if (status != common::V1_0::Status::OK ) {
4146 return CameraProviderManager::mapToStatusT(status);
4147 }
4148
4149 // And convert output stream configuration from HIDL
4150
4151 for (size_t i = 0; i < config->num_streams; i++) {
4152 camera3_stream_t *dst = config->streams[i];
4153 int streamId = Camera3Stream::cast(dst)->getId();
4154
4155 // Start scan at i, with the assumption that the stream order matches
4156 size_t realIdx = i;
4157 bool found = false;
4158 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004159 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004160 found = true;
4161 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004162 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004163 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4164 }
4165 if (!found) {
4166 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4167 __FUNCTION__, streamId);
4168 return INVALID_OPERATION;
4169 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004170 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004171
Emilian Peev710c1422017-08-30 11:19:38 +01004172 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4173 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004174 dstStream->setDataSpaceOverride(false);
4175 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4176 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4177
Emilian Peev31abd0a2017-05-11 18:37:46 +01004178 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4179 if (dst->format != overrideFormat) {
4180 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4181 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004182 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004183 if (dst->data_space != overrideDataSpace) {
4184 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4185 streamId, dst->format);
4186 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004187 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004188 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004189 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4190
Emilian Peev31abd0a2017-05-11 18:37:46 +01004191 // Override allowed with IMPLEMENTATION_DEFINED
4192 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004193 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004194 }
4195
Emilian Peev31abd0a2017-05-11 18:37:46 +01004196 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004197 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004198 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004199 __FUNCTION__, streamId);
4200 return INVALID_OPERATION;
4201 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004202 dstStream->setUsage(
4203 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004204 } else {
4205 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004206 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004207 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4208 __FUNCTION__, streamId);
4209 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004210 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004211 dstStream->setUsage(
4212 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004213 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004214 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004215 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004216
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004217 return res;
4218}
4219
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004220status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004221 /*out*/device::V3_2::CaptureRequest* captureRequest,
4222 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004223 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004224 if (captureRequest == nullptr || handlesCreated == nullptr) {
4225 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4226 __FUNCTION__, captureRequest, handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004227 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004228 }
4229
4230 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004231
4232 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004233
4234 {
4235 std::lock_guard<std::mutex> lock(mInflightLock);
4236 if (request->input_buffer != nullptr) {
4237 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4238 buffer_handle_t buf = *(request->input_buffer->buffer);
4239 auto pair = getBufferId(buf, streamId);
4240 bool isNewBuffer = pair.first;
4241 uint64_t bufferId = pair.second;
4242 captureRequest->inputBuffer.streamId = streamId;
4243 captureRequest->inputBuffer.bufferId = bufferId;
4244 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4245 captureRequest->inputBuffer.status = BufferStatus::OK;
4246 native_handle_t *acquireFence = nullptr;
4247 if (request->input_buffer->acquire_fence != -1) {
4248 acquireFence = native_handle_create(1,0);
4249 acquireFence->data[0] = request->input_buffer->acquire_fence;
4250 handlesCreated->push_back(acquireFence);
4251 }
4252 captureRequest->inputBuffer.acquireFence = acquireFence;
4253 captureRequest->inputBuffer.releaseFence = nullptr;
4254
4255 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4256 request->input_buffer->buffer,
4257 request->input_buffer->acquire_fence);
4258 } else {
4259 captureRequest->inputBuffer.streamId = -1;
4260 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4261 }
4262
4263 captureRequest->outputBuffers.resize(request->num_output_buffers);
4264 for (size_t i = 0; i < request->num_output_buffers; i++) {
4265 const camera3_stream_buffer_t *src = request->output_buffers + i;
4266 StreamBuffer &dst = captureRequest->outputBuffers[i];
4267 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004268 if (src->buffer != nullptr) {
4269 buffer_handle_t buf = *(src->buffer);
4270 auto pair = getBufferId(buf, streamId);
4271 bool isNewBuffer = pair.first;
4272 dst.bufferId = pair.second;
4273 dst.buffer = isNewBuffer ? buf : nullptr;
4274 native_handle_t *acquireFence = nullptr;
4275 if (src->acquire_fence != -1) {
4276 acquireFence = native_handle_create(1,0);
4277 acquireFence->data[0] = src->acquire_fence;
4278 handlesCreated->push_back(acquireFence);
4279 }
4280 dst.acquireFence = acquireFence;
4281 } else if (mUseHalBufManager) {
4282 // HAL buffer management path
4283 dst.bufferId = BUFFER_ID_NO_BUFFER;
4284 dst.buffer = nullptr;
4285 dst.acquireFence = nullptr;
4286 } else {
4287 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4288 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004289 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004290 dst.streamId = streamId;
4291 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004292 dst.releaseFence = nullptr;
4293
4294 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4295 src->buffer, src->acquire_fence);
4296 }
4297 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004298 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004299}
4300
4301status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4302 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4303 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4304 if (!valid()) return INVALID_OPERATION;
4305
Emilian Peevaebbe412018-01-15 13:53:24 +00004306 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4307 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4308 if (castResult_3_4.isOk()) {
4309 hidlSession_3_4 = castResult_3_4;
4310 }
4311
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004312 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004313 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004314 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004315 if (hidlSession_3_4 != nullptr) {
4316 captureRequests_3_4.resize(batchSize);
4317 } else {
4318 captureRequests.resize(batchSize);
4319 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004320 std::vector<native_handle_t*> handlesCreated;
4321
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004322 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004323 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004324 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004325 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Emilian Peevaebbe412018-01-15 13:53:24 +00004326 /*out*/&handlesCreated);
4327 } else {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004328 res = wrapAsHidlRequest(requests[i],
4329 /*out*/&captureRequests[i], /*out*/&handlesCreated);
4330 }
4331 if (res != OK) {
4332 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004333 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004334 }
4335
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004336 std::vector<device::V3_2::BufferCache> cachesToRemove;
4337 {
4338 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4339 for (auto& pair : mFreedBuffers) {
4340 // The stream might have been removed since onBufferFreed
4341 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4342 cachesToRemove.push_back({pair.first, pair.second});
4343 }
4344 }
4345 mFreedBuffers.clear();
4346 }
4347
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004348 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4349 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004350
4351 // Write metadata to FMQ.
4352 for (size_t i = 0; i < batchSize; i++) {
4353 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004354 device::V3_2::CaptureRequest* captureRequest;
4355 if (hidlSession_3_4 != nullptr) {
4356 captureRequest = &captureRequests_3_4[i].v3_2;
4357 } else {
4358 captureRequest = &captureRequests[i];
4359 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004360
4361 if (request->settings != nullptr) {
4362 size_t settingsSize = get_camera_metadata_size(request->settings);
4363 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4364 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4365 captureRequest->settings.resize(0);
4366 captureRequest->fmqSettingsSize = settingsSize;
4367 } else {
4368 if (mRequestMetadataQueue != nullptr) {
4369 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4370 }
4371 captureRequest->settings.setToExternal(
4372 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4373 get_camera_metadata_size(request->settings));
4374 captureRequest->fmqSettingsSize = 0u;
4375 }
4376 } else {
4377 // A null request settings maps to a size-0 CameraMetadata
4378 captureRequest->settings.resize(0);
4379 captureRequest->fmqSettingsSize = 0u;
4380 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004381
4382 if (hidlSession_3_4 != nullptr) {
4383 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4384 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004385 if (request->physcam_settings != nullptr) {
4386 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4387 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4388 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4389 settingsSize)) {
4390 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4391 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4392 settingsSize;
4393 } else {
4394 if (mRequestMetadataQueue != nullptr) {
4395 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4396 }
4397 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4398 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4399 request->physcam_settings[j])),
4400 get_camera_metadata_size(request->physcam_settings[j]));
4401 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004402 }
Emilian Peev00420d22018-02-05 21:33:13 +00004403 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004404 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004405 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004406 }
4407 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4408 request->physcam_id[j];
4409 }
4410 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004411 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004412
4413 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004414 auto resultCallback =
4415 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4416 status = s;
4417 *numRequestProcessed = n;
4418 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004419 if (hidlSession_3_4 != nullptr) {
4420 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004421 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004422 } else {
4423 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004424 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004425 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004426 if (!err.isOk()) {
4427 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4428 return DEAD_OBJECT;
4429 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004430 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4431 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4432 __FUNCTION__, *numRequestProcessed, batchSize);
4433 status = common::V1_0::Status::INTERNAL_ERROR;
4434 }
4435
4436 for (auto& handle : handlesCreated) {
4437 native_handle_delete(handle);
4438 }
4439 return CameraProviderManager::mapToStatusT(status);
4440}
4441
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004442status_t Camera3Device::HalInterface::processCaptureRequest(
4443 camera3_capture_request_t *request) {
4444 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004445 if (!valid()) return INVALID_OPERATION;
4446 status_t res = OK;
4447
Emilian Peev31abd0a2017-05-11 18:37:46 +01004448 uint32_t numRequestProcessed = 0;
4449 std::vector<camera3_capture_request_t*> requests(1);
4450 requests[0] = request;
4451 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4452
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004453 return res;
4454}
4455
4456status_t Camera3Device::HalInterface::flush() {
4457 ATRACE_NAME("CameraHal::flush");
4458 if (!valid()) return INVALID_OPERATION;
4459 status_t res = OK;
4460
Emilian Peev31abd0a2017-05-11 18:37:46 +01004461 auto err = mHidlSession->flush();
4462 if (!err.isOk()) {
4463 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4464 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004465 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004466 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004467 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004468
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004469 return res;
4470}
4471
Emilian Peev31abd0a2017-05-11 18:37:46 +01004472status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004473 ATRACE_NAME("CameraHal::dump");
4474 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004475
Emilian Peev31abd0a2017-05-11 18:37:46 +01004476 // Handled by CameraProviderManager::dump
4477
4478 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004479}
4480
4481status_t Camera3Device::HalInterface::close() {
4482 ATRACE_NAME("CameraHal::close()");
4483 if (!valid()) return INVALID_OPERATION;
4484 status_t res = OK;
4485
Emilian Peev31abd0a2017-05-11 18:37:46 +01004486 auto err = mHidlSession->close();
4487 // Interface will be dead shortly anyway, so don't log errors
4488 if (!err.isOk()) {
4489 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004490 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004491
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004492 return res;
4493}
4494
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004495void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4496 ATRACE_NAME("CameraHal::signalPipelineDrain");
4497 if (!valid() || mHidlSession_3_5 == nullptr) {
4498 ALOGE("%s called on invalid camera!", __FUNCTION__);
4499 return;
4500 }
4501
4502 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter);
4503 if (!err.isOk()) {
4504 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4505 return;
4506 }
4507}
4508
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004509void Camera3Device::HalInterface::getInflightBufferKeys(
4510 std::vector<std::pair<int32_t, int32_t>>* out) {
4511 std::lock_guard<std::mutex> lock(mInflightLock);
4512 out->clear();
4513 out->reserve(mInflightBufferMap.size());
4514 for (auto& pair : mInflightBufferMap) {
4515 uint64_t key = pair.first;
4516 int32_t streamId = key & 0xFFFFFFFF;
4517 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4518 out->push_back(std::make_pair(frameNumber, streamId));
4519 }
4520 return;
4521}
4522
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004523status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004524 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004525 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004526 auto pair = std::make_pair(buffer, acquireFence);
4527 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004528 return OK;
4529}
4530
4531status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004532 int32_t frameNumber, int32_t streamId,
4533 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004534 std::lock_guard<std::mutex> lock(mInflightLock);
4535
4536 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4537 auto it = mInflightBufferMap.find(key);
4538 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004539 auto pair = it->second;
4540 *buffer = pair.first;
4541 int acquireFence = pair.second;
4542 if (acquireFence > 0) {
4543 ::close(acquireFence);
4544 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004545 mInflightBufferMap.erase(it);
4546 return OK;
4547}
4548
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004549status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
4550 uint64_t bufferId, buffer_handle_t* buf) {
4551 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4552 auto pair = mRequestedBuffers.insert({bufferId, buf});
4553 if (!pair.second) {
4554 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4555 __FUNCTION__, bufferId);
4556 return BAD_VALUE;
4557 }
4558 return OK;
4559}
4560
4561// Find and pop a buffer_handle_t based on bufferId
4562status_t Camera3Device::HalInterface::popInflightRequestBuffer(
4563 uint64_t bufferId, /*out*/ buffer_handle_t **buffer) {
4564 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4565 auto it = mRequestedBuffers.find(bufferId);
4566 if (it == mRequestedBuffers.end()) {
4567 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4568 __FUNCTION__, bufferId);
4569 return BAD_VALUE;
4570 }
4571 *buffer = it->second;
4572 mRequestedBuffers.erase(it);
4573 return OK;
4574}
4575
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004576std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4577 const buffer_handle_t& buf, int streamId) {
4578 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4579
4580 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4581 auto it = bIdMap.find(buf);
4582 if (it == bIdMap.end()) {
4583 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004584 ALOGV("stream %d now have %zu buffer caches, buf %p",
4585 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004586 return std::make_pair(true, mNextBufferId - 1);
4587 } else {
4588 return std::make_pair(false, it->second);
4589 }
4590}
4591
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004592void Camera3Device::HalInterface::onBufferFreed(
4593 int streamId, const native_handle_t* handle) {
4594 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4595 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4596 auto mapIt = mBufferIdMaps.find(streamId);
4597 if (mapIt == mBufferIdMaps.end()) {
4598 // streamId might be from a deleted stream here
4599 ALOGI("%s: stream %d has been removed",
4600 __FUNCTION__, streamId);
4601 return;
4602 }
4603 BufferIdMap& bIdMap = mapIt->second;
4604 auto it = bIdMap.find(handle);
4605 if (it == bIdMap.end()) {
4606 ALOGW("%s: cannot find buffer %p in stream %d",
4607 __FUNCTION__, handle, streamId);
4608 return;
4609 } else {
4610 bufferId = it->second;
4611 bIdMap.erase(it);
4612 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4613 __FUNCTION__, streamId, bIdMap.size(), handle);
4614 }
4615 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4616}
4617
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004618/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004619 * RequestThread inner class methods
4620 */
4621
4622Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004623 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004624 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4625 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004626 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004627 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004628 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004629 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004630 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004631 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004632 mReconfigured(false),
4633 mDoPause(false),
4634 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004635 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004636 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004637 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004638 mCurrentAfTriggerId(0),
4639 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004640 mRepeatingLastFrameNumber(
4641 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004642 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004643 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004644 mRequestLatency(kRequestLatencyBinSize),
4645 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004646 mLatestSessionParams(sessionParamKeys.size()),
4647 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004648 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004649}
4650
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004651Camera3Device::RequestThread::~RequestThread() {}
4652
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004653void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004654 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004655 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004656 Mutex::Autolock l(mRequestLock);
4657 mListener = listener;
4658}
4659
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004660void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4661 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004662 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004663 Mutex::Autolock l(mRequestLock);
4664 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004665 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004666 // Prepare video stream for high speed recording.
4667 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004668 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004669}
4670
Jianing Wei90e59c92014-03-12 18:29:36 -07004671status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004672 List<sp<CaptureRequest> > &requests,
4673 /*out*/
4674 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004675 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004676 Mutex::Autolock l(mRequestLock);
4677 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4678 ++it) {
4679 mRequestQueue.push_back(*it);
4680 }
4681
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004682 if (lastFrameNumber != NULL) {
4683 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4684 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4685 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4686 *lastFrameNumber);
4687 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004688
Jianing Wei90e59c92014-03-12 18:29:36 -07004689 unpauseForNewRequests();
4690
4691 return OK;
4692}
4693
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004694
4695status_t Camera3Device::RequestThread::queueTrigger(
4696 RequestTrigger trigger[],
4697 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004698 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004699 Mutex::Autolock l(mTriggerMutex);
4700 status_t ret;
4701
4702 for (size_t i = 0; i < count; ++i) {
4703 ret = queueTriggerLocked(trigger[i]);
4704
4705 if (ret != OK) {
4706 return ret;
4707 }
4708 }
4709
4710 return OK;
4711}
4712
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004713const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4714 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004715 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004716 if (d != nullptr) return d->mId;
4717 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004718}
4719
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004720status_t Camera3Device::RequestThread::queueTriggerLocked(
4721 RequestTrigger trigger) {
4722
4723 uint32_t tag = trigger.metadataTag;
4724 ssize_t index = mTriggerMap.indexOfKey(tag);
4725
4726 switch (trigger.getTagType()) {
4727 case TYPE_BYTE:
4728 // fall-through
4729 case TYPE_INT32:
4730 break;
4731 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004732 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4733 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004734 return INVALID_OPERATION;
4735 }
4736
4737 /**
4738 * Collect only the latest trigger, since we only have 1 field
4739 * in the request settings per trigger tag, and can't send more than 1
4740 * trigger per request.
4741 */
4742 if (index != NAME_NOT_FOUND) {
4743 mTriggerMap.editValueAt(index) = trigger;
4744 } else {
4745 mTriggerMap.add(tag, trigger);
4746 }
4747
4748 return OK;
4749}
4750
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004751status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004752 const RequestList &requests,
4753 /*out*/
4754 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004755 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004756 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004757 if (lastFrameNumber != NULL) {
4758 *lastFrameNumber = mRepeatingLastFrameNumber;
4759 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004760 mRepeatingRequests.clear();
4761 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4762 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004763
4764 unpauseForNewRequests();
4765
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004766 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004767 return OK;
4768}
4769
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004770bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004771 if (mRepeatingRequests.empty()) {
4772 return false;
4773 }
4774 int32_t requestId = requestIn->mResultExtras.requestId;
4775 const RequestList &repeatRequests = mRepeatingRequests;
4776 // All repeating requests are guaranteed to have same id so only check first quest
4777 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4778 return (firstRequest->mResultExtras.requestId == requestId);
4779}
4780
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004781status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004782 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004783 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004784 return clearRepeatingRequestsLocked(lastFrameNumber);
4785
4786}
4787
4788status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004789 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004790 if (lastFrameNumber != NULL) {
4791 *lastFrameNumber = mRepeatingLastFrameNumber;
4792 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004793 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004794 return OK;
4795}
4796
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004797status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004798 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004799 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004800 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004801 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004802
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004803 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004804
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004805 // Send errors for all requests pending in the request queue, including
4806 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004807 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004808 if (listener != NULL) {
4809 for (RequestList::iterator it = mRequestQueue.begin();
4810 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004811 // Abort the input buffers for reprocess requests.
4812 if ((*it)->mInputStream != NULL) {
4813 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004814 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4815 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004816 if (res != OK) {
4817 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4818 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4819 } else {
4820 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4821 if (res != OK) {
4822 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4823 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4824 }
4825 }
4826 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004827 // Set the frame number this request would have had, if it
4828 // had been submitted; this frame number will not be reused.
4829 // The requestId and burstId fields were set when the request was
4830 // submitted originally (in convertMetadataListToRequestListLocked)
4831 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004832 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004833 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004834 }
4835 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004836 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004837
4838 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004839 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004840 if (lastFrameNumber != NULL) {
4841 *lastFrameNumber = mRepeatingLastFrameNumber;
4842 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004843 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004844 return OK;
4845}
4846
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004847status_t Camera3Device::RequestThread::flush() {
4848 ATRACE_CALL();
4849 Mutex::Autolock l(mFlushLock);
4850
Emilian Peev08dd2452017-04-06 16:55:14 +01004851 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004852}
4853
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004854void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004855 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004856 Mutex::Autolock l(mPauseLock);
4857 mDoPause = paused;
4858 mDoPauseSignal.signal();
4859}
4860
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004861status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4862 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004863 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004864 Mutex::Autolock l(mLatestRequestMutex);
4865 status_t res;
4866 while (mLatestRequestId != requestId) {
4867 nsecs_t startTime = systemTime();
4868
4869 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4870 if (res != OK) return res;
4871
4872 timeout -= (systemTime() - startTime);
4873 }
4874
4875 return OK;
4876}
4877
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004878void Camera3Device::RequestThread::requestExit() {
4879 // Call parent to set up shutdown
4880 Thread::requestExit();
4881 // The exit from any possible waits
4882 mDoPauseSignal.signal();
4883 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004884
4885 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4886 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004887}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004888
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004889void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004890 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004891 bool surfaceAbandoned = false;
4892 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004893 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004894 {
4895 Mutex::Autolock l(mRequestLock);
4896 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4897 // repeating requests.
4898 for (const auto& request : mRepeatingRequests) {
4899 for (const auto& s : request->mOutputStreams) {
4900 if (s->isAbandoned()) {
4901 surfaceAbandoned = true;
4902 clearRepeatingRequestsLocked(&lastFrameNumber);
4903 break;
4904 }
4905 }
4906 if (surfaceAbandoned) {
4907 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004908 }
4909 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004910 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004911 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004912
4913 if (listener != NULL && surfaceAbandoned) {
4914 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004915 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004916}
4917
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004918bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004919 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004920 status_t res;
4921 size_t batchSize = mNextRequests.size();
4922 std::vector<camera3_capture_request_t*> requests(batchSize);
4923 uint32_t numRequestProcessed = 0;
4924 for (size_t i = 0; i < batchSize; i++) {
4925 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004926 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004927 }
4928
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004929 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4930
4931 bool triggerRemoveFailed = false;
4932 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4933 for (size_t i = 0; i < numRequestProcessed; i++) {
4934 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4935 nextRequest.submitted = true;
4936
4937
4938 // Update the latest request sent to HAL
4939 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4940 Mutex::Autolock al(mLatestRequestMutex);
4941
4942 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4943 mLatestRequest.acquire(cloned);
4944
4945 sp<Camera3Device> parent = mParent.promote();
4946 if (parent != NULL) {
4947 parent->monitorMetadata(TagMonitor::REQUEST,
4948 nextRequest.halRequest.frame_number,
4949 0, mLatestRequest);
4950 }
4951 }
4952
4953 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004954 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4955 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004956 }
4957
Emilian Peevaebbe412018-01-15 13:53:24 +00004958 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4959
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004960 if (!triggerRemoveFailed) {
4961 // Remove any previously queued triggers (after unlock)
4962 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4963 if (removeTriggerRes != OK) {
4964 triggerRemoveFailed = true;
4965 triggerFailedRequest = nextRequest;
4966 }
4967 }
4968 }
4969
4970 if (triggerRemoveFailed) {
4971 SET_ERR("RequestThread: Unable to remove triggers "
4972 "(capture request %d, HAL device: %s (%d)",
4973 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4974 cleanUpFailedRequests(/*sendRequestError*/ false);
4975 return false;
4976 }
4977
4978 if (res != OK) {
4979 // Should only get a failure here for malformed requests or device-level
4980 // errors, so consider all errors fatal. Bad metadata failures should
4981 // come through notify.
4982 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4983 mNextRequests[numRequestProcessed].halRequest.frame_number,
4984 strerror(-res), res);
4985 cleanUpFailedRequests(/*sendRequestError*/ false);
4986 return false;
4987 }
4988 return true;
4989}
4990
4991bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4992 status_t res;
4993
4994 for (auto& nextRequest : mNextRequests) {
4995 // Submit request and block until ready for next one
4996 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4997 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4998
4999 if (res != OK) {
5000 // Should only get a failure here for malformed requests or device-level
5001 // errors, so consider all errors fatal. Bad metadata failures should
5002 // come through notify.
5003 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
5004 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
5005 res);
5006 cleanUpFailedRequests(/*sendRequestError*/ false);
5007 return false;
5008 }
5009
5010 // Mark that the request has be submitted successfully.
5011 nextRequest.submitted = true;
5012
5013 // Update the latest request sent to HAL
5014 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5015 Mutex::Autolock al(mLatestRequestMutex);
5016
5017 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5018 mLatestRequest.acquire(cloned);
5019
5020 sp<Camera3Device> parent = mParent.promote();
5021 if (parent != NULL) {
5022 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
5023 0, mLatestRequest);
5024 }
5025 }
5026
5027 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005028 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5029 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005030 }
5031
Emilian Peevaebbe412018-01-15 13:53:24 +00005032 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5033
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005034 // Remove any previously queued triggers (after unlock)
5035 res = removeTriggers(mPrevRequest);
5036 if (res != OK) {
5037 SET_ERR("RequestThread: Unable to remove triggers "
5038 "(capture request %d, HAL device: %s (%d)",
5039 nextRequest.halRequest.frame_number, strerror(-res), res);
5040 cleanUpFailedRequests(/*sendRequestError*/ false);
5041 return false;
5042 }
5043 }
5044 return true;
5045}
5046
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005047nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5048 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5049 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5050 find_camera_metadata_ro_entry(request,
5051 ANDROID_CONTROL_AE_MODE,
5052 &e);
5053 if (e.count == 0) return maxExpectedDuration;
5054
5055 switch (e.data.u8[0]) {
5056 case ANDROID_CONTROL_AE_MODE_OFF:
5057 find_camera_metadata_ro_entry(request,
5058 ANDROID_SENSOR_EXPOSURE_TIME,
5059 &e);
5060 if (e.count > 0) {
5061 maxExpectedDuration = e.data.i64[0];
5062 }
5063 find_camera_metadata_ro_entry(request,
5064 ANDROID_SENSOR_FRAME_DURATION,
5065 &e);
5066 if (e.count > 0) {
5067 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5068 }
5069 break;
5070 default:
5071 find_camera_metadata_ro_entry(request,
5072 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5073 &e);
5074 if (e.count > 1) {
5075 maxExpectedDuration = 1e9 / e.data.u8[0];
5076 }
5077 break;
5078 }
5079
5080 return maxExpectedDuration;
5081}
5082
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005083bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5084 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5085 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5086 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5087 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5088 return true;
5089 }
5090
5091 return false;
5092}
5093
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005094bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5095 ATRACE_CALL();
5096 bool updatesDetected = false;
5097
5098 for (auto tag : mSessionParamKeys) {
5099 camera_metadata_ro_entry entry = settings.find(tag);
5100 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
5101
5102 if (entry.count > 0) {
5103 bool isDifferent = false;
5104 if (lastEntry.count > 0) {
5105 // Have a last value, compare to see if changed
5106 if (lastEntry.type == entry.type &&
5107 lastEntry.count == entry.count) {
5108 // Same type and count, compare values
5109 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5110 size_t entryBytes = bytesPerValue * lastEntry.count;
5111 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5112 if (cmp != 0) {
5113 isDifferent = true;
5114 }
5115 } else {
5116 // Count or type has changed
5117 isDifferent = true;
5118 }
5119 } else {
5120 // No last entry, so always consider to be different
5121 isDifferent = true;
5122 }
5123
5124 if (isDifferent) {
5125 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005126 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5127 updatesDetected = true;
5128 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005129 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005130 }
5131 } else if (lastEntry.count > 0) {
5132 // Value has been removed
5133 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
5134 mLatestSessionParams.erase(tag);
5135 updatesDetected = true;
5136 }
5137 }
5138
5139 return updatesDetected;
5140}
5141
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005142bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005143 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005144 status_t res;
5145
5146 // Handle paused state.
5147 if (waitIfPaused()) {
5148 return true;
5149 }
5150
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005151 // Wait for the next batch of requests.
5152 waitForNextRequestBatch();
5153 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005154 return true;
5155 }
5156
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005157 // Get the latest request ID, if any
5158 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005159 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005160 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005161 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005162 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005163 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005164 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5165 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005166 }
5167
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005168 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5169 // or a single request from streaming or burst. In either case the first element
5170 // should contain the latest camera settings that we need to check for any session
5171 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005172 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005173 res = OK;
5174
5175 //Input stream buffers are already acquired at this point so an input stream
5176 //will not be able to move to idle state unless we force it.
5177 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5178 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5179 if (res != OK) {
5180 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5181 cleanUpFailedRequests(/*sendRequestError*/ false);
5182 return false;
5183 }
5184 }
5185
5186 if (res == OK) {
5187 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5188 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005189 sp<Camera3Device> parent = mParent.promote();
5190 if (parent != nullptr) {
5191 parent->pauseStateNotify(true);
5192 }
5193
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005194 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5195
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005196 if (parent != nullptr) {
5197 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5198 }
5199
5200 statusTracker->markComponentActive(mStatusId);
5201 setPaused(false);
5202 }
5203
5204 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5205 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5206 if (res != OK) {
5207 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5208 cleanUpFailedRequests(/*sendRequestError*/ false);
5209 return false;
5210 }
5211 }
5212 }
5213 }
5214
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005215 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005216 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005217 if (res == TIMED_OUT) {
5218 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005219 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005220 // Check if any stream is abandoned.
5221 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005222 return true;
5223 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005224 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005225 return false;
5226 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005227
Zhijun Hecc27e112013-10-03 16:12:43 -07005228 // Inform waitUntilRequestProcessed thread of a new request ID
5229 {
5230 Mutex::Autolock al(mLatestRequestMutex);
5231
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005232 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005233 mLatestRequestSignal.signal();
5234 }
5235
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005236 // Submit a batch of requests to HAL.
5237 // Use flush lock only when submitting multilple requests in a batch.
5238 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5239 // which may take a long time to finish so synchronizing flush() and
5240 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5241 // For now, only synchronize for high speed recording and we should figure something out for
5242 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005243 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005244
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005245 if (useFlushLock) {
5246 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005247 }
5248
Zhijun Hef0645c12016-08-02 00:58:11 -07005249 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005250 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005251
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005252 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005253 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005254 if (mInterface->supportBatchRequest()) {
5255 submitRequestSuccess = sendRequestsBatch();
5256 } else {
5257 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005258 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005259 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5260 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005261
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005262 if (submitRequestSuccess) {
5263 sp<Camera3Device> parent = mParent.promote();
5264 if (parent != nullptr) {
5265 parent->mRequestBufferSM.onRequestSubmitted();
5266 }
5267 }
5268
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005269 if (useFlushLock) {
5270 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005271 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005272
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005273 // Unset as current request
5274 {
5275 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005276 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005277 }
5278
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005279 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005280}
5281
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005282status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005283 ATRACE_CALL();
5284
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005285 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005286 for (size_t i = 0; i < mNextRequests.size(); i++) {
5287 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005288 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5289 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5290 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5291
5292 // Prepare a request to HAL
5293 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5294
5295 // Insert any queued triggers (before metadata is locked)
5296 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005297 if (res < 0) {
5298 SET_ERR("RequestThread: Unable to insert triggers "
5299 "(capture request %d, HAL device: %s (%d)",
5300 halRequest->frame_number, strerror(-res), res);
5301 return INVALID_OPERATION;
5302 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005303
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005304 int triggerCount = res;
5305 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5306 mPrevTriggers = triggerCount;
5307
5308 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005309 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5310 // Request settings are all the same within one batch, so only treat the first
5311 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005312 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005313 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005314 /**
5315 * HAL workaround:
5316 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5317 */
5318 res = addDummyTriggerIds(captureRequest);
5319 if (res != OK) {
5320 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5321 "(capture request %d, HAL device: %s (%d)",
5322 halRequest->frame_number, strerror(-res), res);
5323 return INVALID_OPERATION;
5324 }
5325
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005326 {
5327 // Correct metadata regions for distortion correction if enabled
5328 sp<Camera3Device> parent = mParent.promote();
5329 if (parent != nullptr) {
5330 res = parent->mDistortionMapper.correctCaptureRequest(
5331 &(captureRequest->mSettingsList.begin()->metadata));
5332 if (res != OK) {
5333 SET_ERR("RequestThread: Unable to correct capture requests "
5334 "for lens distortion for request %d: %s (%d)",
5335 halRequest->frame_number, strerror(-res), res);
5336 return INVALID_OPERATION;
5337 }
5338 }
5339 }
5340
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005341 /**
5342 * The request should be presorted so accesses in HAL
5343 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5344 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005345 captureRequest->mSettingsList.begin()->metadata.sort();
5346 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005347 mPrevRequest = captureRequest;
5348 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5349
5350 IF_ALOGV() {
5351 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5352 find_camera_metadata_ro_entry(
5353 halRequest->settings,
5354 ANDROID_CONTROL_AF_TRIGGER,
5355 &e
5356 );
5357 if (e.count > 0) {
5358 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5359 __FUNCTION__,
5360 halRequest->frame_number,
5361 e.data.u8[0]);
5362 }
5363 }
5364 } else {
5365 // leave request.settings NULL to indicate 'reuse latest given'
5366 ALOGVV("%s: Request settings are REUSED",
5367 __FUNCTION__);
5368 }
5369
Emilian Peevaebbe412018-01-15 13:53:24 +00005370 if (captureRequest->mSettingsList.size() > 1) {
5371 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5372 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005373 if (newRequest) {
5374 halRequest->physcam_settings =
5375 new const camera_metadata* [halRequest->num_physcam_settings];
5376 } else {
5377 halRequest->physcam_settings = nullptr;
5378 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005379 auto it = ++captureRequest->mSettingsList.begin();
5380 size_t i = 0;
5381 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5382 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005383 if (newRequest) {
5384 it->metadata.sort();
5385 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5386 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005387 }
5388 }
5389
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005390 uint32_t totalNumBuffers = 0;
5391
5392 // Fill in buffers
5393 if (captureRequest->mInputStream != NULL) {
5394 halRequest->input_buffer = &captureRequest->mInputBuffer;
5395 totalNumBuffers += 1;
5396 } else {
5397 halRequest->input_buffer = NULL;
5398 }
5399
5400 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5401 captureRequest->mOutputStreams.size());
5402 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005403 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005404
5405 sp<Camera3Device> parent = mParent.promote();
5406 if (parent == NULL) {
5407 // Should not happen, and nowhere to send errors to, so just log it
5408 CLOGE("RequestThread: Parent is gone");
5409 return INVALID_OPERATION;
5410 }
5411 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5412
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005413 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005414 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005415 sp<Camera3OutputStreamInterface> outputStream =
5416 captureRequest->mOutputStreams.editItemAt(j);
5417 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005418
5419 // Prepare video buffers for high speed recording on the first video request.
5420 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5421 // Only try to prepare video stream on the first video request.
5422 mPrepareVideoStream = false;
5423
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005424 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5425 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005426 while (res == NOT_ENOUGH_DATA) {
5427 res = outputStream->prepareNextBuffer();
5428 }
5429 if (res != OK) {
5430 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5431 __FUNCTION__, strerror(-res), res);
5432 outputStream->cancelPrepare();
5433 }
5434 }
5435
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005436 std::vector<size_t> uniqueSurfaceIds;
5437 res = outputStream->getUniqueSurfaceIds(
5438 captureRequest->mOutputSurfaces[streamId],
5439 &uniqueSurfaceIds);
5440 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5441 if (res != OK && res != INVALID_OPERATION) {
5442 ALOGE("%s: failed to query stream %d unique surface IDs",
5443 __FUNCTION__, streamId);
5444 return res;
5445 }
5446 if (res == OK) {
5447 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5448 }
5449
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005450 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005451 if (outputStream->isAbandoned()) {
5452 ALOGE("%s: stream %d is abandoned.", __FUNCTION__, streamId);
5453 return TIMED_OUT;
5454 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005455 // HAL will request buffer through requestStreamBuffer API
5456 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5457 buffer.stream = outputStream->asHalStream();
5458 buffer.buffer = nullptr;
5459 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5460 buffer.acquire_fence = -1;
5461 buffer.release_fence = -1;
5462 } else {
5463 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5464 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005465 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005466 if (res != OK) {
5467 // Can't get output buffer from gralloc queue - this could be due to
5468 // abandoned queue or other consumer misbehavior, so not a fatal
5469 // error
5470 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5471 " %s (%d)", strerror(-res), res);
5472
5473 return TIMED_OUT;
5474 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005475 }
Emilian Peev538c90e2018-12-17 18:03:19 +00005476 outputStream->fireBufferRequestForFrameNumber(
5477 captureRequest->mResultExtras.frameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -07005478
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005479 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5480
5481 if (!physicalCameraId.isEmpty()) {
5482 // Physical stream isn't supported for input request.
5483 if (halRequest->input_buffer) {
5484 CLOGE("Physical stream is not supported for input request");
5485 return INVALID_OPERATION;
5486 }
5487 requestedPhysicalCameras.insert(physicalCameraId);
5488 }
5489 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005490 }
5491 totalNumBuffers += halRequest->num_output_buffers;
5492
5493 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005494 // If this request list is for constrained high speed recording (not
5495 // preview), and the current request is not the last one in the batch,
5496 // do not send callback to the app.
5497 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005498 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005499 hasCallback = false;
5500 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005501 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005502 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005503 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5504 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5505 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5506 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5507 isStillCapture = true;
5508 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5509 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005510
5511 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5512 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5513 isZslCapture = true;
5514 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005515 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005516 res = parent->registerInFlight(halRequest->frame_number,
5517 totalNumBuffers, captureRequest->mResultExtras,
5518 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005519 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005520 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005521 requestedPhysicalCameras, isStillCapture, isZslCapture,
5522 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5523 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005524 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5525 ", burstId = %" PRId32 ".",
5526 __FUNCTION__,
5527 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5528 captureRequest->mResultExtras.burstId);
5529 if (res != OK) {
5530 SET_ERR("RequestThread: Unable to register new in-flight request:"
5531 " %s (%d)", strerror(-res), res);
5532 return INVALID_OPERATION;
5533 }
5534 }
5535
5536 return OK;
5537}
5538
Igor Murashkin1e479c02013-09-06 16:55:14 -07005539CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005540 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005541 Mutex::Autolock al(mLatestRequestMutex);
5542
5543 ALOGV("RequestThread::%s", __FUNCTION__);
5544
5545 return mLatestRequest;
5546}
5547
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005548bool Camera3Device::RequestThread::isStreamPending(
5549 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005550 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005551 Mutex::Autolock l(mRequestLock);
5552
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005553 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005554 if (!nextRequest.submitted) {
5555 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5556 if (stream == s) return true;
5557 }
5558 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005559 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005560 }
5561
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005562 for (const auto& request : mRequestQueue) {
5563 for (const auto& s : request->mOutputStreams) {
5564 if (stream == s) return true;
5565 }
5566 if (stream == request->mInputStream) return true;
5567 }
5568
5569 for (const auto& request : mRepeatingRequests) {
5570 for (const auto& s : request->mOutputStreams) {
5571 if (stream == s) return true;
5572 }
5573 if (stream == request->mInputStream) return true;
5574 }
5575
5576 return false;
5577}
Jianing Weicb0652e2014-03-12 18:29:36 -07005578
Emilian Peev40ead602017-09-26 15:46:36 +01005579bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5580 ATRACE_CALL();
5581 Mutex::Autolock l(mRequestLock);
5582
5583 for (const auto& nextRequest : mNextRequests) {
5584 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5585 if (s.first == streamId) {
5586 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5587 if (it != s.second.end()) {
5588 return true;
5589 }
5590 }
5591 }
5592 }
5593
5594 for (const auto& request : mRequestQueue) {
5595 for (const auto& s : request->mOutputSurfaces) {
5596 if (s.first == streamId) {
5597 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5598 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005599 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005600 }
5601 }
5602 }
5603 }
5604
5605 for (const auto& request : mRepeatingRequests) {
5606 for (const auto& s : request->mOutputSurfaces) {
5607 if (s.first == streamId) {
5608 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5609 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005610 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005611 }
5612 }
5613 }
5614 }
5615
5616 return false;
5617}
5618
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005619void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5620 if (!mUseHalBufManager) {
5621 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5622 return;
5623 }
5624
5625 Mutex::Autolock pl(mPauseLock);
5626 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005627 mInterface->signalPipelineDrain(streamIds);
5628 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005629 }
5630 // If request thread is still busy, wait until paused then notify HAL
5631 mNotifyPipelineDrain = true;
5632 mStreamIdsToBeDrained = streamIds;
5633}
5634
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005635nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005636 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005637 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005638 return mExpectedInflightDuration > kMinInflightDuration ?
5639 mExpectedInflightDuration : kMinInflightDuration;
5640}
5641
Emilian Peevaebbe412018-01-15 13:53:24 +00005642void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5643 camera3_capture_request_t *halRequest) {
5644 if ((request == nullptr) || (halRequest == nullptr)) {
5645 ALOGE("%s: Invalid request!", __FUNCTION__);
5646 return;
5647 }
5648
5649 if (halRequest->num_physcam_settings > 0) {
5650 if (halRequest->physcam_id != nullptr) {
5651 delete [] halRequest->physcam_id;
5652 halRequest->physcam_id = nullptr;
5653 }
5654 if (halRequest->physcam_settings != nullptr) {
5655 auto it = ++(request->mSettingsList.begin());
5656 size_t i = 0;
5657 for (; it != request->mSettingsList.end(); it++, i++) {
5658 it->metadata.unlock(halRequest->physcam_settings[i]);
5659 }
5660 delete [] halRequest->physcam_settings;
5661 halRequest->physcam_settings = nullptr;
5662 }
5663 }
5664}
5665
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005666void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5667 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005668 return;
5669 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005670
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005671 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005672 // Skip the ones that have been submitted successfully.
5673 if (nextRequest.submitted) {
5674 continue;
5675 }
5676
5677 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5678 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5679 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5680
5681 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005682 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005683 }
5684
Emilian Peevaebbe412018-01-15 13:53:24 +00005685 cleanupPhysicalSettings(captureRequest, halRequest);
5686
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005687 if (captureRequest->mInputStream != NULL) {
5688 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5689 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5690 }
5691
5692 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005693 //Buffers that failed processing could still have
5694 //valid acquire fence.
5695 int acquireFence = (*outputBuffers)[i].acquire_fence;
5696 if (0 <= acquireFence) {
5697 close(acquireFence);
5698 outputBuffers->editItemAt(i).acquire_fence = -1;
5699 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005700 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00005701 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5702 /*timestampIncreasing*/true, std::vector<size_t> (),
5703 captureRequest->mResultExtras.frameNumber);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005704 }
5705
5706 if (sendRequestError) {
5707 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005708 sp<NotificationListener> listener = mListener.promote();
5709 if (listener != NULL) {
5710 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005711 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005712 captureRequest->mResultExtras);
5713 }
5714 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005715
5716 // Remove yet-to-be submitted inflight request from inflightMap
5717 {
5718 sp<Camera3Device> parent = mParent.promote();
5719 if (parent != NULL) {
5720 Mutex::Autolock l(parent->mInFlightLock);
5721 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5722 if (idx >= 0) {
5723 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5724 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5725 parent->removeInFlightMapEntryLocked(idx);
5726 }
5727 }
5728 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005729 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005730
5731 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005732 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005733}
5734
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005735void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005736 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005737 // Optimized a bit for the simple steady-state case (single repeating
5738 // request), to avoid putting that request in the queue temporarily.
5739 Mutex::Autolock l(mRequestLock);
5740
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005741 assert(mNextRequests.empty());
5742
5743 NextRequest nextRequest;
5744 nextRequest.captureRequest = waitForNextRequestLocked();
5745 if (nextRequest.captureRequest == nullptr) {
5746 return;
5747 }
5748
5749 nextRequest.halRequest = camera3_capture_request_t();
5750 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005751 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005752
5753 // Wait for additional requests
5754 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5755
5756 for (size_t i = 1; i < batchSize; i++) {
5757 NextRequest additionalRequest;
5758 additionalRequest.captureRequest = waitForNextRequestLocked();
5759 if (additionalRequest.captureRequest == nullptr) {
5760 break;
5761 }
5762
5763 additionalRequest.halRequest = camera3_capture_request_t();
5764 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005765 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005766 }
5767
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005768 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005769 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005770 mNextRequests.size(), batchSize);
5771 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005772 }
5773
5774 return;
5775}
5776
5777sp<Camera3Device::CaptureRequest>
5778 Camera3Device::RequestThread::waitForNextRequestLocked() {
5779 status_t res;
5780 sp<CaptureRequest> nextRequest;
5781
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005782 while (mRequestQueue.empty()) {
5783 if (!mRepeatingRequests.empty()) {
5784 // Always atomically enqueue all requests in a repeating request
5785 // list. Guarantees a complete in-sequence set of captures to
5786 // application.
5787 const RequestList &requests = mRepeatingRequests;
5788 RequestList::const_iterator firstRequest =
5789 requests.begin();
5790 nextRequest = *firstRequest;
5791 mRequestQueue.insert(mRequestQueue.end(),
5792 ++firstRequest,
5793 requests.end());
5794 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005795
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005796 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005797
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005798 break;
5799 }
5800
5801 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5802
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005803 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5804 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005805 Mutex::Autolock pl(mPauseLock);
5806 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005807 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005808 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005809 // Let the tracker know
5810 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5811 if (statusTracker != 0) {
5812 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5813 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005814 if (mNotifyPipelineDrain) {
5815 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5816 mNotifyPipelineDrain = false;
5817 mStreamIdsToBeDrained.clear();
5818 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005819 sp<Camera3Device> parent = mParent.promote();
5820 if (parent != nullptr) {
5821 parent->mRequestBufferSM.onRequestThreadPaused();
5822 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005823 }
5824 // Stop waiting for now and let thread management happen
5825 return NULL;
5826 }
5827 }
5828
5829 if (nextRequest == NULL) {
5830 // Don't have a repeating request already in hand, so queue
5831 // must have an entry now.
5832 RequestList::iterator firstRequest =
5833 mRequestQueue.begin();
5834 nextRequest = *firstRequest;
5835 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005836 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5837 sp<NotificationListener> listener = mListener.promote();
5838 if (listener != NULL) {
5839 listener->notifyRequestQueueEmpty();
5840 }
5841 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005842 }
5843
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005844 // In case we've been unpaused by setPaused clearing mDoPause, need to
5845 // update internal pause state (capture/setRepeatingRequest unpause
5846 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005847 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005848 if (mPaused) {
5849 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5850 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5851 if (statusTracker != 0) {
5852 statusTracker->markComponentActive(mStatusId);
5853 }
5854 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005855 mPaused = false;
5856
5857 // Check if we've reconfigured since last time, and reset the preview
5858 // request if so. Can't use 'NULL request == repeat' across configure calls.
5859 if (mReconfigured) {
5860 mPrevRequest.clear();
5861 mReconfigured = false;
5862 }
5863
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005864 if (nextRequest != NULL) {
5865 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005866 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5867 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005868
5869 // Since RequestThread::clear() removes buffers from the input stream,
5870 // get the right buffer here before unlocking mRequestLock
5871 if (nextRequest->mInputStream != NULL) {
5872 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5873 if (res != OK) {
5874 // Can't get input buffer from gralloc queue - this could be due to
5875 // disconnected queue or other producer misbehavior, so not a fatal
5876 // error
5877 ALOGE("%s: Can't get input buffer, skipping request:"
5878 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005879
5880 sp<NotificationListener> listener = mListener.promote();
5881 if (listener != NULL) {
5882 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005883 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005884 nextRequest->mResultExtras);
5885 }
5886 return NULL;
5887 }
5888 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005889 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005890
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005891 return nextRequest;
5892}
5893
5894bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005895 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005896 status_t res;
5897 Mutex::Autolock l(mPauseLock);
5898 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005899 if (mPaused == false) {
5900 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005901 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5902 // Let the tracker know
5903 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5904 if (statusTracker != 0) {
5905 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5906 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005907 if (mNotifyPipelineDrain) {
5908 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5909 mNotifyPipelineDrain = false;
5910 mStreamIdsToBeDrained.clear();
5911 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005912 sp<Camera3Device> parent = mParent.promote();
5913 if (parent != nullptr) {
5914 parent->mRequestBufferSM.onRequestThreadPaused();
5915 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005916 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005917
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005918 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005919 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005920 return true;
5921 }
5922 }
5923 // We don't set mPaused to false here, because waitForNextRequest needs
5924 // to further manage the paused state in case of starvation.
5925 return false;
5926}
5927
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005928void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005929 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005930 // With work to do, mark thread as unpaused.
5931 // If paused by request (setPaused), don't resume, to avoid
5932 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005933 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005934 Mutex::Autolock p(mPauseLock);
5935 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005936 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5937 if (mPaused) {
5938 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5939 if (statusTracker != 0) {
5940 statusTracker->markComponentActive(mStatusId);
5941 }
5942 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005943 mPaused = false;
5944 }
5945}
5946
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005947void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5948 sp<Camera3Device> parent = mParent.promote();
5949 if (parent != NULL) {
5950 va_list args;
5951 va_start(args, fmt);
5952
5953 parent->setErrorStateV(fmt, args);
5954
5955 va_end(args);
5956 }
5957}
5958
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005959status_t Camera3Device::RequestThread::insertTriggers(
5960 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005961 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005962 Mutex::Autolock al(mTriggerMutex);
5963
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005964 sp<Camera3Device> parent = mParent.promote();
5965 if (parent == NULL) {
5966 CLOGE("RequestThread: Parent is gone");
5967 return DEAD_OBJECT;
5968 }
5969
Emilian Peevaebbe412018-01-15 13:53:24 +00005970 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005971 size_t count = mTriggerMap.size();
5972
5973 for (size_t i = 0; i < count; ++i) {
5974 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005975 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005976
5977 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5978 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5979 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005980 if (isAeTrigger) {
5981 request->mResultExtras.precaptureTriggerId = triggerId;
5982 mCurrentPreCaptureTriggerId = triggerId;
5983 } else {
5984 request->mResultExtras.afTriggerId = triggerId;
5985 mCurrentAfTriggerId = triggerId;
5986 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005987 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005988 }
5989
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005990 camera_metadata_entry entry = metadata.find(tag);
5991
5992 if (entry.count > 0) {
5993 /**
5994 * Already has an entry for this trigger in the request.
5995 * Rewrite it with our requested trigger value.
5996 */
5997 RequestTrigger oldTrigger = trigger;
5998
5999 oldTrigger.entryValue = entry.data.u8[0];
6000
6001 mTriggerReplacedMap.add(tag, oldTrigger);
6002 } else {
6003 /**
6004 * More typical, no trigger entry, so we just add it
6005 */
6006 mTriggerRemovedMap.add(tag, trigger);
6007 }
6008
6009 status_t res;
6010
6011 switch (trigger.getTagType()) {
6012 case TYPE_BYTE: {
6013 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6014 res = metadata.update(tag,
6015 &entryValue,
6016 /*count*/1);
6017 break;
6018 }
6019 case TYPE_INT32:
6020 res = metadata.update(tag,
6021 &trigger.entryValue,
6022 /*count*/1);
6023 break;
6024 default:
6025 ALOGE("%s: Type not supported: 0x%x",
6026 __FUNCTION__,
6027 trigger.getTagType());
6028 return INVALID_OPERATION;
6029 }
6030
6031 if (res != OK) {
6032 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6033 ", value %d", __FUNCTION__, trigger.getTagName(),
6034 trigger.entryValue);
6035 return res;
6036 }
6037
6038 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6039 trigger.getTagName(),
6040 trigger.entryValue);
6041 }
6042
6043 mTriggerMap.clear();
6044
6045 return count;
6046}
6047
6048status_t Camera3Device::RequestThread::removeTriggers(
6049 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006050 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006051 Mutex::Autolock al(mTriggerMutex);
6052
Emilian Peevaebbe412018-01-15 13:53:24 +00006053 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006054
6055 /**
6056 * Replace all old entries with their old values.
6057 */
6058 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6059 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6060
6061 status_t res;
6062
6063 uint32_t tag = trigger.metadataTag;
6064 switch (trigger.getTagType()) {
6065 case TYPE_BYTE: {
6066 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6067 res = metadata.update(tag,
6068 &entryValue,
6069 /*count*/1);
6070 break;
6071 }
6072 case TYPE_INT32:
6073 res = metadata.update(tag,
6074 &trigger.entryValue,
6075 /*count*/1);
6076 break;
6077 default:
6078 ALOGE("%s: Type not supported: 0x%x",
6079 __FUNCTION__,
6080 trigger.getTagType());
6081 return INVALID_OPERATION;
6082 }
6083
6084 if (res != OK) {
6085 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6086 ", trigger value %d", __FUNCTION__,
6087 trigger.getTagName(), trigger.entryValue);
6088 return res;
6089 }
6090 }
6091 mTriggerReplacedMap.clear();
6092
6093 /**
6094 * Remove all new entries.
6095 */
6096 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6097 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6098 status_t res = metadata.erase(trigger.metadataTag);
6099
6100 if (res != OK) {
6101 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6102 ", trigger value %d", __FUNCTION__,
6103 trigger.getTagName(), trigger.entryValue);
6104 return res;
6105 }
6106 }
6107 mTriggerRemovedMap.clear();
6108
6109 return OK;
6110}
6111
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006112status_t Camera3Device::RequestThread::addDummyTriggerIds(
6113 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006114 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006115 static const int32_t dummyTriggerId = 1;
6116 status_t res;
6117
Emilian Peevaebbe412018-01-15 13:53:24 +00006118 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006119
6120 // If AF trigger is active, insert a dummy AF trigger ID if none already
6121 // exists
6122 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6123 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6124 if (afTrigger.count > 0 &&
6125 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6126 afId.count == 0) {
6127 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6128 if (res != OK) return res;
6129 }
6130
6131 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6132 // if none already exists
6133 camera_metadata_entry pcTrigger =
6134 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6135 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6136 if (pcTrigger.count > 0 &&
6137 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6138 pcId.count == 0) {
6139 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6140 &dummyTriggerId, 1);
6141 if (res != OK) return res;
6142 }
6143
6144 return OK;
6145}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006146
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006147/**
6148 * PreparerThread inner class methods
6149 */
6150
6151Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006152 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006153 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006154}
6155
6156Camera3Device::PreparerThread::~PreparerThread() {
6157 Thread::requestExitAndWait();
6158 if (mCurrentStream != nullptr) {
6159 mCurrentStream->cancelPrepare();
6160 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6161 mCurrentStream.clear();
6162 }
6163 clear();
6164}
6165
Ruben Brunkc78ac262015-08-13 17:58:46 -07006166status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006167 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006168 status_t res;
6169
6170 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006171 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006172
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006173 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006174 if (res == OK) {
6175 // No preparation needed, fire listener right off
6176 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006177 if (listener != NULL) {
6178 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006179 }
6180 return OK;
6181 } else if (res != NOT_ENOUGH_DATA) {
6182 return res;
6183 }
6184
6185 // Need to prepare, start up thread if necessary
6186 if (!mActive) {
6187 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6188 // isn't running
6189 Thread::requestExitAndWait();
6190 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6191 if (res != OK) {
6192 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006193 if (listener != NULL) {
6194 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006195 }
6196 return res;
6197 }
6198 mCancelNow = false;
6199 mActive = true;
6200 ALOGV("%s: Preparer stream started", __FUNCTION__);
6201 }
6202
6203 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006204 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006205 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6206
6207 return OK;
6208}
6209
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006210void Camera3Device::PreparerThread::pause() {
6211 ATRACE_CALL();
6212
6213 Mutex::Autolock l(mLock);
6214
6215 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6216 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6217 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6218 int currentMaxCount = mCurrentMaxCount;
6219 mPendingStreams.clear();
6220 mCancelNow = true;
6221 while (mActive) {
6222 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6223 if (res == TIMED_OUT) {
6224 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6225 return;
6226 } else if (res != OK) {
6227 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6228 return;
6229 }
6230 }
6231
6232 //Check whether the prepare thread was able to complete the current
6233 //stream. In case work is still pending emplace it along with the rest
6234 //of the streams in the pending list.
6235 if (currentStream != nullptr) {
6236 if (!mCurrentPrepareComplete) {
6237 pendingStreams.emplace(currentMaxCount, currentStream);
6238 }
6239 }
6240
6241 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6242 for (const auto& it : mPendingStreams) {
6243 it.second->cancelPrepare();
6244 }
6245}
6246
6247status_t Camera3Device::PreparerThread::resume() {
6248 ATRACE_CALL();
6249 status_t res;
6250
6251 Mutex::Autolock l(mLock);
6252 sp<NotificationListener> listener = mListener.promote();
6253
6254 if (mActive) {
6255 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6256 return NO_INIT;
6257 }
6258
6259 auto it = mPendingStreams.begin();
6260 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006261 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006262 if (res == OK) {
6263 if (listener != NULL) {
6264 listener->notifyPrepared(it->second->getId());
6265 }
6266 it = mPendingStreams.erase(it);
6267 } else if (res != NOT_ENOUGH_DATA) {
6268 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6269 res, strerror(-res));
6270 it = mPendingStreams.erase(it);
6271 } else {
6272 it++;
6273 }
6274 }
6275
6276 if (mPendingStreams.empty()) {
6277 return OK;
6278 }
6279
6280 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6281 if (res != OK) {
6282 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6283 __FUNCTION__, res, strerror(-res));
6284 return res;
6285 }
6286 mCancelNow = false;
6287 mActive = true;
6288 ALOGV("%s: Preparer stream started", __FUNCTION__);
6289
6290 return OK;
6291}
6292
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006293status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006294 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006295 Mutex::Autolock l(mLock);
6296
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006297 for (const auto& it : mPendingStreams) {
6298 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006299 }
6300 mPendingStreams.clear();
6301 mCancelNow = true;
6302
6303 return OK;
6304}
6305
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006306void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006307 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006308 Mutex::Autolock l(mLock);
6309 mListener = listener;
6310}
6311
6312bool Camera3Device::PreparerThread::threadLoop() {
6313 status_t res;
6314 {
6315 Mutex::Autolock l(mLock);
6316 if (mCurrentStream == nullptr) {
6317 // End thread if done with work
6318 if (mPendingStreams.empty()) {
6319 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6320 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6321 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6322 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006323 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006324 return false;
6325 }
6326
6327 // Get next stream to prepare
6328 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006329 mCurrentStream = it->second;
6330 mCurrentMaxCount = it->first;
6331 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006332 mPendingStreams.erase(it);
6333 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6334 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6335 } else if (mCancelNow) {
6336 mCurrentStream->cancelPrepare();
6337 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6338 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6339 mCurrentStream.clear();
6340 mCancelNow = false;
6341 return true;
6342 }
6343 }
6344
6345 res = mCurrentStream->prepareNextBuffer();
6346 if (res == NOT_ENOUGH_DATA) return true;
6347 if (res != OK) {
6348 // Something bad happened; try to recover by cancelling prepare and
6349 // signalling listener anyway
6350 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6351 mCurrentStream->getId(), res, strerror(-res));
6352 mCurrentStream->cancelPrepare();
6353 }
6354
6355 // This stream has finished, notify listener
6356 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006357 sp<NotificationListener> listener = mListener.promote();
6358 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006359 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6360 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006361 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006362 }
6363
6364 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6365 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006366 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006367
6368 return true;
6369}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006370
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006371status_t Camera3Device::RequestBufferStateMachine::initialize(
6372 sp<camera3::StatusTracker> statusTracker) {
6373 if (statusTracker == nullptr) {
6374 ALOGE("%s: statusTracker is null", __FUNCTION__);
6375 return BAD_VALUE;
6376 }
6377
6378 std::lock_guard<std::mutex> lock(mLock);
6379 mStatusTracker = statusTracker;
6380 mRequestBufferStatusId = statusTracker->addComponent();
6381 return OK;
6382}
6383
6384bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6385 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006386 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006387 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006388 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006389 return true;
6390 }
6391 return false;
6392}
6393
6394void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6395 std::lock_guard<std::mutex> lock(mLock);
6396 if (!mRequestBufferOngoing) {
6397 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6398 return;
6399 }
6400 mRequestBufferOngoing = false;
6401 if (mStatus == RB_STATUS_PENDING_STOP) {
6402 checkSwitchToStopLocked();
6403 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006404 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006405}
6406
6407void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6408 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006409 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006410 return;
6411}
6412
6413void Camera3Device::RequestBufferStateMachine::onRequestSubmitted() {
6414 std::lock_guard<std::mutex> lock(mLock);
6415 mRequestThreadPaused = false;
6416 mInflightMapEmpty = false;
6417 if (mStatus == RB_STATUS_STOPPED) {
6418 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006419 }
6420 return;
6421}
6422
6423void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6424 std::lock_guard<std::mutex> lock(mLock);
6425 mRequestThreadPaused = true;
6426 if (mStatus == RB_STATUS_PENDING_STOP) {
6427 checkSwitchToStopLocked();
6428 }
6429 return;
6430}
6431
6432void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6433 std::lock_guard<std::mutex> lock(mLock);
6434 mInflightMapEmpty = true;
6435 if (mStatus == RB_STATUS_PENDING_STOP) {
6436 checkSwitchToStopLocked();
6437 }
6438 return;
6439}
6440
6441void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6442 std::lock_guard<std::mutex> lock(mLock);
6443 if (!checkSwitchToStopLocked()) {
6444 mStatus = RB_STATUS_PENDING_STOP;
6445 }
6446 return;
6447}
6448
6449void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6450 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6451 if (statusTracker != nullptr) {
6452 if (active) {
6453 statusTracker->markComponentActive(mRequestBufferStatusId);
6454 } else {
6455 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6456 }
6457 }
6458}
6459
6460bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6461 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6462 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006463 return true;
6464 }
6465 return false;
6466}
6467
Shuzhen Wang268a1362018-10-16 16:32:59 -07006468status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6469 CameraMetadata& resultMetadata) {
6470 status_t res = OK;
6471 if (!mNeedFixupMonochromeTags) {
6472 return res;
6473 }
6474
6475 // Remove tags that are not applicable to monochrome camera.
6476 int32_t tagsToRemove[] = {
6477 ANDROID_SENSOR_GREEN_SPLIT,
6478 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6479 ANDROID_COLOR_CORRECTION_MODE,
6480 ANDROID_COLOR_CORRECTION_TRANSFORM,
6481 ANDROID_COLOR_CORRECTION_GAINS,
6482 };
6483 for (auto tag : tagsToRemove) {
6484 res = resultMetadata.erase(tag);
6485 if (res != OK) {
6486 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6487 return res;
6488 }
6489 }
6490
6491 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6492 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6493 for (size_t i = 1; i < blEntry.count; i++) {
6494 blEntry.data.f[i] = blEntry.data.f[0];
6495 }
6496
6497 // ANDROID_SENSOR_NOISE_PROFILE
6498 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6499 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6500 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6501 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6502 if (res != OK) {
6503 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6504 __FUNCTION__, strerror(-res), res);
6505 return res;
6506 }
6507 }
6508
6509 // ANDROID_STATISTICS_LENS_SHADING_MAP
6510 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6511 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6512 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6513 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6514 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6515 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6516 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6517 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6518 }
6519 }
6520
6521 // ANDROID_TONEMAP_CURVE_BLUE
6522 // ANDROID_TONEMAP_CURVE_GREEN
6523 // ANDROID_TONEMAP_CURVE_RED
6524 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6525 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6526 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6527 if (tcbEntry.count > 0
6528 && tcbEntry.count == tcgEntry.count
6529 && tcbEntry.count == tcrEntry.count) {
6530 for (size_t i = 0; i < tcbEntry.count; i++) {
6531 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6532 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6533 }
6534 }
6535
6536 return res;
6537}
6538
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006539}; // namespace android