blob: 00f0d86387ec3256bfc6392f47721dc22b9a07ec [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
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080061#include <tuple>
62
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080063using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080064using namespace android::hardware::camera;
65using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080066
67namespace android {
68
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080069Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080070 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080071 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070072 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070073 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070074 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070075 mUsePartialResult(false),
76 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080077 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070078 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070079 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070080 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070081 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070082 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070083 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000084 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010085 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070086 mLastTemplateId(-1),
87 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080088{
89 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080090 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080091}
92
93Camera3Device::~Camera3Device()
94{
95 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080096 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -070097 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080098}
99
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800100const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800101 return mId;
102}
103
Emilian Peevbd8c5032018-02-14 23:05:40 +0000104status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800105 ATRACE_CALL();
106 Mutex::Autolock il(mInterfaceLock);
107 Mutex::Autolock l(mLock);
108
109 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
110 if (mStatus != STATUS_UNINITIALIZED) {
111 CLOGE("Already initialized!");
112 return INVALID_OPERATION;
113 }
114 if (manager == nullptr) return INVALID_OPERATION;
115
116 sp<ICameraDeviceSession> session;
117 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800118 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800119 /*out*/ &session);
120 ATRACE_END();
121 if (res != OK) {
122 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
123 return res;
124 }
125
Steven Moreland5ff9c912017-03-09 23:13:00 -0800126 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800127 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700128 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800129 session->close();
130 return res;
131 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800132
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700133 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700134 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700135 if (isLogical) {
136 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700137 res = manager->getCameraCharacteristics(
138 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700139 if (res != OK) {
140 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
141 physicalId.c_str(), strerror(-res), res);
142 session->close();
143 return res;
144 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700145
146 if (DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId])) {
147 mDistortionMappers[physicalId].setupStaticInfo(mPhysicalDeviceInfoMap[physicalId]);
148 if (res != OK) {
149 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
150 "correction", physicalId.c_str());
151 session->close();
152 return res;
153 }
154 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700155 }
156 }
157
Yifan Hongf79b5542017-04-11 14:44:25 -0700158 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700159 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
160 [&queue](const auto& descriptor) {
161 queue = std::make_shared<RequestMetadataQueue>(descriptor);
162 if (!queue->isValid() || queue->availableToWrite() <= 0) {
163 ALOGE("HAL returns empty request metadata fmq, not use it");
164 queue = nullptr;
165 // don't use the queue onwards.
166 }
167 });
168 if (!requestQueueRet.isOk()) {
169 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
170 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700171 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700172 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700173
174 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700175 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700176 [&resQueue](const auto& descriptor) {
177 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
178 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700179 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700180 resQueue = nullptr;
181 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700182 }
183 });
184 if (!resultQueueRet.isOk()) {
185 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
186 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700187 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700188 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700189 IF_ALOGV() {
190 session->interfaceChain([](
191 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
192 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800193 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700194 ALOGV(" %s", iface.c_str());
195 }
196 });
197 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700198
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800199 camera_metadata_entry bufMgrMode =
200 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
201 if (bufMgrMode.count > 0) {
202 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
203 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
204 }
205
206 mInterface = new HalInterface(session, queue, mUseHalBufManager);
Emilian Peev71c73a22017-03-21 16:35:51 +0000207 std::string providerType;
208 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000209 mTagMonitor.initialize(mVendorTagId);
210 if (!monitorTags.isEmpty()) {
211 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
212 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800213
Shuzhen Wang268a1362018-10-16 16:32:59 -0700214 // Metadata tags needs fixup for monochrome camera device version less
215 // than 3.5.
216 hardware::hidl_version maxVersion{0,0};
217 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
218 if (res != OK) {
219 ALOGE("%s: Error in getting camera device version id: %s (%d)",
220 __FUNCTION__, strerror(-res), res);
221 return res;
222 }
223 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
224 maxVersion.get_major(), maxVersion.get_minor());
225
226 bool isMonochrome = false;
227 camera_metadata_entry_t entry = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
228 for (size_t i = 0; i < entry.count; i++) {
229 uint8_t capability = entry.data.u8[i];
230 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
231 isMonochrome = true;
232 }
233 }
234 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
235
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800236 return initializeCommonLocked();
237}
238
239status_t Camera3Device::initializeCommonLocked() {
240
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700241 /** Start up status tracker thread */
242 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800243 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700244 if (res != OK) {
245 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
246 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800247 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700248 mStatusTracker.clear();
249 return res;
250 }
251
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700252 /** Register in-flight map to the status tracker */
253 mInFlightStatusId = mStatusTracker->addComponent();
254
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700255 if (mUseHalBufManager) {
256 res = mRequestBufferSM.initialize(mStatusTracker);
257 if (res != OK) {
258 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
259 strerror(-res), res);
260 mInterface->close();
261 mStatusTracker.clear();
262 return res;
263 }
264 }
265
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800266 /** Create buffer manager */
267 mBufferManager = new Camera3BufferManager();
268
269 Vector<int32_t> sessionParamKeys;
270 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
271 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
272 if (sessionKeysEntry.count > 0) {
273 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
274 }
275
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700276 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700277 mRequestThread = new RequestThread(
278 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800279 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800280 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700281 SET_ERR_L("Unable to start request queue thread: %s (%d)",
282 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800283 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800284 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800285 return res;
286 }
287
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700288 mPreparerThread = new PreparerThread();
289
Ruben Brunk183f0562015-08-12 12:55:02 -0700290 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800291 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700292 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700293 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700294 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800295
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800296 // Measure the clock domain offset between camera and video/hw_composer
297 camera_metadata_entry timestampSource =
298 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
299 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
300 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
301 mTimestampOffset = getMonoToBoottimeOffset();
302 }
303
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700304 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100305 camera_metadata_entry partialResultsCount =
306 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
307 if (partialResultsCount.count > 0) {
308 mNumPartialResults = partialResultsCount.data.i32[0];
309 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700310 }
311
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700312 camera_metadata_entry configs =
313 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
314 for (uint32_t i = 0; i < configs.count; i += 4) {
315 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
316 configs.data.i32[i + 3] ==
317 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
318 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
319 configs.data.i32[i + 2]));
320 }
321 }
322
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700323 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700324 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700325 if (res != OK) {
326 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
327 return res;
328 }
329 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800330 return OK;
331}
332
333status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700334 return disconnectImpl();
335}
336
337status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800338 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700339 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800340
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700341 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800342
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700343 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700344 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700345 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700346 {
347 Mutex::Autolock l(mLock);
348 if (mStatus == STATUS_UNINITIALIZED) return res;
349
350 if (mStatus == STATUS_ACTIVE ||
351 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
352 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700353 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700354 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700355 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700356 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700357 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700358 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700359 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
360 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700361 // Continue to close device even in case of error
362 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700363 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800364 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800365
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700366 if (mStatus == STATUS_ERROR) {
367 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700368 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700369
370 if (mStatusTracker != NULL) {
371 mStatusTracker->requestExit();
372 }
373
374 if (mRequestThread != NULL) {
375 mRequestThread->requestExit();
376 }
377
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700378 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
379 for (size_t i = 0; i < mOutputStreams.size(); i++) {
380 streams.push_back(mOutputStreams[i]);
381 }
382 if (mInputStream != nullptr) {
383 streams.push_back(mInputStream);
384 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700385 }
386
387 // Joining done without holding mLock, otherwise deadlocks may ensue
388 // as the threads try to access parent state
389 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
390 // HAL may be in a bad state, so waiting for request thread
391 // (which may be stuck in the HAL processCaptureRequest call)
392 // could be dangerous.
393 mRequestThread->join();
394 }
395
396 if (mStatusTracker != NULL) {
397 mStatusTracker->join();
398 }
399
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800400 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700401 {
402 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800403 mRequestThread.clear();
Emilian Peev2843c362018-09-26 08:49:40 +0100404 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700405 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800406 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700407 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800408
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700409 // Call close without internal mutex held, as the HAL close may need to
410 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800411 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700412
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700413 flushInflightRequests();
414
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700415 {
416 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800417 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700418 mOutputStreams.clear();
419 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700420 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700421 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700422 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700423 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800424
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700425 for (auto& weakStream : streams) {
426 sp<Camera3StreamInterface> stream = weakStream.promote();
427 if (stream != nullptr) {
428 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
429 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
430 }
431 }
432
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700433 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700434 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800435}
436
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700437// For dumping/debugging only -
438// try to acquire a lock a few times, eventually give up to proceed with
439// debug/dump operations
440bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
441 bool gotLock = false;
442 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
443 if (lock.tryLock() == NO_ERROR) {
444 gotLock = true;
445 break;
446 } else {
447 usleep(kDumpSleepDuration);
448 }
449 }
450 return gotLock;
451}
452
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700453Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
454 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100455 const int STREAM_CONFIGURATION_SIZE = 4;
456 const int STREAM_FORMAT_OFFSET = 0;
457 const int STREAM_WIDTH_OFFSET = 1;
458 const int STREAM_HEIGHT_OFFSET = 2;
459 const int STREAM_IS_INPUT_OFFSET = 3;
460 camera_metadata_ro_entry_t availableStreamConfigs =
461 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
462 if (availableStreamConfigs.count == 0 ||
463 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
464 return Size(0, 0);
465 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700466
Emilian Peev08dd2452017-04-06 16:55:14 +0100467 // Get max jpeg size (area-wise).
468 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
469 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
470 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
471 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
472 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
473 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
474 && format == HAL_PIXEL_FORMAT_BLOB &&
475 (width * height > maxJpegWidth * maxJpegHeight)) {
476 maxJpegWidth = width;
477 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700478 }
479 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100480
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700481 return Size(maxJpegWidth, maxJpegHeight);
482}
483
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800484nsecs_t Camera3Device::getMonoToBoottimeOffset() {
485 // try three times to get the clock offset, choose the one
486 // with the minimum gap in measurements.
487 const int tries = 3;
488 nsecs_t bestGap, measured;
489 for (int i = 0; i < tries; ++i) {
490 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
491 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
492 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
493 const nsecs_t gap = tmono2 - tmono;
494 if (i == 0 || gap < bestGap) {
495 bestGap = gap;
496 measured = tbase - ((tmono + tmono2) >> 1);
497 }
498 }
499 return measured;
500}
501
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800502hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
503 int frameworkFormat) {
504 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
505}
506
507DataspaceFlags Camera3Device::mapToHidlDataspace(
508 android_dataspace dataSpace) {
509 return dataSpace;
510}
511
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700512BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100513 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700514 return usage;
515}
516
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800517StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
518 switch (rotation) {
519 case CAMERA3_STREAM_ROTATION_0:
520 return StreamRotation::ROTATION_0;
521 case CAMERA3_STREAM_ROTATION_90:
522 return StreamRotation::ROTATION_90;
523 case CAMERA3_STREAM_ROTATION_180:
524 return StreamRotation::ROTATION_180;
525 case CAMERA3_STREAM_ROTATION_270:
526 return StreamRotation::ROTATION_270;
527 }
528 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
529 return StreamRotation::ROTATION_0;
530}
531
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800532status_t Camera3Device::mapToStreamConfigurationMode(
533 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
534 if (mode == nullptr) return BAD_VALUE;
535 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
536 switch(operationMode) {
537 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
538 *mode = StreamConfigurationMode::NORMAL_MODE;
539 break;
540 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
541 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
542 break;
543 default:
544 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
545 return BAD_VALUE;
546 }
547 } else {
548 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800549 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800550 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800551}
552
553camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
554 switch (status) {
555 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
556 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
557 }
558 return CAMERA3_BUFFER_STATUS_ERROR;
559}
560
561int Camera3Device::mapToFrameworkFormat(
562 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
563 return static_cast<uint32_t>(pixelFormat);
564}
565
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700566android_dataspace Camera3Device::mapToFrameworkDataspace(
567 DataspaceFlags dataSpace) {
568 return static_cast<android_dataspace>(dataSpace);
569}
570
Emilian Peev050f5dc2017-05-18 14:43:56 +0100571uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700572 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700573 return usage;
574}
575
Emilian Peev050f5dc2017-05-18 14:43:56 +0100576uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700577 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700578 return usage;
579}
580
Zhijun Hef7da0962014-04-24 13:27:56 -0700581ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700582 // Get max jpeg size (area-wise).
583 Size maxJpegResolution = getMaxJpegResolution();
584 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800585 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
586 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700587 return BAD_VALUE;
588 }
589
Zhijun Hef7da0962014-04-24 13:27:56 -0700590 // Get max jpeg buffer size
591 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700592 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
593 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800594 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
595 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700596 return BAD_VALUE;
597 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700598 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800599 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700600
601 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700602 float scaleFactor = ((float) (width * height)) /
603 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800604 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
605 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700606 if (jpegBufferSize > maxJpegBufferSize) {
607 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700608 }
609
610 return jpegBufferSize;
611}
612
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700613ssize_t Camera3Device::getPointCloudBufferSize() const {
614 const int FLOATS_PER_POINT=4;
615 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
616 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800617 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
618 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700619 return BAD_VALUE;
620 }
621 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
622 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
623 return maxBytesForPointCloud;
624}
625
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800626ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800627 const int PER_CONFIGURATION_SIZE = 3;
628 const int WIDTH_OFFSET = 0;
629 const int HEIGHT_OFFSET = 1;
630 const int SIZE_OFFSET = 2;
631 camera_metadata_ro_entry rawOpaqueSizes =
632 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800633 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800634 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800635 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
636 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800637 return BAD_VALUE;
638 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700639
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800640 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
641 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
642 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
643 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
644 }
645 }
646
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800647 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
648 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800649 return BAD_VALUE;
650}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700651
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800652status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
653 ATRACE_CALL();
654 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700655
656 // Try to lock, but continue in case of failure (to avoid blocking in
657 // deadlocks)
658 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
659 bool gotLock = tryLockSpinRightRound(mLock);
660
661 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800662 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
663 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700664 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800665 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
666 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700667
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800668 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700669
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800670 String16 templatesOption("-t");
671 int n = args.size();
672 for (int i = 0; i < n; i++) {
673 if (args[i] == templatesOption) {
674 dumpTemplates = true;
675 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000676 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700677 if (i + 1 < n) {
678 String8 monitorTags = String8(args[i + 1]);
679 if (monitorTags == "off") {
680 mTagMonitor.disableMonitoring();
681 } else {
682 mTagMonitor.parseTagsToMonitor(monitorTags);
683 }
684 } else {
685 mTagMonitor.disableMonitoring();
686 }
687 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800688 }
689
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800690 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800691
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800692 const char *status =
693 mStatus == STATUS_ERROR ? "ERROR" :
694 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700695 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
696 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800697 mStatus == STATUS_ACTIVE ? "ACTIVE" :
698 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700699
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800700 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700701 if (mStatus == STATUS_ERROR) {
702 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
703 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800704 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800705 const char *mode =
706 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
707 mOperatingMode == static_cast<int>(
708 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
709 "CUSTOM";
710 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800711
712 if (mInputStream != NULL) {
713 write(fd, lines.string(), lines.size());
714 mInputStream->dump(fd, args);
715 } else {
716 lines.appendFormat(" No input stream.\n");
717 write(fd, lines.string(), lines.size());
718 }
719 for (size_t i = 0; i < mOutputStreams.size(); i++) {
720 mOutputStreams[i]->dump(fd,args);
721 }
722
Zhijun He431503c2016-03-07 17:30:16 -0800723 if (mBufferManager != NULL) {
724 lines = String8(" Camera3 Buffer Manager:\n");
725 write(fd, lines.string(), lines.size());
726 mBufferManager->dump(fd, args);
727 }
Zhijun He125684a2015-12-26 15:07:30 -0800728
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700729 lines = String8(" In-flight requests:\n");
730 if (mInFlightMap.size() == 0) {
731 lines.append(" None\n");
732 } else {
733 for (size_t i = 0; i < mInFlightMap.size(); i++) {
734 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700735 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700736 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800737 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700738 r.numBuffersLeft);
739 }
740 }
741 write(fd, lines.string(), lines.size());
742
Shuzhen Wang686f6442017-06-20 16:16:04 -0700743 if (mRequestThread != NULL) {
744 mRequestThread->dumpCaptureRequestLatency(fd,
745 " ProcessCaptureRequest latency histogram:");
746 }
747
Igor Murashkin1e479c02013-09-06 16:55:14 -0700748 {
749 lines = String8(" Last request sent:\n");
750 write(fd, lines.string(), lines.size());
751
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700752 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700753 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
754 }
755
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800756 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800757 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800758 "TEMPLATE_PREVIEW",
759 "TEMPLATE_STILL_CAPTURE",
760 "TEMPLATE_VIDEO_RECORD",
761 "TEMPLATE_VIDEO_SNAPSHOT",
762 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800763 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800764 };
765
766 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800767 camera_metadata_t *templateRequest = nullptr;
768 mInterface->constructDefaultRequestSettings(
769 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800770 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800771 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800772 lines.append(" Not supported\n");
773 write(fd, lines.string(), lines.size());
774 } else {
775 write(fd, lines.string(), lines.size());
776 dump_indented_camera_metadata(templateRequest,
777 fd, /*verbosity*/2, /*indentation*/8);
778 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800779 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800780 }
781 }
782
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700783 mTagMonitor.dumpMonitoredMetadata(fd);
784
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800785 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800786 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800787 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800788 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800789 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800790
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700791 if (gotLock) mLock.unlock();
792 if (gotInterfaceLock) mInterfaceLock.unlock();
793
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800794 return OK;
795}
796
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700797const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800798 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800799 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
800 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700801 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800802 mStatus == STATUS_ERROR ?
803 "when in error state" : "before init");
804 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700805 if (physicalId.isEmpty()) {
806 return mDeviceInfo;
807 } else {
808 std::string id(physicalId.c_str());
809 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
810 return mPhysicalDeviceInfoMap.at(id);
811 } else {
812 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
813 return mDeviceInfo;
814 }
815 }
816}
817
818const CameraMetadata& Camera3Device::info() const {
819 String8 emptyId;
820 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800821}
822
Jianing Wei90e59c92014-03-12 18:29:36 -0700823status_t Camera3Device::checkStatusOkToCaptureLocked() {
824 switch (mStatus) {
825 case STATUS_ERROR:
826 CLOGE("Device has encountered a serious error");
827 return INVALID_OPERATION;
828 case STATUS_UNINITIALIZED:
829 CLOGE("Device not initialized");
830 return INVALID_OPERATION;
831 case STATUS_UNCONFIGURED:
832 case STATUS_CONFIGURED:
833 case STATUS_ACTIVE:
834 // OK
835 break;
836 default:
837 SET_ERR_L("Unexpected status: %d", mStatus);
838 return INVALID_OPERATION;
839 }
840 return OK;
841}
842
843status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000844 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700845 const std::list<const SurfaceMap> &surfaceMaps,
846 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700847 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700848 if (requestList == NULL) {
849 CLOGE("requestList cannot be NULL.");
850 return BAD_VALUE;
851 }
852
Jianing Weicb0652e2014-03-12 18:29:36 -0700853 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000854 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700855 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
856 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
857 ++metadataIt, ++surfaceMapIt) {
858 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700859 if (newRequest == 0) {
860 CLOGE("Can't create capture request");
861 return BAD_VALUE;
862 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700863
Shuzhen Wang9d066012016-09-30 11:30:20 -0700864 newRequest->mRepeating = repeating;
865
Jianing Weicb0652e2014-03-12 18:29:36 -0700866 // Setup burst Id and request Id
867 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000868 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
869 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700870 CLOGE("RequestID entry exists; but must not be empty in metadata");
871 return BAD_VALUE;
872 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000873 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
874 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700875 } else {
876 CLOGE("RequestID does not exist in metadata");
877 return BAD_VALUE;
878 }
879
Jianing Wei90e59c92014-03-12 18:29:36 -0700880 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700881
882 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700883 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700884 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
885 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
886 return BAD_VALUE;
887 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700888
889 // Setup batch size if this is a high speed video recording request.
890 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
891 auto firstRequest = requestList->begin();
892 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
893 if (outputStream->isVideoStream()) {
894 (*firstRequest)->mBatchSize = requestList->size();
895 break;
896 }
897 }
898 }
899
Jianing Wei90e59c92014-03-12 18:29:36 -0700900 return OK;
901}
902
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800903status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800904 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800905
Emilian Peevaebbe412018-01-15 13:53:24 +0000906 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700907 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000908 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700909
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800910 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700911}
912
Emilian Peevaebbe412018-01-15 13:53:24 +0000913void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700914 std::list<const SurfaceMap>& surfaceMaps,
915 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000916 PhysicalCameraSettingsList requestList;
917 requestList.push_back({std::string(getId().string()), request});
918 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700919
920 SurfaceMap surfaceMap;
921 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
922 // With no surface list passed in, stream and surface will have 1-to-1
923 // mapping. So the surface index is 0 for each stream in the surfaceMap.
924 for (size_t i = 0; i < streams.count; i++) {
925 surfaceMap[streams.data.i32[i]].push_back(0);
926 }
927 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800928}
929
Jianing Wei90e59c92014-03-12 18:29:36 -0700930status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000931 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700932 const std::list<const SurfaceMap> &surfaceMaps,
933 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700934 /*out*/
935 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700936 ATRACE_CALL();
937 Mutex::Autolock il(mInterfaceLock);
938 Mutex::Autolock l(mLock);
939
940 status_t res = checkStatusOkToCaptureLocked();
941 if (res != OK) {
942 // error logged by previous call
943 return res;
944 }
945
946 RequestList requestList;
947
Shuzhen Wang0129d522016-10-30 22:43:41 -0700948 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
949 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700950 if (res != OK) {
951 // error logged by previous call
952 return res;
953 }
954
955 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700956 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700957 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700958 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700959 }
960
961 if (res == OK) {
962 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
963 if (res != OK) {
964 SET_ERR_L("Can't transition to active in %f seconds!",
965 kActiveTimeout/1e9);
966 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800967 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700968 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700969 } else {
970 CLOGE("Cannot queue request. Impossible.");
971 return BAD_VALUE;
972 }
973
974 return res;
975}
976
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700977hardware::Return<void> Camera3Device::requestStreamBuffers(
978 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
979 requestStreamBuffers_cb _hidl_cb) {
980 using hardware::camera::device::V3_5::BufferRequestStatus;
981 using hardware::camera::device::V3_5::StreamBufferRet;
982 using hardware::camera::device::V3_5::StreamBufferRequestError;
983
984 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
985
986 hardware::hidl_vec<StreamBufferRet> bufRets;
987 if (!mUseHalBufManager) {
988 ALOGE("%s: Camera %s does not support HAL buffer management",
989 __FUNCTION__, mId.string());
990 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
991 return hardware::Void();
992 }
993
994 SortedVector<int32_t> streamIds;
995 ssize_t sz = streamIds.setCapacity(bufReqs.size());
996 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
997 ALOGE("%s: failed to allocate memory for %zu buffer requests",
998 __FUNCTION__, bufReqs.size());
999 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1000 return hardware::Void();
1001 }
1002
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001003 if (bufReqs.size() > mOutputStreams.size()) {
1004 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
1005 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
1006 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1007 return hardware::Void();
1008 }
1009
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001010 // Check for repeated streamId
1011 for (const auto& bufReq : bufReqs) {
1012 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
1013 ALOGE("%s: Stream %d appear multiple times in buffer requests",
1014 __FUNCTION__, bufReq.streamId);
1015 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1016 return hardware::Void();
1017 }
1018 streamIds.add(bufReq.streamId);
1019 }
1020
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001021 if (!mRequestBufferSM.startRequestBuffer()) {
1022 ALOGE("%s: request buffer disallowed while camera service is configuring",
1023 __FUNCTION__);
1024 _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001025 return hardware::Void();
1026 }
1027
1028 bufRets.resize(bufReqs.size());
1029
1030 bool allReqsSucceeds = true;
1031 bool oneReqSucceeds = false;
1032 for (size_t i = 0; i < bufReqs.size(); i++) {
1033 const auto& bufReq = bufReqs[i];
1034 auto& bufRet = bufRets[i];
1035 int32_t streamId = bufReq.streamId;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001036 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
1037 if (outputStream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001038 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
1039 hardware::hidl_vec<StreamBufferRet> emptyBufRets;
1040 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001041 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001042 return hardware::Void();
1043 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001044
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001045 if (outputStream->isAbandoned()) {
1046 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1047 allReqsSucceeds = false;
1048 continue;
1049 }
1050
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001051 bufRet.streamId = streamId;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001052 size_t handOutBufferCount = outputStream->getOutstandingBuffersCount();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001053 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001054 size_t totalHandout = handOutBufferCount + numBuffersRequested;
1055 uint32_t maxBuffers = outputStream->asHalStream()->max_buffers;
1056 if (totalHandout > maxBuffers) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001057 // Not able to allocate enough buffer. Exit early for this stream
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001058 ALOGE("%s: request too much buffers for stream %d: at HAL: %zu + requesting: %d"
1059 " > max: %d", __FUNCTION__, streamId, handOutBufferCount,
1060 numBuffersRequested, maxBuffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001061 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1062 allReqsSucceeds = false;
1063 continue;
1064 }
1065
1066 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1067 bool currentReqSucceeds = true;
1068 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1069 size_t numAllocatedBuffers = 0;
1070 size_t numPushedInflightBuffers = 0;
1071 for (size_t b = 0; b < numBuffersRequested; b++) {
1072 camera3_stream_buffer_t& sb = streamBuffers[b];
1073 // Since this method can run concurrently with request thread
1074 // We need to update the wait duration everytime we call getbuffer
1075 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1076 status_t res = outputStream->getBuffer(&sb, waitDuration);
1077 if (res != OK) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001078 if (res == NO_INIT || res == DEAD_OBJECT) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001079 ALOGV("%s: Can't get output buffer for stream %d: %s (%d)",
1080 __FUNCTION__, streamId, strerror(-res), res);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001081 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001082 } else {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001083 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1084 __FUNCTION__, streamId, strerror(-res), res);
1085 if (res == TIMED_OUT || res == NO_MEMORY) {
1086 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1087 } else {
1088 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1089 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001090 }
1091 currentReqSucceeds = false;
1092 break;
1093 }
1094 numAllocatedBuffers++;
1095
1096 buffer_handle_t *buffer = sb.buffer;
1097 auto pair = mInterface->getBufferId(*buffer, streamId);
1098 bool isNewBuffer = pair.first;
1099 uint64_t bufferId = pair.second;
1100 StreamBuffer& hBuf = tmpRetBuffers[b];
1101
1102 hBuf.streamId = streamId;
1103 hBuf.bufferId = bufferId;
1104 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1105 hBuf.status = BufferStatus::OK;
1106 hBuf.releaseFence = nullptr;
1107
1108 native_handle_t *acquireFence = nullptr;
1109 if (sb.acquire_fence != -1) {
1110 acquireFence = native_handle_create(1,0);
1111 acquireFence->data[0] = sb.acquire_fence;
1112 }
1113 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1114 hBuf.releaseFence = nullptr;
1115
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08001116 res = mInterface->pushInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001117 if (res != OK) {
1118 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1119 __FUNCTION__, streamId, strerror(-res), res);
1120 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1121 currentReqSucceeds = false;
1122 break;
1123 }
1124 numPushedInflightBuffers++;
1125 }
1126 if (currentReqSucceeds) {
1127 bufRet.val.buffers(std::move(tmpRetBuffers));
1128 oneReqSucceeds = true;
1129 } else {
1130 allReqsSucceeds = false;
1131 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1132 StreamBuffer& hBuf = tmpRetBuffers[b];
1133 buffer_handle_t* buffer;
1134 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1135 if (res != OK) {
1136 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1137 __FUNCTION__, streamId, strerror(-res), res);
1138 }
1139 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001140 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1141 camera3_stream_buffer_t& sb = streamBuffers[b];
1142 sb.acquire_fence = -1;
1143 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1144 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001145 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1146 }
1147 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001148
1149 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1150 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1151 BufferRequestStatus::FAILED_UNKNOWN,
1152 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001153 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001154 return hardware::Void();
1155}
1156
1157hardware::Return<void> Camera3Device::returnStreamBuffers(
1158 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1159 if (!mUseHalBufManager) {
1160 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1161 __FUNCTION__, mId.string());
1162 return hardware::Void();
1163 }
1164
1165 for (const auto& buf : buffers) {
1166 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1167 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1168 continue;
1169 }
1170
1171 buffer_handle_t* buffer;
1172 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1173
1174 if (res != OK) {
1175 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1176 __FUNCTION__, buf.bufferId, buf.streamId);
1177 continue;
1178 }
1179
1180 camera3_stream_buffer_t streamBuffer;
1181 streamBuffer.buffer = buffer;
1182 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1183 streamBuffer.acquire_fence = -1;
1184 streamBuffer.release_fence = -1;
1185
1186 if (buf.releaseFence == nullptr) {
1187 streamBuffer.release_fence = -1;
1188 } else if (buf.releaseFence->numFds == 1) {
1189 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1190 } else {
1191 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1192 __FUNCTION__, buf.releaseFence->numFds);
1193 continue;
1194 }
1195
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001196 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1197 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001198 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1199 continue;
1200 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001201 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001202 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1203 }
1204 return hardware::Void();
1205}
1206
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001207hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001208 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001209 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001210 // Ideally we should grab mLock, but that can lead to deadlock, and
1211 // it's not super important to get up to date value of mStatus for this
1212 // warning print, hence skipping the lock here
1213 if (mStatus == STATUS_ERROR) {
1214 // Per API contract, HAL should act as closed after device error
1215 // But mStatus can be set to error by framework as well, so just log
1216 // a warning here.
1217 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001218 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001219
1220 if (mProcessCaptureResultLock.tryLock() != OK) {
1221 // This should never happen; it indicates a wrong client implementation
1222 // that doesn't follow the contract. But, we can be tolerant here.
1223 ALOGE("%s: callback overlapped! waiting 1s...",
1224 __FUNCTION__);
1225 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1226 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1227 __FUNCTION__);
1228 // really don't know what to do, so bail out.
1229 return hardware::Void();
1230 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001231 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001232 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001233 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001234 }
1235 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001236 return hardware::Void();
1237}
1238
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001239// Only one processCaptureResult should be called at a time, so
1240// the locks won't block. The locks are present here simply to enforce this.
1241hardware::Return<void> Camera3Device::processCaptureResult(
1242 const hardware::hidl_vec<
1243 hardware::camera::device::V3_2::CaptureResult>& results) {
1244 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1245
1246 // Ideally we should grab mLock, but that can lead to deadlock, and
1247 // it's not super important to get up to date value of mStatus for this
1248 // warning print, hence skipping the lock here
1249 if (mStatus == STATUS_ERROR) {
1250 // Per API contract, HAL should act as closed after device error
1251 // But mStatus can be set to error by framework as well, so just log
1252 // a warning here.
1253 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1254 }
1255
1256 if (mProcessCaptureResultLock.tryLock() != OK) {
1257 // This should never happen; it indicates a wrong client implementation
1258 // that doesn't follow the contract. But, we can be tolerant here.
1259 ALOGE("%s: callback overlapped! waiting 1s...",
1260 __FUNCTION__);
1261 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1262 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1263 __FUNCTION__);
1264 // really don't know what to do, so bail out.
1265 return hardware::Void();
1266 }
1267 }
1268 for (const auto& result : results) {
1269 processOneCaptureResultLocked(result, noPhysMetadata);
1270 }
1271 mProcessCaptureResultLock.unlock();
1272 return hardware::Void();
1273}
1274
1275status_t Camera3Device::readOneCameraMetadataLocked(
1276 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1277 const hardware::camera::device::V3_2::CameraMetadata& result) {
1278 if (fmqResultSize > 0) {
1279 resultMetadata.resize(fmqResultSize);
1280 if (mResultMetadataQueue == nullptr) {
1281 return NO_MEMORY; // logged in initialize()
1282 }
1283 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1284 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1285 __FUNCTION__, fmqResultSize);
1286 return INVALID_OPERATION;
1287 }
1288 } else {
1289 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1290 result.size());
1291 }
1292
1293 if (resultMetadata.size() != 0) {
1294 status_t res;
1295 const camera_metadata_t* metadata =
1296 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1297 size_t expected_metadata_size = resultMetadata.size();
1298 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1299 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1300 __FUNCTION__, strerror(-res), res);
1301 return INVALID_OPERATION;
1302 }
1303 }
1304
1305 return OK;
1306}
1307
Yifan Honga640c5a2017-04-12 16:30:31 -07001308void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001309 const hardware::camera::device::V3_2::CaptureResult& result,
1310 const hardware::hidl_vec<
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001311 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadata) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001312 camera3_capture_result r;
1313 status_t res;
1314 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001315
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001316 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001317 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001318 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1319 if (res != OK) {
1320 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1321 __FUNCTION__, result.frameNumber);
1322 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001323 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001324 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001325
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001326 // Read and validate physical camera metadata
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001327 size_t physResultCount = physicalCameraMetadata.size();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001328 std::vector<const char*> physCamIds(physResultCount);
1329 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1330 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1331 physResultMetadata.resize(physResultCount);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001332 for (size_t i = 0; i < physicalCameraMetadata.size(); i++) {
1333 res = readOneCameraMetadataLocked(physicalCameraMetadata[i].fmqMetadataSize,
1334 physResultMetadata[i], physicalCameraMetadata[i].metadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001335 if (res != OK) {
1336 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1337 __FUNCTION__, result.frameNumber,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001338 physicalCameraMetadata[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001339 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001340 }
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001341 physCamIds[i] = physicalCameraMetadata[i].physicalCameraId.c_str();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001342 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1343 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001344 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001345 r.num_physcam_metadata = physResultCount;
1346 r.physcam_ids = physCamIds.data();
1347 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001348
1349 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1350 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1351 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1352 auto& bDst = outputBuffers[i];
1353 const StreamBuffer &bSrc = result.outputBuffers[i];
1354
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001355 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1356 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001357 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1358 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001359 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001360 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001361 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001362
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001363 bool noBufferReturned = false;
1364 buffer_handle_t *buffer = nullptr;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001365 if (mUseHalBufManager) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001366 // This is suspicious most of the time but can be correct during flush where HAL
1367 // has to return capture result before a buffer is requested
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001368 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001369 if (bSrc.status == BufferStatus::OK) {
1370 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1371 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1372 // Still proceeds so other buffers can be returned
1373 }
1374 noBufferReturned = true;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001375 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001376 if (noBufferReturned) {
1377 res = OK;
1378 } else {
1379 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1380 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001381 } else {
1382 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1383 }
1384
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001385 if (res != OK) {
1386 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1387 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001388 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001389 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001390
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001391 bDst.buffer = buffer;
1392 bDst.status = mapHidlBufferStatus(bSrc.status);
1393 bDst.acquire_fence = -1;
1394 if (bSrc.releaseFence == nullptr) {
1395 bDst.release_fence = -1;
1396 } else if (bSrc.releaseFence->numFds == 1) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001397 if (noBufferReturned) {
1398 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
1399 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001400 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1401 } else {
1402 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1403 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001404 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001405 }
1406 }
1407 r.num_output_buffers = outputBuffers.size();
1408 r.output_buffers = outputBuffers.data();
1409
1410 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001411 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001412 r.input_buffer = nullptr;
1413 } else {
1414 if (mInputStream->getId() != result.inputBuffer.streamId) {
1415 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1416 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001417 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001418 }
1419 inputBuffer.stream = mInputStream->asHalStream();
1420 buffer_handle_t *buffer;
1421 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1422 &buffer);
1423 if (res != OK) {
1424 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1425 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001426 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001427 }
1428 inputBuffer.buffer = buffer;
1429 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1430 inputBuffer.acquire_fence = -1;
1431 if (result.inputBuffer.releaseFence == nullptr) {
1432 inputBuffer.release_fence = -1;
1433 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1434 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1435 } else {
1436 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1437 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001438 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001439 }
1440 r.input_buffer = &inputBuffer;
1441 }
1442
1443 r.partial_result = result.partialResult;
1444
1445 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001446}
1447
1448hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001449 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001450 // Ideally we should grab mLock, but that can lead to deadlock, and
1451 // it's not super important to get up to date value of mStatus for this
1452 // warning print, hence skipping the lock here
1453 if (mStatus == STATUS_ERROR) {
1454 // Per API contract, HAL should act as closed after device error
1455 // But mStatus can be set to error by framework as well, so just log
1456 // a warning here.
1457 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001458 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001459
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001460 for (const auto& msg : msgs) {
1461 notify(msg);
1462 }
1463 return hardware::Void();
1464}
1465
1466void Camera3Device::notify(
1467 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1468
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001469 camera3_notify_msg m;
1470 switch (msg.type) {
1471 case MsgType::ERROR:
1472 m.type = CAMERA3_MSG_ERROR;
1473 m.message.error.frame_number = msg.msg.error.frameNumber;
1474 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001475 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1476 if (stream == nullptr) {
1477 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1478 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001479 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001480 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001481 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001482 } else {
1483 m.message.error.error_stream = nullptr;
1484 }
1485 switch (msg.msg.error.errorCode) {
1486 case ErrorCode::ERROR_DEVICE:
1487 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1488 break;
1489 case ErrorCode::ERROR_REQUEST:
1490 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1491 break;
1492 case ErrorCode::ERROR_RESULT:
1493 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1494 break;
1495 case ErrorCode::ERROR_BUFFER:
1496 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1497 break;
1498 }
1499 break;
1500 case MsgType::SHUTTER:
1501 m.type = CAMERA3_MSG_SHUTTER;
1502 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1503 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1504 break;
1505 }
1506 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001507}
1508
Emilian Peevaebbe412018-01-15 13:53:24 +00001509status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001510 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001511 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001512 ATRACE_CALL();
1513
Emilian Peevaebbe412018-01-15 13:53:24 +00001514 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001515}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001516
Jianing Weicb0652e2014-03-12 18:29:36 -07001517status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1518 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001519 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001520
Emilian Peevaebbe412018-01-15 13:53:24 +00001521 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001522 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001523 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001524
Emilian Peevaebbe412018-01-15 13:53:24 +00001525 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001526 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001527}
1528
Emilian Peevaebbe412018-01-15 13:53:24 +00001529status_t Camera3Device::setStreamingRequestList(
1530 const List<const PhysicalCameraSettingsList> &requestsList,
1531 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001532 ATRACE_CALL();
1533
Emilian Peevaebbe412018-01-15 13:53:24 +00001534 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001535}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536
1537sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001538 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001539 status_t res;
1540
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001541 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001542 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1543 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001544 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1545 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001546 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001547 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001548 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001549 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001550 } else if (mStatus == STATUS_UNCONFIGURED) {
1551 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001552 CLOGE("No streams configured");
1553 return NULL;
1554 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001555 }
1556
Shuzhen Wang0129d522016-10-30 22:43:41 -07001557 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001559}
1560
Jianing Weicb0652e2014-03-12 18:29:36 -07001561status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001562 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001563 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001565
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001566 switch (mStatus) {
1567 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001568 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001569 return INVALID_OPERATION;
1570 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001571 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001573 case STATUS_UNCONFIGURED:
1574 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 case STATUS_ACTIVE:
1576 // OK
1577 break;
1578 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001579 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001580 return INVALID_OPERATION;
1581 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001582 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001583
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001584 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001585}
1586
1587status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1588 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001589 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001590
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001591 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001592}
1593
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001594status_t Camera3Device::createInputStream(
1595 uint32_t width, uint32_t height, int format, int *id) {
1596 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001597 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001598 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001599 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001600 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1601 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001602
1603 status_t res;
1604 bool wasActive = false;
1605
1606 switch (mStatus) {
1607 case STATUS_ERROR:
1608 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1609 return INVALID_OPERATION;
1610 case STATUS_UNINITIALIZED:
1611 ALOGE("%s: Device not initialized", __FUNCTION__);
1612 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001613 case STATUS_UNCONFIGURED:
1614 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001615 // OK
1616 break;
1617 case STATUS_ACTIVE:
1618 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001619 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001620 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001621 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001622 return res;
1623 }
1624 wasActive = true;
1625 break;
1626 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001627 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001628 return INVALID_OPERATION;
1629 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001630 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001631
1632 if (mInputStream != 0) {
1633 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1634 return INVALID_OPERATION;
1635 }
1636
1637 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1638 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001639 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001640
1641 mInputStream = newStream;
1642
1643 *id = mNextStreamId++;
1644
1645 // Continue captures if active at start
1646 if (wasActive) {
1647 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001648 // Reuse current operating mode and session parameters for new stream config
1649 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001650 if (res != OK) {
1651 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1652 __FUNCTION__, mNextStreamId, strerror(-res), res);
1653 return res;
1654 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001655 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001656 }
1657
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001658 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001659 return OK;
1660}
1661
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001662status_t Camera3Device::StreamSet::add(
1663 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1664 if (stream == nullptr) {
1665 ALOGE("%s: cannot add null stream", __FUNCTION__);
1666 return BAD_VALUE;
1667 }
1668 std::lock_guard<std::mutex> lock(mLock);
1669 return mData.add(streamId, stream);
1670}
1671
1672ssize_t Camera3Device::StreamSet::remove(int streamId) {
1673 std::lock_guard<std::mutex> lock(mLock);
1674 return mData.removeItem(streamId);
1675}
1676
1677sp<camera3::Camera3OutputStreamInterface>
1678Camera3Device::StreamSet::get(int streamId) {
1679 std::lock_guard<std::mutex> lock(mLock);
1680 ssize_t idx = mData.indexOfKey(streamId);
1681 if (idx == NAME_NOT_FOUND) {
1682 return nullptr;
1683 }
1684 return mData.editValueAt(idx);
1685}
1686
1687sp<camera3::Camera3OutputStreamInterface>
1688Camera3Device::StreamSet::operator[] (size_t index) {
1689 std::lock_guard<std::mutex> lock(mLock);
1690 return mData.editValueAt(index);
1691}
1692
1693size_t Camera3Device::StreamSet::size() const {
1694 std::lock_guard<std::mutex> lock(mLock);
1695 return mData.size();
1696}
1697
1698void Camera3Device::StreamSet::clear() {
1699 std::lock_guard<std::mutex> lock(mLock);
1700 return mData.clear();
1701}
1702
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001703std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1704 std::lock_guard<std::mutex> lock(mLock);
1705 std::vector<int> streamIds(mData.size());
1706 for (size_t i = 0; i < mData.size(); i++) {
1707 streamIds[i] = mData.keyAt(i);
1708 }
1709 return streamIds;
1710}
1711
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001712status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001713 uint32_t width, uint32_t height, int format,
1714 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001715 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001716 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001717 ATRACE_CALL();
1718
1719 if (consumer == nullptr) {
1720 ALOGE("%s: consumer must not be null", __FUNCTION__);
1721 return BAD_VALUE;
1722 }
1723
1724 std::vector<sp<Surface>> consumers;
1725 consumers.push_back(consumer);
1726
1727 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001728 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1729 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001730}
1731
1732status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1733 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1734 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001735 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001736 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001737 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001738
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001739 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001740 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001741 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001742 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001743 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1744 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1745 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001746
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001747 status_t res;
1748 bool wasActive = false;
1749
1750 switch (mStatus) {
1751 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001752 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001753 return INVALID_OPERATION;
1754 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001755 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001756 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001757 case STATUS_UNCONFIGURED:
1758 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001759 // OK
1760 break;
1761 case STATUS_ACTIVE:
1762 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001763 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001764 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001765 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001766 return res;
1767 }
1768 wasActive = true;
1769 break;
1770 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001771 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001772 return INVALID_OPERATION;
1773 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001774 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001775
1776 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001777
Shuzhen Wang0129d522016-10-30 22:43:41 -07001778 if (consumers.size() == 0 && !hasDeferredConsumer) {
1779 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1780 return BAD_VALUE;
1781 }
Zhijun He5d677d12016-05-29 16:52:39 -07001782
Shuzhen Wang0129d522016-10-30 22:43:41 -07001783 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001784 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1785 return BAD_VALUE;
1786 }
1787
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001788 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001789 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001790 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001791 blobBufferSize = getPointCloudBufferSize();
1792 if (blobBufferSize <= 0) {
1793 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1794 return BAD_VALUE;
1795 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001796 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1797 blobBufferSize = width * height;
1798 } else {
1799 blobBufferSize = getJpegBufferSize(width, height);
1800 if (blobBufferSize <= 0) {
1801 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1802 return BAD_VALUE;
1803 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001804 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001805 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001806 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001807 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001808 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1809 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1810 if (rawOpaqueBufferSize <= 0) {
1811 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1812 return BAD_VALUE;
1813 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001814 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001815 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001816 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001817 } else if (isShared) {
1818 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1819 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001820 mTimestampOffset, physicalCameraId, streamSetId,
1821 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001822 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001823 newStream = new Camera3OutputStream(mNextStreamId,
1824 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001825 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001826 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001827 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001828 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001829 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001830 }
Emilian Peev40ead602017-09-26 15:46:36 +01001831
1832 size_t consumerCount = consumers.size();
1833 for (size_t i = 0; i < consumerCount; i++) {
1834 int id = newStream->getSurfaceId(consumers[i]);
1835 if (id < 0) {
1836 SET_ERR_L("Invalid surface id");
1837 return BAD_VALUE;
1838 }
1839 if (surfaceIds != nullptr) {
1840 surfaceIds->push_back(id);
1841 }
1842 }
1843
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001844 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001845
Emilian Peev08dd2452017-04-06 16:55:14 +01001846 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001847
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001848 res = mOutputStreams.add(mNextStreamId, newStream);
1849 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001850 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001851 return res;
1852 }
1853
1854 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001855 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001856
1857 // Continue captures if active at start
1858 if (wasActive) {
1859 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001860 // Reuse current operating mode and session parameters for new stream config
1861 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001862 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001863 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1864 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001865 return res;
1866 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001867 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001868 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001869 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001870 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001871}
1872
Emilian Peev710c1422017-08-30 11:19:38 +01001873status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001874 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001875 if (nullptr == streamInfo) {
1876 return BAD_VALUE;
1877 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001878 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001879 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001880
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001881 switch (mStatus) {
1882 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001883 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001884 return INVALID_OPERATION;
1885 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001886 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001887 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001888 case STATUS_UNCONFIGURED:
1889 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001890 case STATUS_ACTIVE:
1891 // OK
1892 break;
1893 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001894 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001895 return INVALID_OPERATION;
1896 }
1897
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001898 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1899 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001900 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001901 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001902 }
1903
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001904 streamInfo->width = stream->getWidth();
1905 streamInfo->height = stream->getHeight();
1906 streamInfo->format = stream->getFormat();
1907 streamInfo->dataSpace = stream->getDataSpace();
1908 streamInfo->formatOverridden = stream->isFormatOverridden();
1909 streamInfo->originalFormat = stream->getOriginalFormat();
1910 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1911 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001912 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001913}
1914
1915status_t Camera3Device::setStreamTransform(int id,
1916 int transform) {
1917 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001918 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001919 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001920
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001921 switch (mStatus) {
1922 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001923 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001924 return INVALID_OPERATION;
1925 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001926 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001927 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001928 case STATUS_UNCONFIGURED:
1929 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001930 case STATUS_ACTIVE:
1931 // OK
1932 break;
1933 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001934 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001935 return INVALID_OPERATION;
1936 }
1937
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001938 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1939 if (stream == nullptr) {
1940 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001941 return BAD_VALUE;
1942 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001943 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001944}
1945
1946status_t Camera3Device::deleteStream(int id) {
1947 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001948 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001949 Mutex::Autolock l(mLock);
1950 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001951
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001952 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001953
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001954 // CameraDevice semantics require device to already be idle before
1955 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001956 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001957 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001958 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001959 }
1960
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001961 if (mStatus == STATUS_ERROR) {
1962 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1963 __FUNCTION__, mId.string());
1964 return -EBUSY;
1965 }
1966
Igor Murashkin2fba5842013-04-22 14:03:54 -07001967 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001968 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001969 if (mInputStream != NULL && id == mInputStream->getId()) {
1970 deletedStream = mInputStream;
1971 mInputStream.clear();
1972 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001973 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001974 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001975 return BAD_VALUE;
1976 }
Zhijun He5f446352014-01-22 09:49:33 -08001977 }
1978
1979 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001980 if (stream != nullptr) {
1981 deletedStream = stream;
1982 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001983 }
1984
1985 // Free up the stream endpoint so that it can be used by some other stream
1986 res = deletedStream->disconnect();
1987 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001988 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001989 // fall through since we want to still list the stream as deleted.
1990 }
1991 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001992 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001993
1994 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001995}
1996
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001997status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001998 ATRACE_CALL();
1999 ALOGV("%s: E", __FUNCTION__);
2000
2001 Mutex::Autolock il(mInterfaceLock);
2002 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07002003
Emilian Peev811d2952018-05-25 11:08:40 +01002004 // In case the client doesn't include any session parameter, try a
2005 // speculative configuration using the values from the last cached
2006 // default request.
2007 if (sessionParams.isEmpty() &&
2008 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
2009 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
2010 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
2011 mLastTemplateId);
2012 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
2013 operatingMode);
2014 }
2015
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002016 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
2017}
2018
2019status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
2020 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002021 //Filter out any incoming session parameters
2022 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002023 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
2024 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002025 CameraMetadata filteredParams(availableSessionKeys.count);
2026 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2027 filteredParams.getAndLock());
2028 set_camera_metadata_vendor_id(meta, mVendorTagId);
2029 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002030 if (availableSessionKeys.count > 0) {
2031 for (size_t i = 0; i < availableSessionKeys.count; i++) {
2032 camera_metadata_ro_entry entry = params.find(
2033 availableSessionKeys.data.i32[i]);
2034 if (entry.count > 0) {
2035 filteredParams.update(entry);
2036 }
2037 }
2038 }
2039
2040 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07002041}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002042
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002043status_t Camera3Device::getInputBufferProducer(
2044 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002045 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002046 Mutex::Autolock il(mInterfaceLock);
2047 Mutex::Autolock l(mLock);
2048
2049 if (producer == NULL) {
2050 return BAD_VALUE;
2051 } else if (mInputStream == NULL) {
2052 return INVALID_OPERATION;
2053 }
2054
2055 return mInputStream->getInputBufferProducer(producer);
2056}
2057
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002058status_t Camera3Device::createDefaultRequest(int templateId,
2059 CameraMetadata *request) {
2060 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002061 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002062
2063 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2064 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002065 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002066 return BAD_VALUE;
2067 }
2068
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002069 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002070
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002071 {
2072 Mutex::Autolock l(mLock);
2073 switch (mStatus) {
2074 case STATUS_ERROR:
2075 CLOGE("Device has encountered a serious error");
2076 return INVALID_OPERATION;
2077 case STATUS_UNINITIALIZED:
2078 CLOGE("Device is not initialized!");
2079 return INVALID_OPERATION;
2080 case STATUS_UNCONFIGURED:
2081 case STATUS_CONFIGURED:
2082 case STATUS_ACTIVE:
2083 // OK
2084 break;
2085 default:
2086 SET_ERR_L("Unexpected status: %d", mStatus);
2087 return INVALID_OPERATION;
2088 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002089
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002090 if (!mRequestTemplateCache[templateId].isEmpty()) {
2091 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002092 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002093 return OK;
2094 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002095 }
2096
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002097 camera_metadata_t *rawRequest;
2098 status_t res = mInterface->constructDefaultRequestSettings(
2099 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002100
2101 {
2102 Mutex::Autolock l(mLock);
2103 if (res == BAD_VALUE) {
2104 ALOGI("%s: template %d is not supported on this camera device",
2105 __FUNCTION__, templateId);
2106 return res;
2107 } else if (res != OK) {
2108 CLOGE("Unable to construct request template %d: %s (%d)",
2109 templateId, strerror(-res), res);
2110 return res;
2111 }
2112
2113 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2114 mRequestTemplateCache[templateId].acquire(rawRequest);
2115
2116 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002117 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002118 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002119 return OK;
2120}
2121
2122status_t Camera3Device::waitUntilDrained() {
2123 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002124 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002125 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002126 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002127
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002128 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002129}
2130
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002131status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002132 switch (mStatus) {
2133 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002134 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002135 ALOGV("%s: Already idle", __FUNCTION__);
2136 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002137 case STATUS_CONFIGURED:
2138 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002139 case STATUS_ERROR:
2140 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002141 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002142 break;
2143 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002144 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002145 return INVALID_OPERATION;
2146 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002147 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2148 maxExpectedDuration);
2149 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002150 if (res != OK) {
2151 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2152 res);
2153 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002154 return res;
2155}
2156
Ruben Brunk183f0562015-08-12 12:55:02 -07002157
2158void Camera3Device::internalUpdateStatusLocked(Status status) {
2159 mStatus = status;
2160 mRecentStatusUpdates.add(mStatus);
2161 mStatusChanged.broadcast();
2162}
2163
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002164void Camera3Device::pauseStateNotify(bool enable) {
2165 Mutex::Autolock il(mInterfaceLock);
2166 Mutex::Autolock l(mLock);
2167
2168 mPauseStateNotify = enable;
2169}
2170
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002171// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002172status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08002173 if (mRequestThread.get() != nullptr) {
2174 mRequestThread->setPaused(true);
2175 } else {
2176 return NO_INIT;
2177 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002178
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002179 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2180 maxExpectedDuration);
2181 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002182 if (res != OK) {
2183 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002184 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002185 }
2186
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002187 return res;
2188}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002189
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002190// Resume after internalPauseAndWaitLocked
2191status_t Camera3Device::internalResumeLocked() {
2192 status_t res;
2193
2194 mRequestThread->setPaused(false);
2195
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002196 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2197 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002198 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2199 if (res != OK) {
2200 SET_ERR_L("Can't transition to active in %f seconds!",
2201 kActiveTimeout/1e9);
2202 }
2203 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002204 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002205}
2206
Ruben Brunk183f0562015-08-12 12:55:02 -07002207status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002208 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002209
2210 size_t startIndex = 0;
2211 if (mStatusWaiters == 0) {
2212 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2213 // this status list
2214 mRecentStatusUpdates.clear();
2215 } else {
2216 // If other threads are waiting on updates to this status list, set the position of the
2217 // first element that this list will check rather than clearing the list.
2218 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002219 }
2220
Ruben Brunk183f0562015-08-12 12:55:02 -07002221 mStatusWaiters++;
2222
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002223 if (!active && mUseHalBufManager) {
2224 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08002225 if (mStatus == STATUS_ACTIVE) {
2226 mRequestThread->signalPipelineDrain(streamIds);
2227 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002228 mRequestBufferSM.onWaitUntilIdle();
2229 }
2230
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002231 bool stateSeen = false;
2232 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002233 if (active == (mStatus == STATUS_ACTIVE)) {
2234 // Desired state is current
2235 break;
2236 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002237
2238 res = mStatusChanged.waitRelative(mLock, timeout);
2239 if (res != OK) break;
2240
Ruben Brunk183f0562015-08-12 12:55:02 -07002241 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2242 // transitions.
2243 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2244 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2245 __FUNCTION__);
2246
2247 // Encountered desired state since we began waiting
2248 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002249 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2250 stateSeen = true;
2251 break;
2252 }
2253 }
2254 } while (!stateSeen);
2255
Ruben Brunk183f0562015-08-12 12:55:02 -07002256 mStatusWaiters--;
2257
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002258 return res;
2259}
2260
2261
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002262status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002263 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002264 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002265
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002266 if (listener != NULL && mListener != NULL) {
2267 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2268 }
2269 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002270 mRequestThread->setNotificationListener(listener);
2271 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002272
2273 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002274}
2275
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002276bool Camera3Device::willNotify3A() {
2277 return false;
2278}
2279
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002280status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002281 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002282 status_t res;
2283 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002284
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002285 while (mResultQueue.empty()) {
2286 res = mResultSignal.waitRelative(mOutputLock, timeout);
2287 if (res == TIMED_OUT) {
2288 return res;
2289 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002290 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2291 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002292 return res;
2293 }
2294 }
2295 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002296}
2297
Jianing Weicb0652e2014-03-12 18:29:36 -07002298status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002299 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002300 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002301
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002302 if (mResultQueue.empty()) {
2303 return NOT_ENOUGH_DATA;
2304 }
2305
Jianing Weicb0652e2014-03-12 18:29:36 -07002306 if (frame == NULL) {
2307 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2308 return BAD_VALUE;
2309 }
2310
2311 CaptureResult &result = *(mResultQueue.begin());
2312 frame->mResultExtras = result.mResultExtras;
2313 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002314 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002315 mResultQueue.erase(mResultQueue.begin());
2316
2317 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002318}
2319
2320status_t Camera3Device::triggerAutofocus(uint32_t id) {
2321 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002322 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002323
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002324 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2325 // Mix-in this trigger into the next request and only the next request.
2326 RequestTrigger trigger[] = {
2327 {
2328 ANDROID_CONTROL_AF_TRIGGER,
2329 ANDROID_CONTROL_AF_TRIGGER_START
2330 },
2331 {
2332 ANDROID_CONTROL_AF_TRIGGER_ID,
2333 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002334 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002335 };
2336
2337 return mRequestThread->queueTrigger(trigger,
2338 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002339}
2340
2341status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2342 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002343 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002344
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002345 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2346 // Mix-in this trigger into the next request and only the next request.
2347 RequestTrigger trigger[] = {
2348 {
2349 ANDROID_CONTROL_AF_TRIGGER,
2350 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2351 },
2352 {
2353 ANDROID_CONTROL_AF_TRIGGER_ID,
2354 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002355 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002356 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002357
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002358 return mRequestThread->queueTrigger(trigger,
2359 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002360}
2361
2362status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2363 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002364 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002365
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002366 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2367 // Mix-in this trigger into the next request and only the next request.
2368 RequestTrigger trigger[] = {
2369 {
2370 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2371 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2372 },
2373 {
2374 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2375 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002376 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002377 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002378
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002379 return mRequestThread->queueTrigger(trigger,
2380 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002381}
2382
Jianing Weicb0652e2014-03-12 18:29:36 -07002383status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002384 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002385 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002386 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002387
Zhijun He7ef20392014-04-21 16:04:17 -07002388 {
2389 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002390
2391 // b/116514106 "disconnect()" can get called twice for the same device. The
2392 // camera device will not be initialized during the second run.
2393 if (mStatus == STATUS_UNINITIALIZED) {
2394 return OK;
2395 }
2396
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002397 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002398 }
2399
Emilian Peev08dd2452017-04-06 16:55:14 +01002400 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002401}
2402
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002403status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002404 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2405}
2406
2407status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002408 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002409 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002410 Mutex::Autolock il(mInterfaceLock);
2411 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002412
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002413 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2414 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002415 CLOGE("Stream %d does not exist", streamId);
2416 return BAD_VALUE;
2417 }
2418
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002419 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002420 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002421 return BAD_VALUE;
2422 }
2423
2424 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002425 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002426 return BAD_VALUE;
2427 }
2428
Ruben Brunkc78ac262015-08-13 17:58:46 -07002429 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002430}
2431
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002432status_t Camera3Device::tearDown(int streamId) {
2433 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002434 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002435 Mutex::Autolock il(mInterfaceLock);
2436 Mutex::Autolock l(mLock);
2437
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002438 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2439 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002440 CLOGE("Stream %d does not exist", streamId);
2441 return BAD_VALUE;
2442 }
2443
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002444 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2445 CLOGE("Stream %d is a target of a in-progress request", streamId);
2446 return BAD_VALUE;
2447 }
2448
2449 return stream->tearDown();
2450}
2451
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002452status_t Camera3Device::addBufferListenerForStream(int streamId,
2453 wp<Camera3StreamBufferListener> listener) {
2454 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002455 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002456 Mutex::Autolock il(mInterfaceLock);
2457 Mutex::Autolock l(mLock);
2458
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002459 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2460 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002461 CLOGE("Stream %d does not exist", streamId);
2462 return BAD_VALUE;
2463 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002464 stream->addBufferListener(listener);
2465
2466 return OK;
2467}
2468
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002469/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002470 * Methods called by subclasses
2471 */
2472
2473void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002474 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002475 {
2476 // Need mLock to safely update state and synchronize to current
2477 // state of methods in flight.
2478 Mutex::Autolock l(mLock);
2479 // We can get various system-idle notices from the status tracker
2480 // while starting up. Only care about them if we've actually sent
2481 // in some requests recently.
2482 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2483 return;
2484 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002485 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2486 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002487 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002488
2489 // Skip notifying listener if we're doing some user-transparent
2490 // state changes
2491 if (mPauseStateNotify) return;
2492 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002493
2494 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002495 {
2496 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002497 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002498 }
2499 if (idle && listener != NULL) {
2500 listener->notifyIdle();
2501 }
2502}
2503
Shuzhen Wang758c2152017-01-10 18:26:18 -08002504status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002505 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002506 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002507 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2508 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002509
2510 if (surfaceIds == nullptr) {
2511 return BAD_VALUE;
2512 }
2513
Zhijun He5d677d12016-05-29 16:52:39 -07002514 Mutex::Autolock il(mInterfaceLock);
2515 Mutex::Autolock l(mLock);
2516
Shuzhen Wang758c2152017-01-10 18:26:18 -08002517 if (consumers.size() == 0) {
2518 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002519 return BAD_VALUE;
2520 }
2521
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002522 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2523 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002524 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002525 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002526 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002527
2528 // isConsumerConfigurationDeferred will be off after setConsumers
2529 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002530 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002531 if (res != OK) {
2532 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2533 return res;
2534 }
2535
Emilian Peev40ead602017-09-26 15:46:36 +01002536 for (auto &consumer : consumers) {
2537 int id = stream->getSurfaceId(consumer);
2538 if (id < 0) {
2539 CLOGE("Invalid surface id!");
2540 return BAD_VALUE;
2541 }
2542 surfaceIds->push_back(id);
2543 }
2544
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002545 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002546 if (!stream->isConfiguring()) {
2547 CLOGE("Stream %d was already fully configured.", streamId);
2548 return INVALID_OPERATION;
2549 }
Zhijun He5d677d12016-05-29 16:52:39 -07002550
Shuzhen Wang0129d522016-10-30 22:43:41 -07002551 res = stream->finishConfiguration();
2552 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002553 // If finishConfiguration fails due to abandoned surface, do not set
2554 // device to error state.
2555 bool isSurfaceAbandoned =
2556 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2557 if (!isSurfaceAbandoned) {
2558 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2559 stream->getId(), strerror(-res), res);
2560 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002561 return res;
2562 }
Zhijun He5d677d12016-05-29 16:52:39 -07002563 }
2564
2565 return OK;
2566}
2567
Emilian Peev40ead602017-09-26 15:46:36 +01002568status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2569 const std::vector<OutputStreamInfo> &outputInfo,
2570 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2571 Mutex::Autolock il(mInterfaceLock);
2572 Mutex::Autolock l(mLock);
2573
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002574 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2575 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002576 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002577 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002578 }
2579
2580 for (const auto &it : removedSurfaceIds) {
2581 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2582 CLOGE("Shared surface still part of a pending request!");
2583 return -EBUSY;
2584 }
2585 }
2586
Emilian Peev40ead602017-09-26 15:46:36 +01002587 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2588 if (res != OK) {
2589 CLOGE("Stream %d failed to update stream (error %d %s) ",
2590 streamId, res, strerror(-res));
2591 if (res == UNKNOWN_ERROR) {
2592 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2593 __FUNCTION__);
2594 }
2595 return res;
2596 }
2597
2598 return res;
2599}
2600
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002601status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2602 Mutex::Autolock il(mInterfaceLock);
2603 Mutex::Autolock l(mLock);
2604
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002605 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2606 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002607 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2608 return BAD_VALUE;
2609 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002610 return stream->dropBuffers(dropping);
2611}
2612
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002613/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002614 * Camera3Device private methods
2615 */
2616
2617sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002618 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002619 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002620
2621 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002622 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002623
2624 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002625 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002626 if (inputStreams.count > 0) {
2627 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002628 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002629 CLOGE("Request references unknown input stream %d",
2630 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002631 return NULL;
2632 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002633
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002634 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002635 SET_ERR_L("%s: input stream %d is not configured!",
2636 __FUNCTION__, mInputStream->getId());
2637 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002638 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002639 // Check if stream prepare is blocking requests.
2640 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002641 CLOGE("Request references an input stream that's being prepared!");
2642 return NULL;
2643 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002644
2645 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002646 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002647 }
2648
2649 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002650 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002651 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002652 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002653 return NULL;
2654 }
2655
2656 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002657 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2658 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002659 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002660 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002661 return NULL;
2662 }
Zhijun He5d677d12016-05-29 16:52:39 -07002663 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002664 auto iter = surfaceMap.find(streams.data.i32[i]);
2665 if (iter != surfaceMap.end()) {
2666 const std::vector<size_t>& surfaces = iter->second;
2667 for (const auto& surface : surfaces) {
2668 if (stream->isConsumerConfigurationDeferred(surface)) {
2669 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2670 "due to deferred consumer", stream->getId(), surface);
2671 return NULL;
2672 }
2673 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002674 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002675 }
2676
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002677 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002678 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2679 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002680 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002681 // Check if stream prepare is blocking requests.
2682 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002683 CLOGE("Request references an output stream that's being prepared!");
2684 return NULL;
2685 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002686
2687 newRequest->mOutputStreams.push(stream);
2688 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002689 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002690 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002691
2692 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002693}
2694
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002695bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2696 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2697 Size size = mSupportedOpaqueInputSizes[i];
2698 if (size.width == width && size.height == height) {
2699 return true;
2700 }
2701 }
2702
2703 return false;
2704}
2705
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002706void Camera3Device::cancelStreamsConfigurationLocked() {
2707 int res = OK;
2708 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2709 res = mInputStream->cancelConfiguration();
2710 if (res != OK) {
2711 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2712 mInputStream->getId(), strerror(-res), res);
2713 }
2714 }
2715
2716 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002717 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002718 if (outputStream->isConfiguring()) {
2719 res = outputStream->cancelConfiguration();
2720 if (res != OK) {
2721 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2722 outputStream->getId(), strerror(-res), res);
2723 }
2724 }
2725 }
2726
2727 // Return state to that at start of call, so that future configures
2728 // properly clean things up
2729 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2730 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002731
2732 res = mPreparerThread->resume();
2733 if (res != OK) {
2734 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2735 }
2736}
2737
2738bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2739 ATRACE_CALL();
2740 bool ret = false;
2741
2742 Mutex::Autolock il(mInterfaceLock);
2743 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2744
2745 Mutex::Autolock l(mLock);
2746 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2747 if (rc == NO_ERROR) {
2748 mNeedConfig = true;
2749 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2750 if (rc == NO_ERROR) {
2751 ret = true;
2752 mPauseStateNotify = false;
2753 //Moving to active state while holding 'mLock' is important.
2754 //There could be pending calls to 'create-/deleteStream' which
2755 //will trigger another stream configuration while the already
2756 //present streams end up with outstanding buffers that will
2757 //not get drained.
2758 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002759 } else if (rc == DEAD_OBJECT) {
2760 // DEAD_OBJECT can be returned if either the consumer surface is
2761 // abandoned, or the HAL has died.
2762 // - If the HAL has died, configureStreamsLocked call will set
2763 // device to error state,
2764 // - If surface is abandoned, we should not set device to error
2765 // state.
2766 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002767 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002768 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002769 }
2770 } else {
2771 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2772 }
2773
2774 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002775}
2776
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002777status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002778 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002779 ATRACE_CALL();
2780 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002781
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002782 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002783 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002784 return INVALID_OPERATION;
2785 }
2786
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002787 if (operatingMode < 0) {
2788 CLOGE("Invalid operating mode: %d", operatingMode);
2789 return BAD_VALUE;
2790 }
2791
2792 bool isConstrainedHighSpeed =
2793 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2794 operatingMode;
2795
2796 if (mOperatingMode != operatingMode) {
2797 mNeedConfig = true;
2798 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2799 mOperatingMode = operatingMode;
2800 }
2801
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002802 if (!mNeedConfig) {
2803 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2804 return OK;
2805 }
2806
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002807 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2808 // adding a dummy stream instead.
2809 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2810 if (mOutputStreams.size() == 0) {
2811 addDummyStreamLocked();
2812 } else {
2813 tryRemoveDummyStreamLocked();
2814 }
2815
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002816 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002817 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002818
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002819 mPreparerThread->pause();
2820
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002821 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002822 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002823 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2824
2825 Vector<camera3_stream_t*> streams;
2826 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002827 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002828
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002829
2830 if (mInputStream != NULL) {
2831 camera3_stream_t *inputStream;
2832 inputStream = mInputStream->startConfiguration();
2833 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002834 CLOGE("Can't start input stream configuration");
2835 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002836 return INVALID_OPERATION;
2837 }
2838 streams.add(inputStream);
2839 }
2840
2841 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002842
2843 // Don't configure bidi streams twice, nor add them twice to the list
2844 if (mOutputStreams[i].get() ==
2845 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2846
2847 config.num_streams--;
2848 continue;
2849 }
2850
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002851 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002852 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002853 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002854 CLOGE("Can't start output stream configuration");
2855 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002856 return INVALID_OPERATION;
2857 }
2858 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002859
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002860 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002861 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2862 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002863 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2864 bufferSizes[k] = static_cast<uint32_t>(
2865 getJpegBufferSize(outputStream->width, outputStream->height));
2866 } else if (outputStream->data_space ==
2867 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2868 bufferSizes[k] = outputStream->width * outputStream->height;
2869 } else {
2870 ALOGW("%s: Blob dataSpace %d not supported",
2871 __FUNCTION__, outputStream->data_space);
2872 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002873 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002874 }
2875
2876 config.streams = streams.editArray();
2877
2878 // Do the HAL configuration; will potentially touch stream
2879 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002880
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002881 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002882 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002883 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002884
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002885 if (res == BAD_VALUE) {
2886 // HAL rejected this set of streams as unsupported, clean up config
2887 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002888 CLOGE("Set of requested inputs/outputs not supported by HAL");
2889 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002890 return BAD_VALUE;
2891 } else if (res != OK) {
2892 // Some other kind of error from configure_streams - this is not
2893 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002894 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2895 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002896 return res;
2897 }
2898
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002899 // Finish all stream configuration immediately.
2900 // TODO: Try to relax this later back to lazy completion, which should be
2901 // faster
2902
Igor Murashkin073f8572013-05-02 14:59:28 -07002903 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002904 bool streamReConfigured = false;
2905 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002906 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002907 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002908 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002909 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002910 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2911 return DEAD_OBJECT;
2912 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002913 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002914 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002915 if (streamReConfigured) {
2916 mInterface->onStreamReConfigured(mInputStream->getId());
2917 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002918 }
2919
2920 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002921 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002922 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002923 bool streamReConfigured = false;
2924 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002925 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002926 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002927 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002928 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002929 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2930 return DEAD_OBJECT;
2931 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002932 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002933 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002934 if (streamReConfigured) {
2935 mInterface->onStreamReConfigured(outputStream->getId());
2936 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002937 }
2938 }
2939
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002940 // Request thread needs to know to avoid using repeat-last-settings protocol
2941 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002942 if (notifyRequestThread) {
2943 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2944 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002945
Zhijun He90f7c372016-08-16 16:19:43 -07002946 char value[PROPERTY_VALUE_MAX];
2947 property_get("camera.fifo.disable", value, "0");
2948 int32_t disableFifo = atoi(value);
2949 if (disableFifo != 1) {
2950 // Boost priority of request thread to SCHED_FIFO.
2951 pid_t requestThreadTid = mRequestThread->getTid();
2952 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002953 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002954 if (res != OK) {
2955 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2956 strerror(-res), res);
2957 } else {
2958 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2959 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002960 }
2961
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002962 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002963 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2964 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2965 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2966 sessionParams.unlock(newSessionParams);
2967 mSessionParams.unlock(currentSessionParams);
2968 if (updateSessionParams) {
2969 mSessionParams = sessionParams;
2970 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002971
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002972 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002973
Ruben Brunk183f0562015-08-12 12:55:02 -07002974 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2975 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002976
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002977 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002978
Zhijun He0a210512014-07-24 13:45:15 -07002979 // tear down the deleted streams after configure streams.
2980 mDeletedStreams.clear();
2981
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002982 auto rc = mPreparerThread->resume();
2983 if (rc != OK) {
2984 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2985 return rc;
2986 }
2987
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002988 if (mDummyStreamId == NO_STREAM) {
2989 mRequestBufferSM.onStreamsConfigured();
2990 }
2991
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002992 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002993}
2994
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002995status_t Camera3Device::addDummyStreamLocked() {
2996 ATRACE_CALL();
2997 status_t res;
2998
2999 if (mDummyStreamId != NO_STREAM) {
3000 // Should never be adding a second dummy stream when one is already
3001 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003002 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
3003 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003004 return INVALID_OPERATION;
3005 }
3006
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003007 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003008
3009 sp<Camera3OutputStreamInterface> dummyStream =
3010 new Camera3DummyStream(mNextStreamId);
3011
3012 res = mOutputStreams.add(mNextStreamId, dummyStream);
3013 if (res < 0) {
3014 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
3015 return res;
3016 }
3017
3018 mDummyStreamId = mNextStreamId;
3019 mNextStreamId++;
3020
3021 return OK;
3022}
3023
3024status_t Camera3Device::tryRemoveDummyStreamLocked() {
3025 ATRACE_CALL();
3026 status_t res;
3027
3028 if (mDummyStreamId == NO_STREAM) return OK;
3029 if (mOutputStreams.size() == 1) return OK;
3030
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003031 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003032
3033 // Ok, have a dummy stream and there's at least one other output stream,
3034 // so remove the dummy
3035
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003036 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
3037 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003038 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3039 return INVALID_OPERATION;
3040 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003041 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003042
3043 // Free up the stream endpoint so that it can be used by some other stream
3044 res = deletedStream->disconnect();
3045 if (res != OK) {
3046 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3047 // fall through since we want to still list the stream as deleted.
3048 }
3049 mDeletedStreams.add(deletedStream);
3050 mDummyStreamId = NO_STREAM;
3051
3052 return res;
3053}
3054
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003055void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003056 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003057 Mutex::Autolock l(mLock);
3058 va_list args;
3059 va_start(args, fmt);
3060
3061 setErrorStateLockedV(fmt, args);
3062
3063 va_end(args);
3064}
3065
3066void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003067 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003068 Mutex::Autolock l(mLock);
3069 setErrorStateLockedV(fmt, args);
3070}
3071
3072void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3073 va_list args;
3074 va_start(args, fmt);
3075
3076 setErrorStateLockedV(fmt, args);
3077
3078 va_end(args);
3079}
3080
3081void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003082 // Print out all error messages to log
3083 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003084 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003085
3086 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003087 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003088
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003089 mErrorCause = errorCause;
3090
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003091 if (mRequestThread != nullptr) {
3092 mRequestThread->setPaused(true);
3093 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003094 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003095
3096 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003097 sp<NotificationListener> listener = mListener.promote();
3098 if (listener != NULL) {
3099 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003100 CaptureResultExtras());
3101 }
3102
3103 // Save stack trace. View by dumping it later.
3104 CameraTraces::saveTrace();
3105 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003106}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003107
3108/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003109 * In-flight request management
3110 */
3111
Jianing Weicb0652e2014-03-12 18:29:36 -07003112status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003113 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003114 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003115 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003116 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003117 ATRACE_CALL();
3118 Mutex::Autolock l(mInFlightLock);
3119
3120 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003121 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003122 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3123 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003124 if (res < 0) return res;
3125
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003126 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003127 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3128 // avoid a deadlock during reprocess requests.
3129 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003130 if (mStatusTracker != nullptr) {
3131 mStatusTracker->markComponentActive(mInFlightStatusId);
3132 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003133 }
3134
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003135 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003136 return OK;
3137}
3138
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003139void Camera3Device::returnOutputBuffers(
3140 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003141 nsecs_t timestamp, bool timestampIncreasing,
3142 const SurfaceMap& outputSurfaces,
3143 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003144
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003145 for (size_t i = 0; i < numBuffers; i++)
3146 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003147 if (outputBuffers[i].buffer == nullptr) {
3148 if (!mUseHalBufManager) {
3149 // With HAL buffer management API, HAL sometimes will have to return buffers that
3150 // has not got a output buffer handle filled yet. This is though illegal if HAL
3151 // buffer management API is not being used.
3152 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3153 }
3154 continue;
3155 }
3156
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003157 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3158 int streamId = stream->getId();
3159 const auto& it = outputSurfaces.find(streamId);
3160 status_t res = OK;
3161 if (it != outputSurfaces.end()) {
3162 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003163 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3164 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003165 } else {
3166 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003167 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3168 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003169 }
3170
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003171 // Note: stream may be deallocated at this point, if this buffer was
3172 // the last reference to it.
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003173 if (res == NO_INIT || res == DEAD_OBJECT) {
3174 ALOGV("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
3175 } else if (res != OK) {
3176 ALOGE("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003177 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003178
3179 // Long processing consumers can cause returnBuffer timeout for shared stream
3180 // If that happens, cancel the buffer and send a buffer error to client
3181 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3182 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3183 // cancel the buffer
3184 camera3_stream_buffer_t sb = outputBuffers[i];
3185 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003186 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3187 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003188
3189 // notify client buffer error
3190 sp<NotificationListener> listener;
3191 {
3192 Mutex::Autolock l(mOutputLock);
3193 listener = mListener.promote();
3194 }
3195
3196 if (listener != nullptr) {
3197 CaptureResultExtras extras = inResultExtras;
3198 extras.errorStreamId = streamId;
3199 listener->notifyError(
3200 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3201 extras);
3202 }
3203 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003204 }
3205}
3206
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003207void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003208 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003209 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003210 mInFlightMap.removeItemsAt(idx, 1);
3211
3212 // Indicate idle inFlightMap to the status tracker
3213 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003214 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003215 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3216 // avoid a deadlock during reprocess requests.
3217 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003218 if (mStatusTracker != nullptr) {
3219 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3220 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003221 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003222 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003223}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003224
3225void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3226
3227 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3228 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3229
3230 nsecs_t sensorTimestamp = request.sensorTimestamp;
3231 nsecs_t shutterTimestamp = request.shutterTimestamp;
3232
3233 // Check if it's okay to remove the request from InFlightMap:
3234 // In the case of a successful request:
3235 // all input and output buffers, all result metadata, shutter callback
3236 // arrived.
3237 // In the case of a unsuccessful request:
3238 // all input and output buffers arrived.
3239 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003240 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003241 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003242 if (request.stillCapture) {
3243 ATRACE_ASYNC_END("still capture", frameNumber);
3244 }
3245
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003246 ATRACE_ASYNC_END("frame capture", frameNumber);
3247
Shuzhen Wang403044a2017-02-26 23:29:04 -08003248 // Sanity check - if sensor timestamp matches shutter timestamp in the
3249 // case of request having callback.
3250 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003251 sensorTimestamp != shutterTimestamp) {
3252 SET_ERR("sensor timestamp (%" PRId64
3253 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3254 sensorTimestamp, frameNumber, shutterTimestamp);
3255 }
3256
3257 // for an unsuccessful request, it may have pending output buffers to
3258 // return.
3259 assert(request.requestStatus != OK ||
3260 request.pendingOutputBuffers.size() == 0);
3261 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003262 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3263 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003264
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003265 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003266 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3267 }
3268
3269 // Sanity check - if we have too many in-flight frames, something has
3270 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003271 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003272 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003273 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3274 kInFlightWarnLimitHighSpeed) {
3275 CLOGE("In-flight list too large for high speed configuration: %zu",
3276 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003277 }
3278}
3279
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003280void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003281 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003282 { // First return buffers cached in mInFlightMap
3283 Mutex::Autolock l(mInFlightLock);
3284 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3285 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3286 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003287 request.pendingOutputBuffers.size(), 0,
3288 /*timestampIncreasing*/true, request.outputSurfaces,
3289 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003290 }
3291 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003292 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003293 }
3294
3295 // Then return all inflight buffers not returned by HAL
3296 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3297 mInterface->getInflightBufferKeys(&inflightKeys);
3298
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003299 // Inflight buffers for HAL buffer manager
3300 std::vector<uint64_t> inflightRequestBufferKeys;
3301 mInterface->getInflightRequestBufferKeys(&inflightRequestBufferKeys);
3302
3303 // (streamId, frameNumber, buffer_handle_t*) tuple for all inflight buffers.
3304 // frameNumber will be -1 for buffers from HAL buffer manager
3305 std::vector<std::tuple<int32_t, int32_t, buffer_handle_t*>> inflightBuffers;
3306 inflightBuffers.reserve(inflightKeys.size() + inflightRequestBufferKeys.size());
3307
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003308 for (auto& pair : inflightKeys) {
3309 int32_t frameNumber = pair.first;
3310 int32_t streamId = pair.second;
3311 buffer_handle_t* buffer;
3312 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3313 if (res != OK) {
3314 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3315 __FUNCTION__, frameNumber, streamId);
3316 continue;
3317 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003318 inflightBuffers.push_back(std::make_tuple(streamId, frameNumber, buffer));
3319 }
3320
3321 for (auto& bufferId : inflightRequestBufferKeys) {
3322 int32_t streamId = -1;
3323 buffer_handle_t* buffer = nullptr;
3324 status_t res = mInterface->popInflightRequestBuffer(bufferId, &buffer, &streamId);
3325 if (res != OK) {
3326 ALOGE("%s: cannot find in-flight buffer %" PRIu64, __FUNCTION__, bufferId);
3327 continue;
3328 }
3329 inflightBuffers.push_back(std::make_tuple(streamId, /*frameNumber*/-1, buffer));
3330 }
3331
3332 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3333 for (auto& tuple : inflightBuffers) {
3334 status_t res = OK;
3335 int32_t streamId = std::get<0>(tuple);
3336 int32_t frameNumber = std::get<1>(tuple);
3337 buffer_handle_t* buffer = std::get<2>(tuple);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003338
3339 camera3_stream_buffer_t streamBuffer;
3340 streamBuffer.buffer = buffer;
3341 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3342 streamBuffer.acquire_fence = -1;
3343 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003344
3345 // First check if the buffer belongs to deleted stream
3346 bool streamDeleted = false;
3347 for (auto& stream : mDeletedStreams) {
3348 if (streamId == stream->getId()) {
3349 streamDeleted = true;
3350 // Return buffer to deleted stream
3351 camera3_stream* halStream = stream->asHalStream();
3352 streamBuffer.stream = halStream;
3353 switch (halStream->stream_type) {
3354 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003355 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3356 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003357 if (res != OK) {
3358 ALOGE("%s: Can't return output buffer for frame %d to"
3359 " stream %d: %s (%d)", __FUNCTION__,
3360 frameNumber, streamId, strerror(-res), res);
3361 }
3362 break;
3363 case CAMERA3_STREAM_INPUT:
3364 res = stream->returnInputBuffer(streamBuffer);
3365 if (res != OK) {
3366 ALOGE("%s: Can't return input buffer for frame %d to"
3367 " stream %d: %s (%d)", __FUNCTION__,
3368 frameNumber, streamId, strerror(-res), res);
3369 }
3370 break;
3371 default: // Bi-direcitonal stream is deprecated
3372 ALOGE("%s: stream %d has unknown stream type %d",
3373 __FUNCTION__, streamId, halStream->stream_type);
3374 break;
3375 }
3376 break;
3377 }
3378 }
3379 if (streamDeleted) {
3380 continue;
3381 }
3382
3383 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003384 if (streamId == inputStreamId) {
3385 streamBuffer.stream = mInputStream->asHalStream();
3386 res = mInputStream->returnInputBuffer(streamBuffer);
3387 if (res != OK) {
3388 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003389 " stream %d: %s (%d)", __FUNCTION__,
3390 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003391 }
3392 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003393 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3394 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003395 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3396 continue;
3397 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003398 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003399 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3400 }
3401 }
3402}
3403
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003404void Camera3Device::insertResultLocked(CaptureResult *result,
3405 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003406 if (result == nullptr) return;
3407
Emilian Peev71c73a22017-03-21 16:35:51 +00003408 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3409 result->mMetadata.getAndLock());
3410 set_camera_metadata_vendor_id(meta, mVendorTagId);
3411 result->mMetadata.unlock(meta);
3412
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003413 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3414 (int32_t*)&frameNumber, 1) != OK) {
3415 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3416 return;
3417 }
3418
3419 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3420 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3421 return;
3422 }
3423
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003424 // Update vendor tag id for physical metadata
3425 for (auto& physicalMetadata : result->mPhysicalMetadatas) {
3426 camera_metadata_t *pmeta = const_cast<camera_metadata_t *>(
3427 physicalMetadata.mPhysicalCameraMetadata.getAndLock());
3428 set_camera_metadata_vendor_id(pmeta, mVendorTagId);
3429 physicalMetadata.mPhysicalCameraMetadata.unlock(pmeta);
3430 }
3431
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003432 // Valid result, insert into queue
3433 List<CaptureResult>::iterator queuedResult =
3434 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3435 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3436 ", burstId = %" PRId32, __FUNCTION__,
3437 queuedResult->mResultExtras.requestId,
3438 queuedResult->mResultExtras.frameNumber,
3439 queuedResult->mResultExtras.burstId);
3440
3441 mResultSignal.signal();
3442}
3443
3444
3445void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003446 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003447 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003448 Mutex::Autolock l(mOutputLock);
3449
3450 CaptureResult captureResult;
3451 captureResult.mResultExtras = resultExtras;
3452 captureResult.mMetadata = partialResult;
3453
Shuzhen Wang268a1362018-10-16 16:32:59 -07003454 // Fix up result metadata for monochrome camera.
3455 status_t 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
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003461 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003462}
3463
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003464
3465void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3466 CaptureResultExtras &resultExtras,
3467 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003468 uint32_t frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003469 bool reprocess, bool zslStillCapture,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003470 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003471 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003472 if (pendingMetadata.isEmpty())
3473 return;
3474
3475 Mutex::Autolock l(mOutputLock);
3476
3477 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003478 if (reprocess) {
3479 if (frameNumber < mNextReprocessResultFrameNumber) {
3480 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003481 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003482 frameNumber, mNextReprocessResultFrameNumber);
3483 return;
3484 }
3485 mNextReprocessResultFrameNumber = frameNumber + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003486 } else if (zslStillCapture) {
3487 if (frameNumber < mNextZslStillResultFrameNumber) {
3488 SET_ERR("Out-of-order ZSL still capture result metadata submitted! "
3489 "(got frame number %d, expecting %d)",
3490 frameNumber, mNextZslStillResultFrameNumber);
3491 return;
3492 }
3493 mNextZslStillResultFrameNumber = frameNumber + 1;
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003494 } else {
3495 if (frameNumber < mNextResultFrameNumber) {
3496 SET_ERR("Out-of-order capture result metadata submitted! "
3497 "(got frame number %d, expecting %d)",
3498 frameNumber, mNextResultFrameNumber);
3499 return;
3500 }
3501 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003502 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003503
3504 CaptureResult captureResult;
3505 captureResult.mResultExtras = resultExtras;
3506 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003507 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003508
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003509 // Append any previous partials to form a complete result
3510 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3511 captureResult.mMetadata.append(collectedPartialResult);
3512 }
3513
3514 captureResult.mMetadata.sort();
3515
3516 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003517 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3518 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003519 SET_ERR("No timestamp provided by HAL for frame %d!",
3520 frameNumber);
3521 return;
3522 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003523 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3524 camera_metadata_entry timestamp =
3525 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3526 if (timestamp.count == 0) {
3527 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3528 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3529 return;
3530 }
3531 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003532
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003533 // Fix up some result metadata to account for HAL-level distortion correction
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003534 status_t res =
3535 mDistortionMappers[mId.c_str()].correctCaptureResult(&captureResult.mMetadata);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003536 if (res != OK) {
3537 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3538 frameNumber, strerror(res), res);
3539 return;
3540 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003541 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3542 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3543 if (mDistortionMappers.find(cameraId8.c_str()) == mDistortionMappers.end()) {
3544 continue;
3545 }
3546 res = mDistortionMappers[cameraId8.c_str()].correctCaptureResult(
3547 &physicalMetadata.mPhysicalCameraMetadata);
3548 if (res != OK) {
3549 SET_ERR("Unable to correct physical capture result metadata for frame %d: %s (%d)",
3550 frameNumber, strerror(res), res);
3551 return;
3552 }
3553 }
3554
Shuzhen Wang268a1362018-10-16 16:32:59 -07003555 // Fix up result metadata for monochrome camera.
3556 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3557 if (res != OK) {
3558 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3559 return;
3560 }
3561 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3562 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3563 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3564 physicalMetadata.mPhysicalCameraMetadata);
3565 if (res != OK) {
3566 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3567 return;
3568 }
3569 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003570
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003571 std::unordered_map<std::string, CameraMetadata> monitoredPhysicalMetadata;
3572 for (auto& m : physicalMetadatas) {
3573 monitoredPhysicalMetadata.emplace(String8(m.mPhysicalCameraId).string(),
3574 CameraMetadata(m.mPhysicalCameraMetadata));
3575 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003576 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003577 frameNumber, timestamp.data.i64[0], captureResult.mMetadata,
3578 monitoredPhysicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003579
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003580 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003581}
3582
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003583/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003584 * Camera HAL device callback methods
3585 */
3586
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003587void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003588 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003589
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003590 status_t res;
3591
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003592 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003593 if (result->result == NULL && result->num_output_buffers == 0 &&
3594 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003595 SET_ERR("No result data provided by HAL for frame %d",
3596 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003597 return;
3598 }
Zhijun He204e3292014-07-14 17:09:23 -07003599
Zhijun He204e3292014-07-14 17:09:23 -07003600 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003601 result->result != NULL &&
3602 result->partial_result != 1) {
3603 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3604 " if partial result is not supported",
3605 frameNumber, result->partial_result);
3606 return;
3607 }
3608
3609 bool isPartialResult = false;
3610 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003611 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003612
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003613 // Get shutter timestamp and resultExtras from list of in-flight requests,
3614 // where it was added by the shutter notification for this frame. If the
3615 // shutter timestamp isn't received yet, append the output buffers to the
3616 // in-flight request and they will be returned when the shutter timestamp
3617 // arrives. Update the in-flight status and remove the in-flight entry if
3618 // all result data and shutter timestamp have been received.
3619 nsecs_t shutterTimestamp = 0;
3620
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003621 {
3622 Mutex::Autolock l(mInFlightLock);
3623 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3624 if (idx == NAME_NOT_FOUND) {
3625 SET_ERR("Unknown frame number for capture result: %d",
3626 frameNumber);
3627 return;
3628 }
3629 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003630 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3631 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003632 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003633 __FUNCTION__, request.resultExtras.requestId,
3634 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003635 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003636 // Always update the partial count to the latest one if it's not 0
3637 // (buffers only). When framework aggregates adjacent partial results
3638 // into one, the latest partial count will be used.
3639 if (result->partial_result != 0)
3640 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003641
3642 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003643 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003644 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3645 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3646 " the range of [1, %d] when metadata is included in the result",
3647 frameNumber, result->partial_result, mNumPartialResults);
3648 return;
3649 }
3650 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003651 if (isPartialResult && result->num_physcam_metadata) {
3652 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3653 " physical camera result", frameNumber);
3654 return;
3655 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003656 if (isPartialResult) {
3657 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003658 }
3659
Shuzhen Wang4a472662017-02-26 23:29:04 -08003660 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003661 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003662 sendPartialCaptureResult(result->result, request.resultExtras,
3663 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003664 }
3665 }
3666
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003667 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003668 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003669
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003670 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003671 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003672 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3673 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3674 request.physicalCameraIds.size(), result->num_physcam_metadata);
3675 return;
3676 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003677 if (request.haveResultMetadata) {
3678 SET_ERR("Called multiple times with metadata for frame %d",
3679 frameNumber);
3680 return;
3681 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003682 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3683 String8 physicalId(result->physcam_ids[i]);
3684 std::set<String8>::iterator cameraIdIter =
3685 request.physicalCameraIds.find(physicalId);
3686 if (cameraIdIter != request.physicalCameraIds.end()) {
3687 request.physicalCameraIds.erase(cameraIdIter);
3688 } else {
3689 SET_ERR("Total result for frame %d has already returned for camera %s",
3690 frameNumber, physicalId.c_str());
3691 return;
3692 }
3693 }
Zhijun He204e3292014-07-14 17:09:23 -07003694 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003695 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003696 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003697 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003698 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003699 request.haveResultMetadata = true;
3700 }
3701
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003702 uint32_t numBuffersReturned = result->num_output_buffers;
3703 if (result->input_buffer != NULL) {
3704 if (hasInputBufferInRequest) {
3705 numBuffersReturned += 1;
3706 } else {
3707 ALOGW("%s: Input buffer should be NULL if there is no input"
3708 " buffer sent in the request",
3709 __FUNCTION__);
3710 }
3711 }
3712 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003713 if (request.numBuffersLeft < 0) {
3714 SET_ERR("Too many buffers returned for frame %d",
3715 frameNumber);
3716 return;
3717 }
3718
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003719 camera_metadata_ro_entry_t entry;
3720 res = find_camera_metadata_ro_entry(result->result,
3721 ANDROID_SENSOR_TIMESTAMP, &entry);
3722 if (res == OK && entry.count == 1) {
3723 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003724 }
3725
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003726 // If shutter event isn't received yet, append the output buffers to
3727 // the in-flight request. Otherwise, return the output buffers to
3728 // streams.
3729 if (shutterTimestamp == 0) {
3730 request.pendingOutputBuffers.appendArray(result->output_buffers,
3731 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003732 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003733 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003734 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003735 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3736 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003737 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003738
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003739 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003740 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3741 CameraMetadata physicalMetadata;
3742 physicalMetadata.append(result->physcam_metadata[i]);
3743 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3744 physicalMetadata});
3745 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003746 if (shutterTimestamp == 0) {
3747 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003748 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003749 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003750 CameraMetadata metadata;
3751 metadata = result->result;
3752 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003753 collectedPartialResult, frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003754 hasInputBufferInRequest, request.zslCapture && request.stillCapture,
3755 request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003756 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003757 }
3758
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003759 removeInFlightRequestIfReadyLocked(idx);
3760 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003761
Zhijun Hef0d962a2014-06-30 10:24:11 -07003762 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003763 if (hasInputBufferInRequest) {
3764 Camera3Stream *stream =
3765 Camera3Stream::cast(result->input_buffer->stream);
3766 res = stream->returnInputBuffer(*(result->input_buffer));
3767 // Note: stream may be deallocated at this point, if this buffer was the
3768 // last reference to it.
3769 if (res != OK) {
3770 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3771 " its stream:%s (%d)", __FUNCTION__,
3772 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003773 }
3774 } else {
3775 ALOGW("%s: Input buffer should be NULL if there is no input"
3776 " buffer sent in the request, skipping input buffer return.",
3777 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003778 }
3779 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003780}
3781
3782void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003783 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003784 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003785 {
3786 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003787 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003788 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003789
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003790 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003791 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003792 return;
3793 }
3794
3795 switch (msg->type) {
3796 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003797 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003798 break;
3799 }
3800 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003801 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003802 break;
3803 }
3804 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003805 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003806 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003807 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003808}
3809
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003810void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003811 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003812 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003813 // Map camera HAL error codes to ICameraDeviceCallback error codes
3814 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003815 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003816 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003817 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003818 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003819 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003820 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003821 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003822 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003823 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003824 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003825 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003826 };
3827
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003828 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003829 ((msg.error_code >= 0) &&
3830 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3831 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003832 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003833
3834 int streamId = 0;
Emilian Peevedec62d2019-03-19 17:59:24 -07003835 String16 physicalCameraId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003836 if (msg.error_stream != NULL) {
3837 Camera3Stream *stream =
3838 Camera3Stream::cast(msg.error_stream);
3839 streamId = stream->getId();
Emilian Peevedec62d2019-03-19 17:59:24 -07003840 physicalCameraId = String16(stream->physicalCameraId());
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003841 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003842 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3843 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003844 streamId, msg.error_code);
3845
3846 CaptureResultExtras resultExtras;
3847 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003848 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003849 // SET_ERR calls notifyError
3850 SET_ERR("Camera HAL reported serious device error");
3851 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003852 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3853 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3854 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003855 {
3856 Mutex::Autolock l(mInFlightLock);
3857 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3858 if (idx >= 0) {
3859 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3860 r.requestStatus = msg.error_code;
3861 resultExtras = r.resultExtras;
Emilian Peevedec62d2019-03-19 17:59:24 -07003862 bool logicalDeviceResultError = false;
3863 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3864 errorCode) {
3865 if (physicalCameraId.size() > 0) {
3866 String8 cameraId(physicalCameraId);
3867 if (r.physicalCameraIds.find(cameraId) == r.physicalCameraIds.end()) {
3868 ALOGE("%s: Reported result failure for physical camera device: %s "
3869 " which is not part of the respective request!",
3870 __FUNCTION__, cameraId.string());
3871 break;
3872 }
3873 resultExtras.errorPhysicalCameraId = physicalCameraId;
3874 } else {
3875 logicalDeviceResultError = true;
3876 }
3877 }
3878
3879 if (logicalDeviceResultError
Shuzhen Wang20f57342017-08-24 15:39:05 -07003880 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3881 errorCode) {
3882 r.skipResultMetadata = true;
3883 }
Emilian Peevedec62d2019-03-19 17:59:24 -07003884 if (logicalDeviceResultError) {
Emilian Peevba0fac32017-03-30 09:05:34 +01003885 // In case of missing result check whether the buffers
3886 // returned. If they returned, then remove inflight
3887 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003888 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3889 // otherwise we are depending on HAL to send the buffers back after
3890 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003891 removeInFlightRequestIfReadyLocked(idx);
3892 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003893 } else {
3894 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003895 ALOGE("Camera %s: %s: cannot find in-flight request on "
3896 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003897 resultExtras.frameNumber);
3898 }
3899 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003900 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003901 if (listener != NULL) {
3902 listener->notifyError(errorCode, resultExtras);
3903 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003904 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003905 }
3906 break;
3907 default:
3908 // SET_ERR calls notifyError
3909 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3910 break;
3911 }
3912}
3913
3914void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003915 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003916 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003917 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003918
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003919 // Set timestamp for the request in the in-flight tracking
3920 // and get the request ID to send upstream
3921 {
3922 Mutex::Autolock l(mInFlightLock);
3923 idx = mInFlightMap.indexOfKey(msg.frame_number);
3924 if (idx >= 0) {
3925 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003926
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003927 // Verify ordering of shutter notifications
3928 {
3929 Mutex::Autolock l(mOutputLock);
3930 // TODO: need to track errors for tighter bounds on expected frame number.
3931 if (r.hasInputBuffer) {
3932 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003933 SET_ERR("Reprocess shutter notification out-of-order. Expected "
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003934 "notification for frame %d, got frame %d",
3935 mNextReprocessShutterFrameNumber, msg.frame_number);
3936 return;
3937 }
3938 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003939 } else if (r.zslCapture && r.stillCapture) {
3940 if (msg.frame_number < mNextZslStillShutterFrameNumber) {
3941 SET_ERR("ZSL still capture shutter notification out-of-order. Expected "
3942 "notification for frame %d, got frame %d",
3943 mNextZslStillShutterFrameNumber, msg.frame_number);
3944 return;
3945 }
3946 mNextZslStillShutterFrameNumber = msg.frame_number + 1;
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003947 } else {
3948 if (msg.frame_number < mNextShutterFrameNumber) {
3949 SET_ERR("Shutter notification out-of-order. Expected "
3950 "notification for frame %d, got frame %d",
3951 mNextShutterFrameNumber, msg.frame_number);
3952 return;
3953 }
3954 mNextShutterFrameNumber = msg.frame_number + 1;
3955 }
3956 }
3957
Shuzhen Wang4a472662017-02-26 23:29:04 -08003958 r.shutterTimestamp = msg.timestamp;
3959 if (r.hasCallback) {
3960 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003961 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003962 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003963 // Call listener, if any
3964 if (listener != NULL) {
3965 listener->notifyShutter(r.resultExtras, msg.timestamp);
3966 }
3967 // send pending result and buffers
3968 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3969 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003970 r.hasInputBuffer, r.zslCapture && r.stillCapture,
3971 r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003972 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003973 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003974 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003975 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3976 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003977 r.pendingOutputBuffers.clear();
3978
3979 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003980 }
3981 }
3982 if (idx < 0) {
3983 SET_ERR("Shutter notification for non-existent frame number %d",
3984 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003985 }
3986}
3987
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003988CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003989 ALOGV("%s", __FUNCTION__);
3990
Igor Murashkin1e479c02013-09-06 16:55:14 -07003991 CameraMetadata retVal;
3992
3993 if (mRequestThread != NULL) {
3994 retVal = mRequestThread->getLatestRequest();
3995 }
3996
Igor Murashkin1e479c02013-09-06 16:55:14 -07003997 return retVal;
3998}
3999
Jianing Weicb0652e2014-03-12 18:29:36 -07004000
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004001void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004002 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
4003 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
4004
4005 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
4006 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004007}
4008
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004009/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004010 * HalInterface inner class methods
4011 */
4012
Yifan Hongf79b5542017-04-11 14:44:25 -07004013Camera3Device::HalInterface::HalInterface(
4014 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004015 std::shared_ptr<RequestMetadataQueue> queue,
4016 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004017 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004018 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08004019 mUseHalBufManager(useHalBufManager),
4020 mIsReconfigurationQuerySupported(true) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004021 // Check with hardware service manager if we can downcast these interfaces
4022 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004023 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
4024 if (castResult_3_5.isOk()) {
4025 mHidlSession_3_5 = castResult_3_5;
4026 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004027 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4028 if (castResult_3_4.isOk()) {
4029 mHidlSession_3_4 = castResult_3_4;
4030 }
4031 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
4032 if (castResult_3_3.isOk()) {
4033 mHidlSession_3_3 = castResult_3_3;
4034 }
4035}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004036
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004037Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004038
4039Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004040 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004041 mRequestMetadataQueue(other.mRequestMetadataQueue),
4042 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004043
4044bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004045 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004046}
4047
4048void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00004049 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00004050 mHidlSession_3_4.clear();
4051 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004052 mHidlSession.clear();
4053}
4054
4055status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
4056 camera3_request_template_t templateId,
4057 /*out*/ camera_metadata_t **requestTemplate) {
4058 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
4059 if (!valid()) return INVALID_OPERATION;
4060 status_t res = OK;
4061
Emilian Peev31abd0a2017-05-11 18:37:46 +01004062 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004063
4064 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01004065 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004066 status = s;
4067 if (status == common::V1_0::Status::OK) {
4068 const camera_metadata *r =
4069 reinterpret_cast<const camera_metadata_t*>(request.data());
4070 size_t expectedSize = request.size();
4071 int ret = validate_camera_metadata_structure(r, &expectedSize);
4072 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
4073 *requestTemplate = clone_camera_metadata(r);
4074 if (*requestTemplate == nullptr) {
4075 ALOGE("%s: Unable to clone camera metadata received from HAL",
4076 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004077 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004078 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004079 } else {
4080 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
4081 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004082 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004083 }
4084 };
4085 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004086 RequestTemplate id;
4087 switch (templateId) {
4088 case CAMERA3_TEMPLATE_PREVIEW:
4089 id = RequestTemplate::PREVIEW;
4090 break;
4091 case CAMERA3_TEMPLATE_STILL_CAPTURE:
4092 id = RequestTemplate::STILL_CAPTURE;
4093 break;
4094 case CAMERA3_TEMPLATE_VIDEO_RECORD:
4095 id = RequestTemplate::VIDEO_RECORD;
4096 break;
4097 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
4098 id = RequestTemplate::VIDEO_SNAPSHOT;
4099 break;
4100 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
4101 id = RequestTemplate::ZERO_SHUTTER_LAG;
4102 break;
4103 case CAMERA3_TEMPLATE_MANUAL:
4104 id = RequestTemplate::MANUAL;
4105 break;
4106 default:
4107 // Unknown template ID, or this HAL is too old to support it
4108 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004109 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004110 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004111
Emilian Peev31abd0a2017-05-11 18:37:46 +01004112 if (!err.isOk()) {
4113 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4114 res = DEAD_OBJECT;
4115 } else {
4116 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004117 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004118
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004119 return res;
4120}
4121
Emilian Peev4ec17882019-01-24 17:16:58 -08004122bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4123 CameraMetadata& newSessionParams) {
4124 // We do reconfiguration by default;
4125 bool ret = true;
4126 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4127 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4128 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4129 oldSessionParams.getAndLock());
4130 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4131 newSessionParams.getAndLock());
4132 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4133 get_camera_metadata_size(oldSessioMeta));
4134 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4135 get_camera_metadata_size(newSessioMeta));
4136 hardware::camera::common::V1_0::Status callStatus;
4137 bool required;
4138 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4139 bool requiredFlag) {
4140 callStatus = s;
4141 required = requiredFlag;
4142 };
4143 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4144 oldSessionParams.unlock(oldSessioMeta);
4145 newSessionParams.unlock(newSessioMeta);
4146 if (err.isOk()) {
4147 switch (callStatus) {
4148 case hardware::camera::common::V1_0::Status::OK:
4149 ret = required;
4150 break;
4151 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4152 mIsReconfigurationQuerySupported = false;
4153 ret = true;
4154 break;
4155 default:
4156 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4157 ret = true;
4158 }
4159 } else {
4160 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4161 ret = true;
4162 }
4163 }
4164
4165 return ret;
4166}
4167
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004168status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004169 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004170 ATRACE_NAME("CameraHal::configureStreams");
4171 if (!valid()) return INVALID_OPERATION;
4172 status_t res = OK;
4173
Emilian Peev31abd0a2017-05-11 18:37:46 +01004174 // Convert stream config to HIDL
4175 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004176 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4177 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4178 requestedConfiguration3_2.streams.resize(config->num_streams);
4179 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004180 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004181 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4182 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004183 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004184
Emilian Peev31abd0a2017-05-11 18:37:46 +01004185 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4186 cam3stream->setBufferFreedListener(this);
4187 int streamId = cam3stream->getId();
4188 StreamType streamType;
4189 switch (src->stream_type) {
4190 case CAMERA3_STREAM_OUTPUT:
4191 streamType = StreamType::OUTPUT;
4192 break;
4193 case CAMERA3_STREAM_INPUT:
4194 streamType = StreamType::INPUT;
4195 break;
4196 default:
4197 ALOGE("%s: Stream %d: Unsupported stream type %d",
4198 __FUNCTION__, streamId, config->streams[i]->stream_type);
4199 return BAD_VALUE;
4200 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004201 dst3_2.id = streamId;
4202 dst3_2.streamType = streamType;
4203 dst3_2.width = src->width;
4204 dst3_2.height = src->height;
4205 dst3_2.format = mapToPixelFormat(src->format);
4206 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
4207 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4208 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
4209 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004210 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004211 if (src->physical_camera_id != nullptr) {
4212 dst3_4.physicalCameraId = src->physical_camera_id;
4213 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004214
4215 activeStreams.insert(streamId);
4216 // Create Buffer ID map if necessary
4217 if (mBufferIdMaps.count(streamId) == 0) {
4218 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4219 }
4220 }
4221 // remove BufferIdMap for deleted streams
4222 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4223 int streamId = it->first;
4224 bool active = activeStreams.count(streamId) > 0;
4225 if (!active) {
4226 it = mBufferIdMaps.erase(it);
4227 } else {
4228 ++it;
4229 }
4230 }
4231
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004232 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004233 res = mapToStreamConfigurationMode(
4234 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004235 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004236 if (res != OK) {
4237 return res;
4238 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004239 requestedConfiguration3_2.operationMode = operationMode;
4240 requestedConfiguration3_4.operationMode = operationMode;
4241 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004242 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4243 get_camera_metadata_size(sessionParams));
4244
Emilian Peev31abd0a2017-05-11 18:37:46 +01004245 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004246 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004247 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004248 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004249
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004250 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004251 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4252 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004253 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004254 };
4255
4256 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4257 (hardware::Return<void>& err) -> status_t {
4258 if (!err.isOk()) {
4259 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4260 return DEAD_OBJECT;
4261 }
4262 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4263 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4264 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4265 }
4266 return OK;
4267 };
4268
4269 // See if we have v3.4 or v3.3 HAL
4270 if (mHidlSession_3_5 != nullptr) {
4271 ALOGV("%s: v3.5 device found", __FUNCTION__);
4272 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4273 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4274 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4275 auto err = mHidlSession_3_5->configureStreams_3_5(
4276 requestedConfiguration3_5, configStream34Cb);
4277 res = postprocConfigStream34(err);
4278 if (res != OK) {
4279 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004280 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004281 } else if (mHidlSession_3_4 != nullptr) {
4282 // We do; use v3.4 for the call
4283 ALOGV("%s: v3.4 device found", __FUNCTION__);
4284 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
4285 auto err = mHidlSession_3_4->configureStreams_3_4(
4286 requestedConfiguration3_4, configStream34Cb);
4287 res = postprocConfigStream34(err);
4288 if (res != OK) {
4289 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004290 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004291 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004292 // We do; use v3.3 for the call
4293 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004294 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004295 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004296 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004297 finalConfiguration = halConfiguration;
4298 status = s;
4299 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004300 if (!err.isOk()) {
4301 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4302 return DEAD_OBJECT;
4303 }
4304 } else {
4305 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4306 ALOGV("%s: v3.2 device found", __FUNCTION__);
4307 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004308 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004309 [&status, &finalConfiguration_3_2]
4310 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4311 finalConfiguration_3_2 = halConfiguration;
4312 status = s;
4313 });
4314 if (!err.isOk()) {
4315 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4316 return DEAD_OBJECT;
4317 }
4318 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4319 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4320 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4321 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004322 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004323 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004324 }
4325
4326 if (status != common::V1_0::Status::OK ) {
4327 return CameraProviderManager::mapToStatusT(status);
4328 }
4329
4330 // And convert output stream configuration from HIDL
4331
4332 for (size_t i = 0; i < config->num_streams; i++) {
4333 camera3_stream_t *dst = config->streams[i];
4334 int streamId = Camera3Stream::cast(dst)->getId();
4335
4336 // Start scan at i, with the assumption that the stream order matches
4337 size_t realIdx = i;
4338 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004339 size_t halStreamCount = finalConfiguration.streams.size();
4340 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004341 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004342 found = true;
4343 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004344 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004345 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004346 }
4347 if (!found) {
4348 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4349 __FUNCTION__, streamId);
4350 return INVALID_OPERATION;
4351 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004352 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004353
Emilian Peev710c1422017-08-30 11:19:38 +01004354 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4355 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004356 dstStream->setDataSpaceOverride(false);
4357 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4358 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4359
Emilian Peev31abd0a2017-05-11 18:37:46 +01004360 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4361 if (dst->format != overrideFormat) {
4362 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4363 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004364 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004365 if (dst->data_space != overrideDataSpace) {
4366 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4367 streamId, dst->format);
4368 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004369 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004370 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004371 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4372
Emilian Peev31abd0a2017-05-11 18:37:46 +01004373 // Override allowed with IMPLEMENTATION_DEFINED
4374 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004375 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004376 }
4377
Emilian Peev31abd0a2017-05-11 18:37:46 +01004378 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004379 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004380 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004381 __FUNCTION__, streamId);
4382 return INVALID_OPERATION;
4383 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004384 dstStream->setUsage(
4385 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004386 } else {
4387 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004388 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004389 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4390 __FUNCTION__, streamId);
4391 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004392 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004393 dstStream->setUsage(
4394 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004395 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004396 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004397 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004398
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004399 return res;
4400}
4401
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004402status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004403 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004404 /*out*/std::vector<native_handle_t*>* handlesCreated,
4405 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004406 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004407 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
4408 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
4409 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004410 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004411 }
4412
4413 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004414
4415 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004416
4417 {
4418 std::lock_guard<std::mutex> lock(mInflightLock);
4419 if (request->input_buffer != nullptr) {
4420 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4421 buffer_handle_t buf = *(request->input_buffer->buffer);
4422 auto pair = getBufferId(buf, streamId);
4423 bool isNewBuffer = pair.first;
4424 uint64_t bufferId = pair.second;
4425 captureRequest->inputBuffer.streamId = streamId;
4426 captureRequest->inputBuffer.bufferId = bufferId;
4427 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4428 captureRequest->inputBuffer.status = BufferStatus::OK;
4429 native_handle_t *acquireFence = nullptr;
4430 if (request->input_buffer->acquire_fence != -1) {
4431 acquireFence = native_handle_create(1,0);
4432 acquireFence->data[0] = request->input_buffer->acquire_fence;
4433 handlesCreated->push_back(acquireFence);
4434 }
4435 captureRequest->inputBuffer.acquireFence = acquireFence;
4436 captureRequest->inputBuffer.releaseFence = nullptr;
4437
4438 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004439 request->input_buffer->buffer);
4440 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004441 } else {
4442 captureRequest->inputBuffer.streamId = -1;
4443 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4444 }
4445
4446 captureRequest->outputBuffers.resize(request->num_output_buffers);
4447 for (size_t i = 0; i < request->num_output_buffers; i++) {
4448 const camera3_stream_buffer_t *src = request->output_buffers + i;
4449 StreamBuffer &dst = captureRequest->outputBuffers[i];
4450 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004451 if (src->buffer != nullptr) {
4452 buffer_handle_t buf = *(src->buffer);
4453 auto pair = getBufferId(buf, streamId);
4454 bool isNewBuffer = pair.first;
4455 dst.bufferId = pair.second;
4456 dst.buffer = isNewBuffer ? buf : nullptr;
4457 native_handle_t *acquireFence = nullptr;
4458 if (src->acquire_fence != -1) {
4459 acquireFence = native_handle_create(1,0);
4460 acquireFence->data[0] = src->acquire_fence;
4461 handlesCreated->push_back(acquireFence);
4462 }
4463 dst.acquireFence = acquireFence;
4464 } else if (mUseHalBufManager) {
4465 // HAL buffer management path
4466 dst.bufferId = BUFFER_ID_NO_BUFFER;
4467 dst.buffer = nullptr;
4468 dst.acquireFence = nullptr;
4469 } else {
4470 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4471 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004472 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004473 dst.streamId = streamId;
4474 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004475 dst.releaseFence = nullptr;
4476
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004477 // Output buffers are empty when using HAL buffer manager
4478 if (!mUseHalBufManager) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004479 pushInflightBufferLocked(captureRequest->frameNumber, streamId, src->buffer);
4480 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004481 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004482 }
4483 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004484 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004485}
4486
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004487void Camera3Device::HalInterface::cleanupNativeHandles(
4488 std::vector<native_handle_t*> *handles, bool closeFd) {
4489 if (handles == nullptr) {
4490 return;
4491 }
4492 if (closeFd) {
4493 for (auto& handle : *handles) {
4494 native_handle_close(handle);
4495 }
4496 }
4497 for (auto& handle : *handles) {
4498 native_handle_delete(handle);
4499 }
4500 handles->clear();
4501 return;
4502}
4503
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004504status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4505 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4506 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4507 if (!valid()) return INVALID_OPERATION;
4508
Emilian Peevaebbe412018-01-15 13:53:24 +00004509 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4510 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4511 if (castResult_3_4.isOk()) {
4512 hidlSession_3_4 = castResult_3_4;
4513 }
4514
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004515 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004516 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004517 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004518 if (hidlSession_3_4 != nullptr) {
4519 captureRequests_3_4.resize(batchSize);
4520 } else {
4521 captureRequests.resize(batchSize);
4522 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004523 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004524 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004525
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004526 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004527 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004528 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004529 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004530 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00004531 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004532 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
4533 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004534 }
4535 if (res != OK) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004536 popInflightBuffers(inflightBuffers);
4537 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004538 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004539 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004540 }
4541
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004542 std::vector<device::V3_2::BufferCache> cachesToRemove;
4543 {
4544 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4545 for (auto& pair : mFreedBuffers) {
4546 // The stream might have been removed since onBufferFreed
4547 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4548 cachesToRemove.push_back({pair.first, pair.second});
4549 }
4550 }
4551 mFreedBuffers.clear();
4552 }
4553
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004554 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4555 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004556
4557 // Write metadata to FMQ.
4558 for (size_t i = 0; i < batchSize; i++) {
4559 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004560 device::V3_2::CaptureRequest* captureRequest;
4561 if (hidlSession_3_4 != nullptr) {
4562 captureRequest = &captureRequests_3_4[i].v3_2;
4563 } else {
4564 captureRequest = &captureRequests[i];
4565 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004566
4567 if (request->settings != nullptr) {
4568 size_t settingsSize = get_camera_metadata_size(request->settings);
4569 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4570 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4571 captureRequest->settings.resize(0);
4572 captureRequest->fmqSettingsSize = settingsSize;
4573 } else {
4574 if (mRequestMetadataQueue != nullptr) {
4575 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4576 }
4577 captureRequest->settings.setToExternal(
4578 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4579 get_camera_metadata_size(request->settings));
4580 captureRequest->fmqSettingsSize = 0u;
4581 }
4582 } else {
4583 // A null request settings maps to a size-0 CameraMetadata
4584 captureRequest->settings.resize(0);
4585 captureRequest->fmqSettingsSize = 0u;
4586 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004587
4588 if (hidlSession_3_4 != nullptr) {
4589 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4590 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004591 if (request->physcam_settings != nullptr) {
4592 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4593 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4594 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4595 settingsSize)) {
4596 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4597 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4598 settingsSize;
4599 } else {
4600 if (mRequestMetadataQueue != nullptr) {
4601 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4602 }
4603 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4604 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4605 request->physcam_settings[j])),
4606 get_camera_metadata_size(request->physcam_settings[j]));
4607 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004608 }
Emilian Peev00420d22018-02-05 21:33:13 +00004609 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004610 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004611 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004612 }
4613 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4614 request->physcam_id[j];
4615 }
4616 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004617 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004618
4619 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004620 auto resultCallback =
4621 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4622 status = s;
4623 *numRequestProcessed = n;
4624 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004625 if (hidlSession_3_4 != nullptr) {
4626 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004627 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004628 } else {
4629 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004630 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004631 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004632 if (!err.isOk()) {
4633 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004634 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004635 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004636
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004637 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4638 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4639 __FUNCTION__, *numRequestProcessed, batchSize);
4640 status = common::V1_0::Status::INTERNAL_ERROR;
4641 }
4642
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004643 res = CameraProviderManager::mapToStatusT(status);
4644 if (res == OK) {
4645 if (mHidlSession->isRemote()) {
4646 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
4647 // sent to camera HAL processes)
4648 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
4649 } else {
4650 // In passthrough mode the FDs are now owned by HAL
4651 cleanupNativeHandles(&handlesCreated);
4652 }
4653 } else {
4654 popInflightBuffers(inflightBuffers);
4655 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004656 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004657 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004658}
4659
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004660status_t Camera3Device::HalInterface::flush() {
4661 ATRACE_NAME("CameraHal::flush");
4662 if (!valid()) return INVALID_OPERATION;
4663 status_t res = OK;
4664
Emilian Peev31abd0a2017-05-11 18:37:46 +01004665 auto err = mHidlSession->flush();
4666 if (!err.isOk()) {
4667 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4668 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004669 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004670 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004671 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004672
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004673 return res;
4674}
4675
Emilian Peev31abd0a2017-05-11 18:37:46 +01004676status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004677 ATRACE_NAME("CameraHal::dump");
4678 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004679
Emilian Peev31abd0a2017-05-11 18:37:46 +01004680 // Handled by CameraProviderManager::dump
4681
4682 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004683}
4684
4685status_t Camera3Device::HalInterface::close() {
4686 ATRACE_NAME("CameraHal::close()");
4687 if (!valid()) return INVALID_OPERATION;
4688 status_t res = OK;
4689
Emilian Peev31abd0a2017-05-11 18:37:46 +01004690 auto err = mHidlSession->close();
4691 // Interface will be dead shortly anyway, so don't log errors
4692 if (!err.isOk()) {
4693 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004694 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004695
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004696 return res;
4697}
4698
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004699void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4700 ATRACE_NAME("CameraHal::signalPipelineDrain");
4701 if (!valid() || mHidlSession_3_5 == nullptr) {
4702 ALOGE("%s called on invalid camera!", __FUNCTION__);
4703 return;
4704 }
4705
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004706 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004707 if (!err.isOk()) {
4708 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4709 return;
4710 }
4711}
4712
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004713void Camera3Device::HalInterface::getInflightBufferKeys(
4714 std::vector<std::pair<int32_t, int32_t>>* out) {
4715 std::lock_guard<std::mutex> lock(mInflightLock);
4716 out->clear();
4717 out->reserve(mInflightBufferMap.size());
4718 for (auto& pair : mInflightBufferMap) {
4719 uint64_t key = pair.first;
4720 int32_t streamId = key & 0xFFFFFFFF;
4721 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4722 out->push_back(std::make_pair(frameNumber, streamId));
4723 }
4724 return;
4725}
4726
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004727void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4728 std::vector<uint64_t>* out) {
4729 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4730 out->clear();
4731 out->reserve(mRequestedBuffers.size());
4732 for (auto& pair : mRequestedBuffers) {
4733 out->push_back(pair.first);
4734 }
4735 return;
4736}
4737
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004738status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004739 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004740 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004741 mInflightBufferMap[key] = buffer;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004742 return OK;
4743}
4744
4745status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004746 int32_t frameNumber, int32_t streamId,
4747 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004748 std::lock_guard<std::mutex> lock(mInflightLock);
4749
4750 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4751 auto it = mInflightBufferMap.find(key);
4752 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004753 if (buffer != nullptr) {
4754 *buffer = it->second;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004755 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004756 mInflightBufferMap.erase(it);
4757 return OK;
4758}
4759
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004760void Camera3Device::HalInterface::popInflightBuffers(
4761 const std::vector<std::pair<int32_t, int32_t>>& buffers) {
4762 for (const auto& pair : buffers) {
4763 int32_t frameNumber = pair.first;
4764 int32_t streamId = pair.second;
4765 popInflightBuffer(frameNumber, streamId, nullptr);
4766 }
4767}
4768
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004769status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004770 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004771 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004772 auto pair = mRequestedBuffers.insert({bufferId, {streamId, buf}});
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004773 if (!pair.second) {
4774 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4775 __FUNCTION__, bufferId);
4776 return BAD_VALUE;
4777 }
4778 return OK;
4779}
4780
4781// Find and pop a buffer_handle_t based on bufferId
4782status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004783 uint64_t bufferId,
4784 /*out*/ buffer_handle_t** buffer,
4785 /*optional out*/ int32_t* streamId) {
4786 if (buffer == nullptr) {
4787 ALOGE("%s: buffer (%p) must not be null", __FUNCTION__, buffer);
4788 return BAD_VALUE;
4789 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004790 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4791 auto it = mRequestedBuffers.find(bufferId);
4792 if (it == mRequestedBuffers.end()) {
4793 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4794 __FUNCTION__, bufferId);
4795 return BAD_VALUE;
4796 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004797 *buffer = it->second.second;
4798 if (streamId != nullptr) {
4799 *streamId = it->second.first;
4800 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004801 mRequestedBuffers.erase(it);
4802 return OK;
4803}
4804
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004805std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4806 const buffer_handle_t& buf, int streamId) {
4807 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4808
4809 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4810 auto it = bIdMap.find(buf);
4811 if (it == bIdMap.end()) {
4812 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004813 ALOGV("stream %d now have %zu buffer caches, buf %p",
4814 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004815 return std::make_pair(true, mNextBufferId - 1);
4816 } else {
4817 return std::make_pair(false, it->second);
4818 }
4819}
4820
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004821void Camera3Device::HalInterface::onBufferFreed(
4822 int streamId, const native_handle_t* handle) {
4823 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4824 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4825 auto mapIt = mBufferIdMaps.find(streamId);
4826 if (mapIt == mBufferIdMaps.end()) {
4827 // streamId might be from a deleted stream here
4828 ALOGI("%s: stream %d has been removed",
4829 __FUNCTION__, streamId);
4830 return;
4831 }
4832 BufferIdMap& bIdMap = mapIt->second;
4833 auto it = bIdMap.find(handle);
4834 if (it == bIdMap.end()) {
4835 ALOGW("%s: cannot find buffer %p in stream %d",
4836 __FUNCTION__, handle, streamId);
4837 return;
4838 } else {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004839 bufferId = it->second;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004840 bIdMap.erase(it);
4841 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4842 __FUNCTION__, streamId, bIdMap.size(), handle);
4843 }
4844 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4845}
4846
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004847void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
4848 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4849 auto mapIt = mBufferIdMaps.find(streamId);
4850 if (mapIt == mBufferIdMaps.end()) {
4851 ALOGE("%s: streamId %d not found!", __FUNCTION__, streamId);
4852 return;
4853 }
4854
4855 BufferIdMap& bIdMap = mapIt->second;
4856 for (const auto& it : bIdMap) {
4857 uint64_t bufferId = it.second;
4858 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4859 }
4860 bIdMap.clear();
4861}
4862
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004863/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004864 * RequestThread inner class methods
4865 */
4866
4867Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004868 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004869 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4870 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004871 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004872 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004873 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004874 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004875 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004876 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004877 mReconfigured(false),
4878 mDoPause(false),
4879 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004880 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004881 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004882 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004883 mCurrentAfTriggerId(0),
4884 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004885 mRepeatingLastFrameNumber(
4886 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004887 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004888 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004889 mRequestLatency(kRequestLatencyBinSize),
4890 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004891 mLatestSessionParams(sessionParamKeys.size()),
4892 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004893 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004894}
4895
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004896Camera3Device::RequestThread::~RequestThread() {}
4897
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004898void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004899 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004900 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004901 Mutex::Autolock l(mRequestLock);
4902 mListener = listener;
4903}
4904
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004905void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4906 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004907 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004908 Mutex::Autolock l(mRequestLock);
4909 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004910 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004911 // Prepare video stream for high speed recording.
4912 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004913 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004914}
4915
Jianing Wei90e59c92014-03-12 18:29:36 -07004916status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004917 List<sp<CaptureRequest> > &requests,
4918 /*out*/
4919 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004920 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004921 Mutex::Autolock l(mRequestLock);
4922 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4923 ++it) {
4924 mRequestQueue.push_back(*it);
4925 }
4926
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004927 if (lastFrameNumber != NULL) {
4928 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4929 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4930 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4931 *lastFrameNumber);
4932 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004933
Jianing Wei90e59c92014-03-12 18:29:36 -07004934 unpauseForNewRequests();
4935
4936 return OK;
4937}
4938
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004939
4940status_t Camera3Device::RequestThread::queueTrigger(
4941 RequestTrigger trigger[],
4942 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004943 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004944 Mutex::Autolock l(mTriggerMutex);
4945 status_t ret;
4946
4947 for (size_t i = 0; i < count; ++i) {
4948 ret = queueTriggerLocked(trigger[i]);
4949
4950 if (ret != OK) {
4951 return ret;
4952 }
4953 }
4954
4955 return OK;
4956}
4957
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004958const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4959 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004960 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004961 if (d != nullptr) return d->mId;
4962 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004963}
4964
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004965status_t Camera3Device::RequestThread::queueTriggerLocked(
4966 RequestTrigger trigger) {
4967
4968 uint32_t tag = trigger.metadataTag;
4969 ssize_t index = mTriggerMap.indexOfKey(tag);
4970
4971 switch (trigger.getTagType()) {
4972 case TYPE_BYTE:
4973 // fall-through
4974 case TYPE_INT32:
4975 break;
4976 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004977 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4978 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004979 return INVALID_OPERATION;
4980 }
4981
4982 /**
4983 * Collect only the latest trigger, since we only have 1 field
4984 * in the request settings per trigger tag, and can't send more than 1
4985 * trigger per request.
4986 */
4987 if (index != NAME_NOT_FOUND) {
4988 mTriggerMap.editValueAt(index) = trigger;
4989 } else {
4990 mTriggerMap.add(tag, trigger);
4991 }
4992
4993 return OK;
4994}
4995
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004996status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004997 const RequestList &requests,
4998 /*out*/
4999 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005000 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005001 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005002 if (lastFrameNumber != NULL) {
5003 *lastFrameNumber = mRepeatingLastFrameNumber;
5004 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005005 mRepeatingRequests.clear();
5006 mRepeatingRequests.insert(mRepeatingRequests.begin(),
5007 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005008
5009 unpauseForNewRequests();
5010
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005011 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005012 return OK;
5013}
5014
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07005015bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005016 if (mRepeatingRequests.empty()) {
5017 return false;
5018 }
5019 int32_t requestId = requestIn->mResultExtras.requestId;
5020 const RequestList &repeatRequests = mRepeatingRequests;
5021 // All repeating requests are guaranteed to have same id so only check first quest
5022 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
5023 return (firstRequest->mResultExtras.requestId == requestId);
5024}
5025
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005026status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005027 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005028 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005029 return clearRepeatingRequestsLocked(lastFrameNumber);
5030
5031}
5032
5033status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005034 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005035 if (lastFrameNumber != NULL) {
5036 *lastFrameNumber = mRepeatingLastFrameNumber;
5037 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005038 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005039 return OK;
5040}
5041
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005042status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005043 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005044 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005045 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005046 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005047
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005048 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005049
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005050 // Send errors for all requests pending in the request queue, including
5051 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005052 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005053 if (listener != NULL) {
5054 for (RequestList::iterator it = mRequestQueue.begin();
5055 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005056 // Abort the input buffers for reprocess requests.
5057 if ((*it)->mInputStream != NULL) {
5058 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07005059 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
5060 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005061 if (res != OK) {
5062 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
5063 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5064 } else {
5065 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
5066 if (res != OK) {
5067 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
5068 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5069 }
5070 }
5071 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005072 // Set the frame number this request would have had, if it
5073 // had been submitted; this frame number will not be reused.
5074 // The requestId and burstId fields were set when the request was
5075 // submitted originally (in convertMetadataListToRequestListLocked)
5076 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005077 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005078 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005079 }
5080 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005081 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08005082
5083 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005084 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005085 if (lastFrameNumber != NULL) {
5086 *lastFrameNumber = mRepeatingLastFrameNumber;
5087 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005088 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005089 return OK;
5090}
5091
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005092status_t Camera3Device::RequestThread::flush() {
5093 ATRACE_CALL();
5094 Mutex::Autolock l(mFlushLock);
5095
Emilian Peev08dd2452017-04-06 16:55:14 +01005096 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005097}
5098
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005099void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005100 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005101 Mutex::Autolock l(mPauseLock);
5102 mDoPause = paused;
5103 mDoPauseSignal.signal();
5104}
5105
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005106status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
5107 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005108 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005109 Mutex::Autolock l(mLatestRequestMutex);
5110 status_t res;
5111 while (mLatestRequestId != requestId) {
5112 nsecs_t startTime = systemTime();
5113
5114 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
5115 if (res != OK) return res;
5116
5117 timeout -= (systemTime() - startTime);
5118 }
5119
5120 return OK;
5121}
5122
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005123void Camera3Device::RequestThread::requestExit() {
5124 // Call parent to set up shutdown
5125 Thread::requestExit();
5126 // The exit from any possible waits
5127 mDoPauseSignal.signal();
5128 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07005129
5130 mRequestLatency.log("ProcessCaptureRequest latency histogram");
5131 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005132}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005133
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005134void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005135 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005136 bool surfaceAbandoned = false;
5137 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005138 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005139 {
5140 Mutex::Autolock l(mRequestLock);
5141 // Check all streams needed by repeating requests are still valid. Otherwise, stop
5142 // repeating requests.
5143 for (const auto& request : mRepeatingRequests) {
5144 for (const auto& s : request->mOutputStreams) {
5145 if (s->isAbandoned()) {
5146 surfaceAbandoned = true;
5147 clearRepeatingRequestsLocked(&lastFrameNumber);
5148 break;
5149 }
5150 }
5151 if (surfaceAbandoned) {
5152 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005153 }
5154 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005155 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005156 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005157
5158 if (listener != NULL && surfaceAbandoned) {
5159 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005160 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005161}
5162
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005163bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005164 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005165 status_t res;
5166 size_t batchSize = mNextRequests.size();
5167 std::vector<camera3_capture_request_t*> requests(batchSize);
5168 uint32_t numRequestProcessed = 0;
5169 for (size_t i = 0; i < batchSize; i++) {
5170 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07005171 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005172 }
5173
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005174 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
5175
5176 bool triggerRemoveFailed = false;
5177 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
5178 for (size_t i = 0; i < numRequestProcessed; i++) {
5179 NextRequest& nextRequest = mNextRequests.editItemAt(i);
5180 nextRequest.submitted = true;
5181
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005182 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00005183
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005184 if (!triggerRemoveFailed) {
5185 // Remove any previously queued triggers (after unlock)
5186 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5187 if (removeTriggerRes != OK) {
5188 triggerRemoveFailed = true;
5189 triggerFailedRequest = nextRequest;
5190 }
5191 }
5192 }
5193
5194 if (triggerRemoveFailed) {
5195 SET_ERR("RequestThread: Unable to remove triggers "
5196 "(capture request %d, HAL device: %s (%d)",
5197 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5198 cleanUpFailedRequests(/*sendRequestError*/ false);
5199 return false;
5200 }
5201
5202 if (res != OK) {
5203 // Should only get a failure here for malformed requests or device-level
5204 // errors, so consider all errors fatal. Bad metadata failures should
5205 // come through notify.
5206 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5207 mNextRequests[numRequestProcessed].halRequest.frame_number,
5208 strerror(-res), res);
5209 cleanUpFailedRequests(/*sendRequestError*/ false);
5210 return false;
5211 }
5212 return true;
5213}
5214
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005215nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5216 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5217 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5218 find_camera_metadata_ro_entry(request,
5219 ANDROID_CONTROL_AE_MODE,
5220 &e);
5221 if (e.count == 0) return maxExpectedDuration;
5222
5223 switch (e.data.u8[0]) {
5224 case ANDROID_CONTROL_AE_MODE_OFF:
5225 find_camera_metadata_ro_entry(request,
5226 ANDROID_SENSOR_EXPOSURE_TIME,
5227 &e);
5228 if (e.count > 0) {
5229 maxExpectedDuration = e.data.i64[0];
5230 }
5231 find_camera_metadata_ro_entry(request,
5232 ANDROID_SENSOR_FRAME_DURATION,
5233 &e);
5234 if (e.count > 0) {
5235 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5236 }
5237 break;
5238 default:
5239 find_camera_metadata_ro_entry(request,
5240 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5241 &e);
5242 if (e.count > 1) {
5243 maxExpectedDuration = 1e9 / e.data.u8[0];
5244 }
5245 break;
5246 }
5247
5248 return maxExpectedDuration;
5249}
5250
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005251bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5252 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5253 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5254 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5255 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5256 return true;
5257 }
5258
5259 return false;
5260}
5261
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005262void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
5263 // Update the latest request sent to HAL
5264 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5265 Mutex::Autolock al(mLatestRequestMutex);
5266
5267 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5268 mLatestRequest.acquire(cloned);
5269
5270 mLatestPhysicalRequest.clear();
5271 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
5272 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
5273 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
5274 CameraMetadata(cloned));
5275 }
5276
5277 sp<Camera3Device> parent = mParent.promote();
5278 if (parent != NULL) {
5279 parent->monitorMetadata(TagMonitor::REQUEST,
5280 nextRequest.halRequest.frame_number,
5281 0, mLatestRequest, mLatestPhysicalRequest);
5282 }
5283 }
5284
5285 if (nextRequest.halRequest.settings != NULL) {
5286 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5287 nextRequest.halRequest.settings);
5288 }
5289
5290 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5291}
5292
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005293bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5294 ATRACE_CALL();
5295 bool updatesDetected = false;
5296
Emilian Peev4ec17882019-01-24 17:16:58 -08005297 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005298 for (auto tag : mSessionParamKeys) {
5299 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005300 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005301
5302 if (entry.count > 0) {
5303 bool isDifferent = false;
5304 if (lastEntry.count > 0) {
5305 // Have a last value, compare to see if changed
5306 if (lastEntry.type == entry.type &&
5307 lastEntry.count == entry.count) {
5308 // Same type and count, compare values
5309 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5310 size_t entryBytes = bytesPerValue * lastEntry.count;
5311 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5312 if (cmp != 0) {
5313 isDifferent = true;
5314 }
5315 } else {
5316 // Count or type has changed
5317 isDifferent = true;
5318 }
5319 } else {
5320 // No last entry, so always consider to be different
5321 isDifferent = true;
5322 }
5323
5324 if (isDifferent) {
5325 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005326 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5327 updatesDetected = true;
5328 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005329 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005330 }
5331 } else if (lastEntry.count > 0) {
5332 // Value has been removed
5333 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005334 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005335 updatesDetected = true;
5336 }
5337 }
5338
Emilian Peev4ec17882019-01-24 17:16:58 -08005339 bool reconfigureRequired;
5340 if (updatesDetected) {
5341 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5342 updatedParams);
5343 mLatestSessionParams = updatedParams;
5344 } else {
5345 reconfigureRequired = false;
5346 }
5347
5348 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005349}
5350
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005351bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005352 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005353 status_t res;
5354
5355 // Handle paused state.
5356 if (waitIfPaused()) {
5357 return true;
5358 }
5359
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005360 // Wait for the next batch of requests.
5361 waitForNextRequestBatch();
5362 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005363 return true;
5364 }
5365
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005366 // Get the latest request ID, if any
5367 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005368 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005369 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005370 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005371 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005372 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005373 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5374 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005375 }
5376
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005377 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5378 // or a single request from streaming or burst. In either case the first element
5379 // should contain the latest camera settings that we need to check for any session
5380 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005381 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005382 res = OK;
5383
5384 //Input stream buffers are already acquired at this point so an input stream
5385 //will not be able to move to idle state unless we force it.
5386 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5387 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5388 if (res != OK) {
5389 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5390 cleanUpFailedRequests(/*sendRequestError*/ false);
5391 return false;
5392 }
5393 }
5394
5395 if (res == OK) {
5396 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5397 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005398 sp<Camera3Device> parent = mParent.promote();
5399 if (parent != nullptr) {
5400 parent->pauseStateNotify(true);
5401 }
5402
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005403 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5404
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005405 if (parent != nullptr) {
5406 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5407 }
5408
5409 statusTracker->markComponentActive(mStatusId);
5410 setPaused(false);
5411 }
5412
5413 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5414 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5415 if (res != OK) {
5416 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5417 cleanUpFailedRequests(/*sendRequestError*/ false);
5418 return false;
5419 }
5420 }
5421 }
5422 }
5423
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005424 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005425 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005426 if (res == TIMED_OUT) {
5427 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005428 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005429 // Check if any stream is abandoned.
5430 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005431 return true;
5432 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005433 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005434 return false;
5435 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005436
Zhijun Hecc27e112013-10-03 16:12:43 -07005437 // Inform waitUntilRequestProcessed thread of a new request ID
5438 {
5439 Mutex::Autolock al(mLatestRequestMutex);
5440
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005441 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005442 mLatestRequestSignal.signal();
5443 }
5444
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005445 // Submit a batch of requests to HAL.
5446 // Use flush lock only when submitting multilple requests in a batch.
5447 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5448 // which may take a long time to finish so synchronizing flush() and
5449 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5450 // For now, only synchronize for high speed recording and we should figure something out for
5451 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005452 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005453
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005454 if (useFlushLock) {
5455 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005456 }
5457
Zhijun Hef0645c12016-08-02 00:58:11 -07005458 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005459 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005460
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005461 sp<Camera3Device> parent = mParent.promote();
5462 if (parent != nullptr) {
5463 parent->mRequestBufferSM.onSubmittingRequest();
5464 }
5465
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005466 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005467 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07005468 submitRequestSuccess = sendRequestsBatch();
5469
Shuzhen Wang686f6442017-06-20 16:16:04 -07005470 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5471 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005472
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005473 if (useFlushLock) {
5474 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005475 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005476
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005477 // Unset as current request
5478 {
5479 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005480 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005481 }
5482
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005483 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005484}
5485
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005486status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005487 ATRACE_CALL();
5488
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005489 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005490 for (size_t i = 0; i < mNextRequests.size(); i++) {
5491 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005492 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5493 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5494 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5495
5496 // Prepare a request to HAL
5497 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5498
5499 // Insert any queued triggers (before metadata is locked)
5500 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005501 if (res < 0) {
5502 SET_ERR("RequestThread: Unable to insert triggers "
5503 "(capture request %d, HAL device: %s (%d)",
5504 halRequest->frame_number, strerror(-res), res);
5505 return INVALID_OPERATION;
5506 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005507
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005508 int triggerCount = res;
5509 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5510 mPrevTriggers = triggerCount;
5511
5512 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005513 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5514 // Request settings are all the same within one batch, so only treat the first
5515 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005516 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005517 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005518 /**
5519 * HAL workaround:
5520 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5521 */
5522 res = addDummyTriggerIds(captureRequest);
5523 if (res != OK) {
5524 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5525 "(capture request %d, HAL device: %s (%d)",
5526 halRequest->frame_number, strerror(-res), res);
5527 return INVALID_OPERATION;
5528 }
5529
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005530 {
5531 // Correct metadata regions for distortion correction if enabled
5532 sp<Camera3Device> parent = mParent.promote();
5533 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07005534 List<PhysicalCameraSettings>::iterator it;
5535 for (it = captureRequest->mSettingsList.begin();
5536 it != captureRequest->mSettingsList.end(); it++) {
5537 if (parent->mDistortionMappers.find(it->cameraId) ==
5538 parent->mDistortionMappers.end()) {
5539 continue;
5540 }
5541 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
5542 &(it->metadata));
5543 if (res != OK) {
5544 SET_ERR("RequestThread: Unable to correct capture requests "
5545 "for lens distortion for request %d: %s (%d)",
5546 halRequest->frame_number, strerror(-res), res);
5547 return INVALID_OPERATION;
5548 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005549 }
5550 }
5551 }
5552
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005553 /**
5554 * The request should be presorted so accesses in HAL
5555 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5556 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005557 captureRequest->mSettingsList.begin()->metadata.sort();
5558 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005559 mPrevRequest = captureRequest;
5560 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5561
5562 IF_ALOGV() {
5563 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5564 find_camera_metadata_ro_entry(
5565 halRequest->settings,
5566 ANDROID_CONTROL_AF_TRIGGER,
5567 &e
5568 );
5569 if (e.count > 0) {
5570 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5571 __FUNCTION__,
5572 halRequest->frame_number,
5573 e.data.u8[0]);
5574 }
5575 }
5576 } else {
5577 // leave request.settings NULL to indicate 'reuse latest given'
5578 ALOGVV("%s: Request settings are REUSED",
5579 __FUNCTION__);
5580 }
5581
Emilian Peevaebbe412018-01-15 13:53:24 +00005582 if (captureRequest->mSettingsList.size() > 1) {
5583 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5584 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005585 if (newRequest) {
5586 halRequest->physcam_settings =
5587 new const camera_metadata* [halRequest->num_physcam_settings];
5588 } else {
5589 halRequest->physcam_settings = nullptr;
5590 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005591 auto it = ++captureRequest->mSettingsList.begin();
5592 size_t i = 0;
5593 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5594 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005595 if (newRequest) {
5596 it->metadata.sort();
5597 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5598 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005599 }
5600 }
5601
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005602 uint32_t totalNumBuffers = 0;
5603
5604 // Fill in buffers
5605 if (captureRequest->mInputStream != NULL) {
5606 halRequest->input_buffer = &captureRequest->mInputBuffer;
5607 totalNumBuffers += 1;
5608 } else {
5609 halRequest->input_buffer = NULL;
5610 }
5611
5612 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5613 captureRequest->mOutputStreams.size());
5614 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005615 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005616
5617 sp<Camera3Device> parent = mParent.promote();
5618 if (parent == NULL) {
5619 // Should not happen, and nowhere to send errors to, so just log it
5620 CLOGE("RequestThread: Parent is gone");
5621 return INVALID_OPERATION;
5622 }
5623 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5624
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005625 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005626 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005627 sp<Camera3OutputStreamInterface> outputStream =
5628 captureRequest->mOutputStreams.editItemAt(j);
5629 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005630
5631 // Prepare video buffers for high speed recording on the first video request.
5632 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5633 // Only try to prepare video stream on the first video request.
5634 mPrepareVideoStream = false;
5635
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005636 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5637 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005638 while (res == NOT_ENOUGH_DATA) {
5639 res = outputStream->prepareNextBuffer();
5640 }
5641 if (res != OK) {
5642 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5643 __FUNCTION__, strerror(-res), res);
5644 outputStream->cancelPrepare();
5645 }
5646 }
5647
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005648 std::vector<size_t> uniqueSurfaceIds;
5649 res = outputStream->getUniqueSurfaceIds(
5650 captureRequest->mOutputSurfaces[streamId],
5651 &uniqueSurfaceIds);
5652 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5653 if (res != OK && res != INVALID_OPERATION) {
5654 ALOGE("%s: failed to query stream %d unique surface IDs",
5655 __FUNCTION__, streamId);
5656 return res;
5657 }
5658 if (res == OK) {
5659 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5660 }
5661
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005662 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005663 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005664 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005665 return TIMED_OUT;
5666 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005667 // HAL will request buffer through requestStreamBuffer API
5668 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5669 buffer.stream = outputStream->asHalStream();
5670 buffer.buffer = nullptr;
5671 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5672 buffer.acquire_fence = -1;
5673 buffer.release_fence = -1;
5674 } else {
5675 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5676 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005677 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005678 if (res != OK) {
5679 // Can't get output buffer from gralloc queue - this could be due to
5680 // abandoned queue or other consumer misbehavior, so not a fatal
5681 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005682 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005683 " %s (%d)", strerror(-res), res);
5684
5685 return TIMED_OUT;
5686 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005687 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005688
5689 {
5690 sp<Camera3Device> parent = mParent.promote();
5691 if (parent != nullptr) {
5692 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5693 for (const auto& settings : captureRequest->mSettingsList) {
5694 if ((streamCameraId.isEmpty() &&
5695 parent->getId() == settings.cameraId.c_str()) ||
5696 streamCameraId == settings.cameraId.c_str()) {
5697 outputStream->fireBufferRequestForFrameNumber(
5698 captureRequest->mResultExtras.frameNumber,
5699 settings.metadata);
5700 }
5701 }
5702 }
5703 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005704
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005705 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5706
5707 if (!physicalCameraId.isEmpty()) {
5708 // Physical stream isn't supported for input request.
5709 if (halRequest->input_buffer) {
5710 CLOGE("Physical stream is not supported for input request");
5711 return INVALID_OPERATION;
5712 }
5713 requestedPhysicalCameras.insert(physicalCameraId);
5714 }
5715 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005716 }
5717 totalNumBuffers += halRequest->num_output_buffers;
5718
5719 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005720 // If this request list is for constrained high speed recording (not
5721 // preview), and the current request is not the last one in the batch,
5722 // do not send callback to the app.
5723 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005724 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005725 hasCallback = false;
5726 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005727 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005728 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005729 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5730 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5731 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5732 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5733 isStillCapture = true;
5734 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5735 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005736
5737 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5738 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5739 isZslCapture = true;
5740 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005741 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005742 res = parent->registerInFlight(halRequest->frame_number,
5743 totalNumBuffers, captureRequest->mResultExtras,
5744 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005745 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005746 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005747 requestedPhysicalCameras, isStillCapture, isZslCapture,
5748 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5749 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005750 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5751 ", burstId = %" PRId32 ".",
5752 __FUNCTION__,
5753 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5754 captureRequest->mResultExtras.burstId);
5755 if (res != OK) {
5756 SET_ERR("RequestThread: Unable to register new in-flight request:"
5757 " %s (%d)", strerror(-res), res);
5758 return INVALID_OPERATION;
5759 }
5760 }
5761
5762 return OK;
5763}
5764
Igor Murashkin1e479c02013-09-06 16:55:14 -07005765CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005766 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005767 Mutex::Autolock al(mLatestRequestMutex);
5768
5769 ALOGV("RequestThread::%s", __FUNCTION__);
5770
5771 return mLatestRequest;
5772}
5773
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005774bool Camera3Device::RequestThread::isStreamPending(
5775 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005776 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005777 Mutex::Autolock l(mRequestLock);
5778
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005779 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005780 if (!nextRequest.submitted) {
5781 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5782 if (stream == s) return true;
5783 }
5784 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005785 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005786 }
5787
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005788 for (const auto& request : mRequestQueue) {
5789 for (const auto& s : request->mOutputStreams) {
5790 if (stream == s) return true;
5791 }
5792 if (stream == request->mInputStream) return true;
5793 }
5794
5795 for (const auto& request : mRepeatingRequests) {
5796 for (const auto& s : request->mOutputStreams) {
5797 if (stream == s) return true;
5798 }
5799 if (stream == request->mInputStream) return true;
5800 }
5801
5802 return false;
5803}
Jianing Weicb0652e2014-03-12 18:29:36 -07005804
Emilian Peev40ead602017-09-26 15:46:36 +01005805bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5806 ATRACE_CALL();
5807 Mutex::Autolock l(mRequestLock);
5808
5809 for (const auto& nextRequest : mNextRequests) {
5810 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5811 if (s.first == streamId) {
5812 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5813 if (it != s.second.end()) {
5814 return true;
5815 }
5816 }
5817 }
5818 }
5819
5820 for (const auto& request : mRequestQueue) {
5821 for (const auto& s : request->mOutputSurfaces) {
5822 if (s.first == streamId) {
5823 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5824 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005825 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005826 }
5827 }
5828 }
5829 }
5830
5831 for (const auto& request : mRepeatingRequests) {
5832 for (const auto& s : request->mOutputSurfaces) {
5833 if (s.first == streamId) {
5834 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5835 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005836 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005837 }
5838 }
5839 }
5840 }
5841
5842 return false;
5843}
5844
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005845void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5846 if (!mUseHalBufManager) {
5847 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5848 return;
5849 }
5850
5851 Mutex::Autolock pl(mPauseLock);
5852 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005853 mInterface->signalPipelineDrain(streamIds);
5854 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005855 }
5856 // If request thread is still busy, wait until paused then notify HAL
5857 mNotifyPipelineDrain = true;
5858 mStreamIdsToBeDrained = streamIds;
5859}
5860
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005861nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005862 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005863 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005864 return mExpectedInflightDuration > kMinInflightDuration ?
5865 mExpectedInflightDuration : kMinInflightDuration;
5866}
5867
Emilian Peevaebbe412018-01-15 13:53:24 +00005868void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5869 camera3_capture_request_t *halRequest) {
5870 if ((request == nullptr) || (halRequest == nullptr)) {
5871 ALOGE("%s: Invalid request!", __FUNCTION__);
5872 return;
5873 }
5874
5875 if (halRequest->num_physcam_settings > 0) {
5876 if (halRequest->physcam_id != nullptr) {
5877 delete [] halRequest->physcam_id;
5878 halRequest->physcam_id = nullptr;
5879 }
5880 if (halRequest->physcam_settings != nullptr) {
5881 auto it = ++(request->mSettingsList.begin());
5882 size_t i = 0;
5883 for (; it != request->mSettingsList.end(); it++, i++) {
5884 it->metadata.unlock(halRequest->physcam_settings[i]);
5885 }
5886 delete [] halRequest->physcam_settings;
5887 halRequest->physcam_settings = nullptr;
5888 }
5889 }
5890}
5891
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005892void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5893 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005894 return;
5895 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005896
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005897 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005898 // Skip the ones that have been submitted successfully.
5899 if (nextRequest.submitted) {
5900 continue;
5901 }
5902
5903 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5904 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5905 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5906
5907 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005908 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005909 }
5910
Emilian Peevaebbe412018-01-15 13:53:24 +00005911 cleanupPhysicalSettings(captureRequest, halRequest);
5912
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005913 if (captureRequest->mInputStream != NULL) {
5914 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5915 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5916 }
5917
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005918 // No output buffer can be returned when using HAL buffer manager
5919 if (!mUseHalBufManager) {
5920 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5921 //Buffers that failed processing could still have
5922 //valid acquire fence.
5923 int acquireFence = (*outputBuffers)[i].acquire_fence;
5924 if (0 <= acquireFence) {
5925 close(acquireFence);
5926 outputBuffers->editItemAt(i).acquire_fence = -1;
5927 }
5928 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5929 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5930 /*timestampIncreasing*/true, std::vector<size_t> (),
5931 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005932 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005933 }
5934
5935 if (sendRequestError) {
5936 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005937 sp<NotificationListener> listener = mListener.promote();
5938 if (listener != NULL) {
5939 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005940 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005941 captureRequest->mResultExtras);
5942 }
5943 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005944
5945 // Remove yet-to-be submitted inflight request from inflightMap
5946 {
5947 sp<Camera3Device> parent = mParent.promote();
5948 if (parent != NULL) {
5949 Mutex::Autolock l(parent->mInFlightLock);
5950 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5951 if (idx >= 0) {
5952 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5953 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5954 parent->removeInFlightMapEntryLocked(idx);
5955 }
5956 }
5957 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005958 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005959
5960 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005961 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005962}
5963
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005964void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005965 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005966 // Optimized a bit for the simple steady-state case (single repeating
5967 // request), to avoid putting that request in the queue temporarily.
5968 Mutex::Autolock l(mRequestLock);
5969
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005970 assert(mNextRequests.empty());
5971
5972 NextRequest nextRequest;
5973 nextRequest.captureRequest = waitForNextRequestLocked();
5974 if (nextRequest.captureRequest == nullptr) {
5975 return;
5976 }
5977
5978 nextRequest.halRequest = camera3_capture_request_t();
5979 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005980 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005981
5982 // Wait for additional requests
5983 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5984
5985 for (size_t i = 1; i < batchSize; i++) {
5986 NextRequest additionalRequest;
5987 additionalRequest.captureRequest = waitForNextRequestLocked();
5988 if (additionalRequest.captureRequest == nullptr) {
5989 break;
5990 }
5991
5992 additionalRequest.halRequest = camera3_capture_request_t();
5993 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005994 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005995 }
5996
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005997 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005998 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005999 mNextRequests.size(), batchSize);
6000 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006001 }
6002
6003 return;
6004}
6005
6006sp<Camera3Device::CaptureRequest>
6007 Camera3Device::RequestThread::waitForNextRequestLocked() {
6008 status_t res;
6009 sp<CaptureRequest> nextRequest;
6010
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006011 while (mRequestQueue.empty()) {
6012 if (!mRepeatingRequests.empty()) {
6013 // Always atomically enqueue all requests in a repeating request
6014 // list. Guarantees a complete in-sequence set of captures to
6015 // application.
6016 const RequestList &requests = mRepeatingRequests;
6017 RequestList::const_iterator firstRequest =
6018 requests.begin();
6019 nextRequest = *firstRequest;
6020 mRequestQueue.insert(mRequestQueue.end(),
6021 ++firstRequest,
6022 requests.end());
6023 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07006024
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006025 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07006026
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006027 break;
6028 }
6029
6030 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
6031
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006032 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
6033 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006034 Mutex::Autolock pl(mPauseLock);
6035 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006036 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006037 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006038 if (mNotifyPipelineDrain) {
6039 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6040 mNotifyPipelineDrain = false;
6041 mStreamIdsToBeDrained.clear();
6042 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006043 // Let the tracker know
6044 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6045 if (statusTracker != 0) {
6046 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6047 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006048 sp<Camera3Device> parent = mParent.promote();
6049 if (parent != nullptr) {
6050 parent->mRequestBufferSM.onRequestThreadPaused();
6051 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006052 }
6053 // Stop waiting for now and let thread management happen
6054 return NULL;
6055 }
6056 }
6057
6058 if (nextRequest == NULL) {
6059 // Don't have a repeating request already in hand, so queue
6060 // must have an entry now.
6061 RequestList::iterator firstRequest =
6062 mRequestQueue.begin();
6063 nextRequest = *firstRequest;
6064 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07006065 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
6066 sp<NotificationListener> listener = mListener.promote();
6067 if (listener != NULL) {
6068 listener->notifyRequestQueueEmpty();
6069 }
6070 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006071 }
6072
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006073 // In case we've been unpaused by setPaused clearing mDoPause, need to
6074 // update internal pause state (capture/setRepeatingRequest unpause
6075 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006076 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006077 if (mPaused) {
6078 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
6079 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6080 if (statusTracker != 0) {
6081 statusTracker->markComponentActive(mStatusId);
6082 }
6083 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006084 mPaused = false;
6085
6086 // Check if we've reconfigured since last time, and reset the preview
6087 // request if so. Can't use 'NULL request == repeat' across configure calls.
6088 if (mReconfigured) {
6089 mPrevRequest.clear();
6090 mReconfigured = false;
6091 }
6092
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006093 if (nextRequest != NULL) {
6094 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006095 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
6096 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006097
6098 // Since RequestThread::clear() removes buffers from the input stream,
6099 // get the right buffer here before unlocking mRequestLock
6100 if (nextRequest->mInputStream != NULL) {
6101 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
6102 if (res != OK) {
6103 // Can't get input buffer from gralloc queue - this could be due to
6104 // disconnected queue or other producer misbehavior, so not a fatal
6105 // error
6106 ALOGE("%s: Can't get input buffer, skipping request:"
6107 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006108
6109 sp<NotificationListener> listener = mListener.promote();
6110 if (listener != NULL) {
6111 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006112 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006113 nextRequest->mResultExtras);
6114 }
6115 return NULL;
6116 }
6117 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006118 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07006119
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006120 return nextRequest;
6121}
6122
6123bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006124 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006125 status_t res;
6126 Mutex::Autolock l(mPauseLock);
6127 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006128 if (mPaused == false) {
6129 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006130 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006131 if (mNotifyPipelineDrain) {
6132 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6133 mNotifyPipelineDrain = false;
6134 mStreamIdsToBeDrained.clear();
6135 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006136 // Let the tracker know
6137 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6138 if (statusTracker != 0) {
6139 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6140 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006141 sp<Camera3Device> parent = mParent.promote();
6142 if (parent != nullptr) {
6143 parent->mRequestBufferSM.onRequestThreadPaused();
6144 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006145 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006146
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006147 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006148 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006149 return true;
6150 }
6151 }
6152 // We don't set mPaused to false here, because waitForNextRequest needs
6153 // to further manage the paused state in case of starvation.
6154 return false;
6155}
6156
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006157void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006158 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006159 // With work to do, mark thread as unpaused.
6160 // If paused by request (setPaused), don't resume, to avoid
6161 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006162 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006163 Mutex::Autolock p(mPauseLock);
6164 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006165 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6166 if (mPaused) {
6167 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6168 if (statusTracker != 0) {
6169 statusTracker->markComponentActive(mStatusId);
6170 }
6171 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006172 mPaused = false;
6173 }
6174}
6175
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006176void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6177 sp<Camera3Device> parent = mParent.promote();
6178 if (parent != NULL) {
6179 va_list args;
6180 va_start(args, fmt);
6181
6182 parent->setErrorStateV(fmt, args);
6183
6184 va_end(args);
6185 }
6186}
6187
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006188status_t Camera3Device::RequestThread::insertTriggers(
6189 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006190 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006191 Mutex::Autolock al(mTriggerMutex);
6192
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006193 sp<Camera3Device> parent = mParent.promote();
6194 if (parent == NULL) {
6195 CLOGE("RequestThread: Parent is gone");
6196 return DEAD_OBJECT;
6197 }
6198
Emilian Peevaebbe412018-01-15 13:53:24 +00006199 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006200 size_t count = mTriggerMap.size();
6201
6202 for (size_t i = 0; i < count; ++i) {
6203 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006204 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006205
6206 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6207 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6208 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006209 if (isAeTrigger) {
6210 request->mResultExtras.precaptureTriggerId = triggerId;
6211 mCurrentPreCaptureTriggerId = triggerId;
6212 } else {
6213 request->mResultExtras.afTriggerId = triggerId;
6214 mCurrentAfTriggerId = triggerId;
6215 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006216 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006217 }
6218
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006219 camera_metadata_entry entry = metadata.find(tag);
6220
6221 if (entry.count > 0) {
6222 /**
6223 * Already has an entry for this trigger in the request.
6224 * Rewrite it with our requested trigger value.
6225 */
6226 RequestTrigger oldTrigger = trigger;
6227
6228 oldTrigger.entryValue = entry.data.u8[0];
6229
6230 mTriggerReplacedMap.add(tag, oldTrigger);
6231 } else {
6232 /**
6233 * More typical, no trigger entry, so we just add it
6234 */
6235 mTriggerRemovedMap.add(tag, trigger);
6236 }
6237
6238 status_t res;
6239
6240 switch (trigger.getTagType()) {
6241 case TYPE_BYTE: {
6242 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6243 res = metadata.update(tag,
6244 &entryValue,
6245 /*count*/1);
6246 break;
6247 }
6248 case TYPE_INT32:
6249 res = metadata.update(tag,
6250 &trigger.entryValue,
6251 /*count*/1);
6252 break;
6253 default:
6254 ALOGE("%s: Type not supported: 0x%x",
6255 __FUNCTION__,
6256 trigger.getTagType());
6257 return INVALID_OPERATION;
6258 }
6259
6260 if (res != OK) {
6261 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6262 ", value %d", __FUNCTION__, trigger.getTagName(),
6263 trigger.entryValue);
6264 return res;
6265 }
6266
6267 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6268 trigger.getTagName(),
6269 trigger.entryValue);
6270 }
6271
6272 mTriggerMap.clear();
6273
6274 return count;
6275}
6276
6277status_t Camera3Device::RequestThread::removeTriggers(
6278 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006279 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006280 Mutex::Autolock al(mTriggerMutex);
6281
Emilian Peevaebbe412018-01-15 13:53:24 +00006282 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006283
6284 /**
6285 * Replace all old entries with their old values.
6286 */
6287 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6288 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6289
6290 status_t res;
6291
6292 uint32_t tag = trigger.metadataTag;
6293 switch (trigger.getTagType()) {
6294 case TYPE_BYTE: {
6295 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6296 res = metadata.update(tag,
6297 &entryValue,
6298 /*count*/1);
6299 break;
6300 }
6301 case TYPE_INT32:
6302 res = metadata.update(tag,
6303 &trigger.entryValue,
6304 /*count*/1);
6305 break;
6306 default:
6307 ALOGE("%s: Type not supported: 0x%x",
6308 __FUNCTION__,
6309 trigger.getTagType());
6310 return INVALID_OPERATION;
6311 }
6312
6313 if (res != OK) {
6314 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6315 ", trigger value %d", __FUNCTION__,
6316 trigger.getTagName(), trigger.entryValue);
6317 return res;
6318 }
6319 }
6320 mTriggerReplacedMap.clear();
6321
6322 /**
6323 * Remove all new entries.
6324 */
6325 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6326 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6327 status_t res = metadata.erase(trigger.metadataTag);
6328
6329 if (res != OK) {
6330 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6331 ", trigger value %d", __FUNCTION__,
6332 trigger.getTagName(), trigger.entryValue);
6333 return res;
6334 }
6335 }
6336 mTriggerRemovedMap.clear();
6337
6338 return OK;
6339}
6340
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006341status_t Camera3Device::RequestThread::addDummyTriggerIds(
6342 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006343 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006344 static const int32_t dummyTriggerId = 1;
6345 status_t res;
6346
Emilian Peevaebbe412018-01-15 13:53:24 +00006347 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006348
6349 // If AF trigger is active, insert a dummy AF trigger ID if none already
6350 // exists
6351 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6352 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6353 if (afTrigger.count > 0 &&
6354 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6355 afId.count == 0) {
6356 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6357 if (res != OK) return res;
6358 }
6359
6360 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6361 // if none already exists
6362 camera_metadata_entry pcTrigger =
6363 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6364 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6365 if (pcTrigger.count > 0 &&
6366 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6367 pcId.count == 0) {
6368 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6369 &dummyTriggerId, 1);
6370 if (res != OK) return res;
6371 }
6372
6373 return OK;
6374}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006375
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006376/**
6377 * PreparerThread inner class methods
6378 */
6379
6380Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006381 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006382 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006383}
6384
6385Camera3Device::PreparerThread::~PreparerThread() {
6386 Thread::requestExitAndWait();
6387 if (mCurrentStream != nullptr) {
6388 mCurrentStream->cancelPrepare();
6389 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6390 mCurrentStream.clear();
6391 }
6392 clear();
6393}
6394
Ruben Brunkc78ac262015-08-13 17:58:46 -07006395status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006396 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006397 status_t res;
6398
6399 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006400 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006401
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006402 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006403 if (res == OK) {
6404 // No preparation needed, fire listener right off
6405 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006406 if (listener != NULL) {
6407 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006408 }
6409 return OK;
6410 } else if (res != NOT_ENOUGH_DATA) {
6411 return res;
6412 }
6413
6414 // Need to prepare, start up thread if necessary
6415 if (!mActive) {
6416 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6417 // isn't running
6418 Thread::requestExitAndWait();
6419 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6420 if (res != OK) {
6421 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006422 if (listener != NULL) {
6423 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006424 }
6425 return res;
6426 }
6427 mCancelNow = false;
6428 mActive = true;
6429 ALOGV("%s: Preparer stream started", __FUNCTION__);
6430 }
6431
6432 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006433 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006434 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6435
6436 return OK;
6437}
6438
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006439void Camera3Device::PreparerThread::pause() {
6440 ATRACE_CALL();
6441
6442 Mutex::Autolock l(mLock);
6443
6444 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6445 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6446 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6447 int currentMaxCount = mCurrentMaxCount;
6448 mPendingStreams.clear();
6449 mCancelNow = true;
6450 while (mActive) {
6451 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6452 if (res == TIMED_OUT) {
6453 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6454 return;
6455 } else if (res != OK) {
6456 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6457 return;
6458 }
6459 }
6460
6461 //Check whether the prepare thread was able to complete the current
6462 //stream. In case work is still pending emplace it along with the rest
6463 //of the streams in the pending list.
6464 if (currentStream != nullptr) {
6465 if (!mCurrentPrepareComplete) {
6466 pendingStreams.emplace(currentMaxCount, currentStream);
6467 }
6468 }
6469
6470 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6471 for (const auto& it : mPendingStreams) {
6472 it.second->cancelPrepare();
6473 }
6474}
6475
6476status_t Camera3Device::PreparerThread::resume() {
6477 ATRACE_CALL();
6478 status_t res;
6479
6480 Mutex::Autolock l(mLock);
6481 sp<NotificationListener> listener = mListener.promote();
6482
6483 if (mActive) {
6484 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6485 return NO_INIT;
6486 }
6487
6488 auto it = mPendingStreams.begin();
6489 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006490 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006491 if (res == OK) {
6492 if (listener != NULL) {
6493 listener->notifyPrepared(it->second->getId());
6494 }
6495 it = mPendingStreams.erase(it);
6496 } else if (res != NOT_ENOUGH_DATA) {
6497 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6498 res, strerror(-res));
6499 it = mPendingStreams.erase(it);
6500 } else {
6501 it++;
6502 }
6503 }
6504
6505 if (mPendingStreams.empty()) {
6506 return OK;
6507 }
6508
6509 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6510 if (res != OK) {
6511 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6512 __FUNCTION__, res, strerror(-res));
6513 return res;
6514 }
6515 mCancelNow = false;
6516 mActive = true;
6517 ALOGV("%s: Preparer stream started", __FUNCTION__);
6518
6519 return OK;
6520}
6521
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006522status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006523 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006524 Mutex::Autolock l(mLock);
6525
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006526 for (const auto& it : mPendingStreams) {
6527 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006528 }
6529 mPendingStreams.clear();
6530 mCancelNow = true;
6531
6532 return OK;
6533}
6534
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006535void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006536 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006537 Mutex::Autolock l(mLock);
6538 mListener = listener;
6539}
6540
6541bool Camera3Device::PreparerThread::threadLoop() {
6542 status_t res;
6543 {
6544 Mutex::Autolock l(mLock);
6545 if (mCurrentStream == nullptr) {
6546 // End thread if done with work
6547 if (mPendingStreams.empty()) {
6548 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6549 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6550 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6551 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006552 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006553 return false;
6554 }
6555
6556 // Get next stream to prepare
6557 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006558 mCurrentStream = it->second;
6559 mCurrentMaxCount = it->first;
6560 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006561 mPendingStreams.erase(it);
6562 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6563 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6564 } else if (mCancelNow) {
6565 mCurrentStream->cancelPrepare();
6566 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6567 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6568 mCurrentStream.clear();
6569 mCancelNow = false;
6570 return true;
6571 }
6572 }
6573
6574 res = mCurrentStream->prepareNextBuffer();
6575 if (res == NOT_ENOUGH_DATA) return true;
6576 if (res != OK) {
6577 // Something bad happened; try to recover by cancelling prepare and
6578 // signalling listener anyway
6579 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6580 mCurrentStream->getId(), res, strerror(-res));
6581 mCurrentStream->cancelPrepare();
6582 }
6583
6584 // This stream has finished, notify listener
6585 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006586 sp<NotificationListener> listener = mListener.promote();
6587 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006588 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6589 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006590 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006591 }
6592
6593 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6594 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006595 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006596
6597 return true;
6598}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006599
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006600status_t Camera3Device::RequestBufferStateMachine::initialize(
6601 sp<camera3::StatusTracker> statusTracker) {
6602 if (statusTracker == nullptr) {
6603 ALOGE("%s: statusTracker is null", __FUNCTION__);
6604 return BAD_VALUE;
6605 }
6606
6607 std::lock_guard<std::mutex> lock(mLock);
6608 mStatusTracker = statusTracker;
6609 mRequestBufferStatusId = statusTracker->addComponent();
6610 return OK;
6611}
6612
6613bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6614 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006615 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006616 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006617 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006618 return true;
6619 }
6620 return false;
6621}
6622
6623void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6624 std::lock_guard<std::mutex> lock(mLock);
6625 if (!mRequestBufferOngoing) {
6626 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6627 return;
6628 }
6629 mRequestBufferOngoing = false;
6630 if (mStatus == RB_STATUS_PENDING_STOP) {
6631 checkSwitchToStopLocked();
6632 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006633 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006634}
6635
6636void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6637 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006638 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006639 return;
6640}
6641
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006642void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006643 std::lock_guard<std::mutex> lock(mLock);
6644 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006645 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6646 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006647 mInflightMapEmpty = false;
6648 if (mStatus == RB_STATUS_STOPPED) {
6649 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006650 }
6651 return;
6652}
6653
6654void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6655 std::lock_guard<std::mutex> lock(mLock);
6656 mRequestThreadPaused = true;
6657 if (mStatus == RB_STATUS_PENDING_STOP) {
6658 checkSwitchToStopLocked();
6659 }
6660 return;
6661}
6662
6663void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6664 std::lock_guard<std::mutex> lock(mLock);
6665 mInflightMapEmpty = true;
6666 if (mStatus == RB_STATUS_PENDING_STOP) {
6667 checkSwitchToStopLocked();
6668 }
6669 return;
6670}
6671
6672void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6673 std::lock_guard<std::mutex> lock(mLock);
6674 if (!checkSwitchToStopLocked()) {
6675 mStatus = RB_STATUS_PENDING_STOP;
6676 }
6677 return;
6678}
6679
6680void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6681 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6682 if (statusTracker != nullptr) {
6683 if (active) {
6684 statusTracker->markComponentActive(mRequestBufferStatusId);
6685 } else {
6686 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6687 }
6688 }
6689}
6690
6691bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6692 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6693 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006694 return true;
6695 }
6696 return false;
6697}
6698
Shuzhen Wang268a1362018-10-16 16:32:59 -07006699status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6700 CameraMetadata& resultMetadata) {
6701 status_t res = OK;
6702 if (!mNeedFixupMonochromeTags) {
6703 return res;
6704 }
6705
6706 // Remove tags that are not applicable to monochrome camera.
6707 int32_t tagsToRemove[] = {
6708 ANDROID_SENSOR_GREEN_SPLIT,
6709 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6710 ANDROID_COLOR_CORRECTION_MODE,
6711 ANDROID_COLOR_CORRECTION_TRANSFORM,
6712 ANDROID_COLOR_CORRECTION_GAINS,
6713 };
6714 for (auto tag : tagsToRemove) {
6715 res = resultMetadata.erase(tag);
6716 if (res != OK) {
6717 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6718 return res;
6719 }
6720 }
6721
6722 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6723 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6724 for (size_t i = 1; i < blEntry.count; i++) {
6725 blEntry.data.f[i] = blEntry.data.f[0];
6726 }
6727
6728 // ANDROID_SENSOR_NOISE_PROFILE
6729 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6730 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6731 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6732 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6733 if (res != OK) {
6734 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6735 __FUNCTION__, strerror(-res), res);
6736 return res;
6737 }
6738 }
6739
6740 // ANDROID_STATISTICS_LENS_SHADING_MAP
6741 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6742 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6743 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6744 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6745 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6746 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6747 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6748 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6749 }
6750 }
6751
6752 // ANDROID_TONEMAP_CURVE_BLUE
6753 // ANDROID_TONEMAP_CURVE_GREEN
6754 // ANDROID_TONEMAP_CURVE_RED
6755 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6756 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6757 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6758 if (tcbEntry.count > 0
6759 && tcbEntry.count == tcgEntry.count
6760 && tcbEntry.count == tcrEntry.count) {
6761 for (size_t i = 0; i < tcbEntry.count; i++) {
6762 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6763 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6764 }
6765 }
6766
6767 return res;
6768}
6769
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006770}; // namespace android