blob: d4f78e0f277793360c53666162d712381e715ecc [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"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080059
60using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080061using namespace android::hardware::camera;
62using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080063
64namespace android {
65
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080066Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080067 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080068 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070069 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070070 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070071 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070072 mUsePartialResult(false),
73 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080074 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070076 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070077 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070078 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000079 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010080 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
81 mLastTemplateId(-1)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080082{
83 ATRACE_CALL();
84 camera3_callback_ops::notify = &sNotify;
85 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080086 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080087}
88
89Camera3Device::~Camera3Device()
90{
91 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080092 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080093 disconnect();
94}
95
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080096const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080097 return mId;
98}
99
Emilian Peevbd8c5032018-02-14 23:05:40 +0000100status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ATRACE_CALL();
102 Mutex::Autolock il(mInterfaceLock);
103 Mutex::Autolock l(mLock);
104
105 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
106 if (mStatus != STATUS_UNINITIALIZED) {
107 CLOGE("Already initialized!");
108 return INVALID_OPERATION;
109 }
110 if (manager == nullptr) return INVALID_OPERATION;
111
112 sp<ICameraDeviceSession> session;
113 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800114 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115 /*out*/ &session);
116 ATRACE_END();
117 if (res != OK) {
118 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
119 return res;
120 }
121
Steven Moreland5ff9c912017-03-09 23:13:00 -0800122 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700124 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125 session->close();
126 return res;
127 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800128
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700129 std::vector<std::string> physicalCameraIds;
130 bool isLogical = CameraProviderManager::isLogicalCamera(mDeviceInfo, &physicalCameraIds);
131 if (isLogical) {
132 for (auto& physicalId : physicalCameraIds) {
133 res = manager->getCameraCharacteristics(physicalId, &mPhysicalDeviceInfoMap[physicalId]);
134 if (res != OK) {
135 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
136 physicalId.c_str(), strerror(-res), res);
137 session->close();
138 return res;
139 }
140 }
141 }
142
Yifan Hongf79b5542017-04-11 14:44:25 -0700143 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700144 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
145 [&queue](const auto& descriptor) {
146 queue = std::make_shared<RequestMetadataQueue>(descriptor);
147 if (!queue->isValid() || queue->availableToWrite() <= 0) {
148 ALOGE("HAL returns empty request metadata fmq, not use it");
149 queue = nullptr;
150 // don't use the queue onwards.
151 }
152 });
153 if (!requestQueueRet.isOk()) {
154 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
155 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700156 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700157 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700158
159 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700160 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700161 [&resQueue](const auto& descriptor) {
162 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
163 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700164 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700165 resQueue = nullptr;
166 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700167 }
168 });
169 if (!resultQueueRet.isOk()) {
170 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
171 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700172 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700173 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700174 IF_ALOGV() {
175 session->interfaceChain([](
176 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
177 ALOGV("Session interface chain:");
178 for (auto iface : interfaceChain) {
179 ALOGV(" %s", iface.c_str());
180 }
181 });
182 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700183
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700184 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000185 std::string providerType;
186 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000187 mTagMonitor.initialize(mVendorTagId);
188 if (!monitorTags.isEmpty()) {
189 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
190 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800191
192 return initializeCommonLocked();
193}
194
195status_t Camera3Device::initializeCommonLocked() {
196
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700197 /** Start up status tracker thread */
198 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800199 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700200 if (res != OK) {
201 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
202 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800203 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700204 mStatusTracker.clear();
205 return res;
206 }
207
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700208 /** Register in-flight map to the status tracker */
209 mInFlightStatusId = mStatusTracker->addComponent();
210
Zhijun He125684a2015-12-26 15:07:30 -0800211 /** Create buffer manager */
212 mBufferManager = new Camera3BufferManager();
213
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000214 Vector<int32_t> sessionParamKeys;
215 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
216 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
217 if (sessionKeysEntry.count > 0) {
218 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
219 }
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700220 /** Start up request queue thread */
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000221 mRequestThread = new RequestThread(this, mStatusTracker, mInterface, sessionParamKeys);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800222 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800223 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700224 SET_ERR_L("Unable to start request queue thread: %s (%d)",
225 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800226 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800227 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800228 return res;
229 }
230
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700231 mPreparerThread = new PreparerThread();
232
Ruben Brunk183f0562015-08-12 12:55:02 -0700233 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800234 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700235 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700236 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700237 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800238
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800239 // Measure the clock domain offset between camera and video/hw_composer
240 camera_metadata_entry timestampSource =
241 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
242 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
243 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
244 mTimestampOffset = getMonoToBoottimeOffset();
245 }
246
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700247 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100248 camera_metadata_entry partialResultsCount =
249 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
250 if (partialResultsCount.count > 0) {
251 mNumPartialResults = partialResultsCount.data.i32[0];
252 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700253 }
254
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700255 camera_metadata_entry configs =
256 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
257 for (uint32_t i = 0; i < configs.count; i += 4) {
258 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
259 configs.data.i32[i + 3] ==
260 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
261 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
262 configs.data.i32[i + 2]));
263 }
264 }
265
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700266 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
267 res = mDistortionMapper.setupStaticInfo(mDeviceInfo);
268 if (res != OK) {
269 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
270 return res;
271 }
272 }
273
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800274 return OK;
275}
276
277status_t Camera3Device::disconnect() {
278 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700279 Mutex::Autolock il(mInterfaceLock);
Emilian Peev26d975d2018-07-05 14:52:57 +0100280 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800281
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700282 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800283
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700284 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700285 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700286 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700287 {
288 Mutex::Autolock l(mLock);
289 if (mStatus == STATUS_UNINITIALIZED) return res;
290
291 if (mStatus == STATUS_ACTIVE ||
292 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
293 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700294 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700295 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700296 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700297 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700298 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700299 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700300 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
301 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700302 // Continue to close device even in case of error
303 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700304 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800305 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800306
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700307 if (mStatus == STATUS_ERROR) {
308 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700309 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700310
311 if (mStatusTracker != NULL) {
312 mStatusTracker->requestExit();
313 }
314
315 if (mRequestThread != NULL) {
316 mRequestThread->requestExit();
317 }
318
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700319 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
320 for (size_t i = 0; i < mOutputStreams.size(); i++) {
321 streams.push_back(mOutputStreams[i]);
322 }
323 if (mInputStream != nullptr) {
324 streams.push_back(mInputStream);
325 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700326 }
327
328 // Joining done without holding mLock, otherwise deadlocks may ensue
329 // as the threads try to access parent state
330 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
331 // HAL may be in a bad state, so waiting for request thread
332 // (which may be stuck in the HAL processCaptureRequest call)
333 // could be dangerous.
334 mRequestThread->join();
335 }
336
337 if (mStatusTracker != NULL) {
338 mStatusTracker->join();
339 }
340
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800341 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700342 {
343 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800344 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700345 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800346 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700347 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800348
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700349 // Call close without internal mutex held, as the HAL close may need to
350 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800351 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700352
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700353 flushInflightRequests();
354
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700355 {
356 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800357 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700358 mOutputStreams.clear();
359 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700360 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700361 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700362 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700363 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800364
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700365 for (auto& weakStream : streams) {
366 sp<Camera3StreamInterface> stream = weakStream.promote();
367 if (stream != nullptr) {
368 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
369 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
370 }
371 }
372
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700373 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700374 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800375}
376
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700377// For dumping/debugging only -
378// try to acquire a lock a few times, eventually give up to proceed with
379// debug/dump operations
380bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
381 bool gotLock = false;
382 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
383 if (lock.tryLock() == NO_ERROR) {
384 gotLock = true;
385 break;
386 } else {
387 usleep(kDumpSleepDuration);
388 }
389 }
390 return gotLock;
391}
392
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700393Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
394 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100395 const int STREAM_CONFIGURATION_SIZE = 4;
396 const int STREAM_FORMAT_OFFSET = 0;
397 const int STREAM_WIDTH_OFFSET = 1;
398 const int STREAM_HEIGHT_OFFSET = 2;
399 const int STREAM_IS_INPUT_OFFSET = 3;
400 camera_metadata_ro_entry_t availableStreamConfigs =
401 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
402 if (availableStreamConfigs.count == 0 ||
403 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
404 return Size(0, 0);
405 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700406
Emilian Peev08dd2452017-04-06 16:55:14 +0100407 // Get max jpeg size (area-wise).
408 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
409 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
410 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
411 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
412 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
413 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
414 && format == HAL_PIXEL_FORMAT_BLOB &&
415 (width * height > maxJpegWidth * maxJpegHeight)) {
416 maxJpegWidth = width;
417 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700418 }
419 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100420
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700421 return Size(maxJpegWidth, maxJpegHeight);
422}
423
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800424nsecs_t Camera3Device::getMonoToBoottimeOffset() {
425 // try three times to get the clock offset, choose the one
426 // with the minimum gap in measurements.
427 const int tries = 3;
428 nsecs_t bestGap, measured;
429 for (int i = 0; i < tries; ++i) {
430 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
431 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
432 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
433 const nsecs_t gap = tmono2 - tmono;
434 if (i == 0 || gap < bestGap) {
435 bestGap = gap;
436 measured = tbase - ((tmono + tmono2) >> 1);
437 }
438 }
439 return measured;
440}
441
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800442hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
443 int frameworkFormat) {
444 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
445}
446
447DataspaceFlags Camera3Device::mapToHidlDataspace(
448 android_dataspace dataSpace) {
449 return dataSpace;
450}
451
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700452BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100453 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700454 return usage;
455}
456
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800457StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
458 switch (rotation) {
459 case CAMERA3_STREAM_ROTATION_0:
460 return StreamRotation::ROTATION_0;
461 case CAMERA3_STREAM_ROTATION_90:
462 return StreamRotation::ROTATION_90;
463 case CAMERA3_STREAM_ROTATION_180:
464 return StreamRotation::ROTATION_180;
465 case CAMERA3_STREAM_ROTATION_270:
466 return StreamRotation::ROTATION_270;
467 }
468 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
469 return StreamRotation::ROTATION_0;
470}
471
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800472status_t Camera3Device::mapToStreamConfigurationMode(
473 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
474 if (mode == nullptr) return BAD_VALUE;
475 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
476 switch(operationMode) {
477 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
478 *mode = StreamConfigurationMode::NORMAL_MODE;
479 break;
480 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
481 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
482 break;
483 default:
484 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
485 return BAD_VALUE;
486 }
487 } else {
488 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800489 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800490 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800491}
492
493camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
494 switch (status) {
495 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
496 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
497 }
498 return CAMERA3_BUFFER_STATUS_ERROR;
499}
500
501int Camera3Device::mapToFrameworkFormat(
502 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
503 return static_cast<uint32_t>(pixelFormat);
504}
505
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700506android_dataspace Camera3Device::mapToFrameworkDataspace(
507 DataspaceFlags dataSpace) {
508 return static_cast<android_dataspace>(dataSpace);
509}
510
Emilian Peev050f5dc2017-05-18 14:43:56 +0100511uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700512 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700513 return usage;
514}
515
Emilian Peev050f5dc2017-05-18 14:43:56 +0100516uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700517 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700518 return usage;
519}
520
Zhijun Hef7da0962014-04-24 13:27:56 -0700521ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700522 // Get max jpeg size (area-wise).
523 Size maxJpegResolution = getMaxJpegResolution();
524 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800525 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
526 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700527 return BAD_VALUE;
528 }
529
Zhijun Hef7da0962014-04-24 13:27:56 -0700530 // Get max jpeg buffer size
531 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700532 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
533 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
535 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700536 return BAD_VALUE;
537 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700538 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800539 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700540
541 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700542 float scaleFactor = ((float) (width * height)) /
543 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800544 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
545 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700546 if (jpegBufferSize > maxJpegBufferSize) {
547 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700548 }
549
550 return jpegBufferSize;
551}
552
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700553ssize_t Camera3Device::getPointCloudBufferSize() const {
554 const int FLOATS_PER_POINT=4;
555 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
556 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800557 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
558 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700559 return BAD_VALUE;
560 }
561 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
562 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
563 return maxBytesForPointCloud;
564}
565
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800566ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800567 const int PER_CONFIGURATION_SIZE = 3;
568 const int WIDTH_OFFSET = 0;
569 const int HEIGHT_OFFSET = 1;
570 const int SIZE_OFFSET = 2;
571 camera_metadata_ro_entry rawOpaqueSizes =
572 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800573 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800574 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800575 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
576 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800577 return BAD_VALUE;
578 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700579
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800580 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
581 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
582 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
583 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
584 }
585 }
586
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800587 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
588 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800589 return BAD_VALUE;
590}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700591
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800592status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
593 ATRACE_CALL();
594 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700595
596 // Try to lock, but continue in case of failure (to avoid blocking in
597 // deadlocks)
598 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
599 bool gotLock = tryLockSpinRightRound(mLock);
600
601 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800602 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
603 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700604 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800605 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
606 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700607
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800608 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700609
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800610 String16 templatesOption("-t");
611 int n = args.size();
612 for (int i = 0; i < n; i++) {
613 if (args[i] == templatesOption) {
614 dumpTemplates = true;
615 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000616 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700617 if (i + 1 < n) {
618 String8 monitorTags = String8(args[i + 1]);
619 if (monitorTags == "off") {
620 mTagMonitor.disableMonitoring();
621 } else {
622 mTagMonitor.parseTagsToMonitor(monitorTags);
623 }
624 } else {
625 mTagMonitor.disableMonitoring();
626 }
627 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800628 }
629
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800630 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800631
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800632 const char *status =
633 mStatus == STATUS_ERROR ? "ERROR" :
634 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700635 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
636 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800637 mStatus == STATUS_ACTIVE ? "ACTIVE" :
638 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700639
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800640 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700641 if (mStatus == STATUS_ERROR) {
642 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
643 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800644 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800645 const char *mode =
646 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
647 mOperatingMode == static_cast<int>(
648 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
649 "CUSTOM";
650 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800651
652 if (mInputStream != NULL) {
653 write(fd, lines.string(), lines.size());
654 mInputStream->dump(fd, args);
655 } else {
656 lines.appendFormat(" No input stream.\n");
657 write(fd, lines.string(), lines.size());
658 }
659 for (size_t i = 0; i < mOutputStreams.size(); i++) {
660 mOutputStreams[i]->dump(fd,args);
661 }
662
Zhijun He431503c2016-03-07 17:30:16 -0800663 if (mBufferManager != NULL) {
664 lines = String8(" Camera3 Buffer Manager:\n");
665 write(fd, lines.string(), lines.size());
666 mBufferManager->dump(fd, args);
667 }
Zhijun He125684a2015-12-26 15:07:30 -0800668
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700669 lines = String8(" In-flight requests:\n");
670 if (mInFlightMap.size() == 0) {
671 lines.append(" None\n");
672 } else {
673 for (size_t i = 0; i < mInFlightMap.size(); i++) {
674 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700675 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700676 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800677 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700678 r.numBuffersLeft);
679 }
680 }
681 write(fd, lines.string(), lines.size());
682
Shuzhen Wang686f6442017-06-20 16:16:04 -0700683 if (mRequestThread != NULL) {
684 mRequestThread->dumpCaptureRequestLatency(fd,
685 " ProcessCaptureRequest latency histogram:");
686 }
687
Igor Murashkin1e479c02013-09-06 16:55:14 -0700688 {
689 lines = String8(" Last request sent:\n");
690 write(fd, lines.string(), lines.size());
691
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700692 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700693 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
694 }
695
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800696 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800697 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800698 "TEMPLATE_PREVIEW",
699 "TEMPLATE_STILL_CAPTURE",
700 "TEMPLATE_VIDEO_RECORD",
701 "TEMPLATE_VIDEO_SNAPSHOT",
702 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800703 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800704 };
705
706 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800707 camera_metadata_t *templateRequest = nullptr;
708 mInterface->constructDefaultRequestSettings(
709 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800710 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800711 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800712 lines.append(" Not supported\n");
713 write(fd, lines.string(), lines.size());
714 } else {
715 write(fd, lines.string(), lines.size());
716 dump_indented_camera_metadata(templateRequest,
717 fd, /*verbosity*/2, /*indentation*/8);
718 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800719 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800720 }
721 }
722
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700723 mTagMonitor.dumpMonitoredMetadata(fd);
724
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800725 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800726 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800727 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800728 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800729 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800730
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700731 if (gotLock) mLock.unlock();
732 if (gotInterfaceLock) mInterfaceLock.unlock();
733
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800734 return OK;
735}
736
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700737const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800738 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800739 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
740 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700741 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800742 mStatus == STATUS_ERROR ?
743 "when in error state" : "before init");
744 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700745 if (physicalId.isEmpty()) {
746 return mDeviceInfo;
747 } else {
748 std::string id(physicalId.c_str());
749 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
750 return mPhysicalDeviceInfoMap.at(id);
751 } else {
752 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
753 return mDeviceInfo;
754 }
755 }
756}
757
758const CameraMetadata& Camera3Device::info() const {
759 String8 emptyId;
760 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800761}
762
Jianing Wei90e59c92014-03-12 18:29:36 -0700763status_t Camera3Device::checkStatusOkToCaptureLocked() {
764 switch (mStatus) {
765 case STATUS_ERROR:
766 CLOGE("Device has encountered a serious error");
767 return INVALID_OPERATION;
768 case STATUS_UNINITIALIZED:
769 CLOGE("Device not initialized");
770 return INVALID_OPERATION;
771 case STATUS_UNCONFIGURED:
772 case STATUS_CONFIGURED:
773 case STATUS_ACTIVE:
774 // OK
775 break;
776 default:
777 SET_ERR_L("Unexpected status: %d", mStatus);
778 return INVALID_OPERATION;
779 }
780 return OK;
781}
782
783status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000784 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700785 const std::list<const SurfaceMap> &surfaceMaps,
786 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700787 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700788 if (requestList == NULL) {
789 CLOGE("requestList cannot be NULL.");
790 return BAD_VALUE;
791 }
792
Jianing Weicb0652e2014-03-12 18:29:36 -0700793 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000794 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700795 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
796 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
797 ++metadataIt, ++surfaceMapIt) {
798 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700799 if (newRequest == 0) {
800 CLOGE("Can't create capture request");
801 return BAD_VALUE;
802 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700803
Shuzhen Wang9d066012016-09-30 11:30:20 -0700804 newRequest->mRepeating = repeating;
805
Jianing Weicb0652e2014-03-12 18:29:36 -0700806 // Setup burst Id and request Id
807 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000808 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
809 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700810 CLOGE("RequestID entry exists; but must not be empty in metadata");
811 return BAD_VALUE;
812 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000813 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
814 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700815 } else {
816 CLOGE("RequestID does not exist in metadata");
817 return BAD_VALUE;
818 }
819
Jianing Wei90e59c92014-03-12 18:29:36 -0700820 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700821
822 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700823 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700824 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
825 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
826 return BAD_VALUE;
827 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700828
829 // Setup batch size if this is a high speed video recording request.
830 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
831 auto firstRequest = requestList->begin();
832 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
833 if (outputStream->isVideoStream()) {
834 (*firstRequest)->mBatchSize = requestList->size();
835 break;
836 }
837 }
838 }
839
Jianing Wei90e59c92014-03-12 18:29:36 -0700840 return OK;
841}
842
Jianing Weicb0652e2014-03-12 18:29:36 -0700843status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800844 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800845
Emilian Peevaebbe412018-01-15 13:53:24 +0000846 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700847 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000848 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700849
Emilian Peevaebbe412018-01-15 13:53:24 +0000850 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700851}
852
Emilian Peevaebbe412018-01-15 13:53:24 +0000853void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700854 std::list<const SurfaceMap>& surfaceMaps,
855 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000856 PhysicalCameraSettingsList requestList;
857 requestList.push_back({std::string(getId().string()), request});
858 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700859
860 SurfaceMap surfaceMap;
861 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
862 // With no surface list passed in, stream and surface will have 1-to-1
863 // mapping. So the surface index is 0 for each stream in the surfaceMap.
864 for (size_t i = 0; i < streams.count; i++) {
865 surfaceMap[streams.data.i32[i]].push_back(0);
866 }
867 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800868}
869
Jianing Wei90e59c92014-03-12 18:29:36 -0700870status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000871 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700872 const std::list<const SurfaceMap> &surfaceMaps,
873 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700874 /*out*/
875 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700876 ATRACE_CALL();
877 Mutex::Autolock il(mInterfaceLock);
878 Mutex::Autolock l(mLock);
879
880 status_t res = checkStatusOkToCaptureLocked();
881 if (res != OK) {
882 // error logged by previous call
883 return res;
884 }
885
886 RequestList requestList;
887
Shuzhen Wang0129d522016-10-30 22:43:41 -0700888 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
889 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700890 if (res != OK) {
891 // error logged by previous call
892 return res;
893 }
894
895 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700896 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700897 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700898 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700899 }
900
901 if (res == OK) {
902 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
903 if (res != OK) {
904 SET_ERR_L("Can't transition to active in %f seconds!",
905 kActiveTimeout/1e9);
906 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800907 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700908 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700909 } else {
910 CLOGE("Cannot queue request. Impossible.");
911 return BAD_VALUE;
912 }
913
914 return res;
915}
916
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800917hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800918 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800919 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700920 // Ideally we should grab mLock, but that can lead to deadlock, and
921 // it's not super important to get up to date value of mStatus for this
922 // warning print, hence skipping the lock here
923 if (mStatus == STATUS_ERROR) {
924 // Per API contract, HAL should act as closed after device error
925 // But mStatus can be set to error by framework as well, so just log
926 // a warning here.
927 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700928 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700929
930 if (mProcessCaptureResultLock.tryLock() != OK) {
931 // This should never happen; it indicates a wrong client implementation
932 // that doesn't follow the contract. But, we can be tolerant here.
933 ALOGE("%s: callback overlapped! waiting 1s...",
934 __FUNCTION__);
935 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
936 ALOGE("%s: cannot acquire lock in 1s, dropping results",
937 __FUNCTION__);
938 // really don't know what to do, so bail out.
939 return hardware::Void();
940 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800941 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700942 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800943 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -0700944 }
945 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800946 return hardware::Void();
947}
948
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800949// Only one processCaptureResult should be called at a time, so
950// the locks won't block. The locks are present here simply to enforce this.
951hardware::Return<void> Camera3Device::processCaptureResult(
952 const hardware::hidl_vec<
953 hardware::camera::device::V3_2::CaptureResult>& results) {
954 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
955
956 // Ideally we should grab mLock, but that can lead to deadlock, and
957 // it's not super important to get up to date value of mStatus for this
958 // warning print, hence skipping the lock here
959 if (mStatus == STATUS_ERROR) {
960 // Per API contract, HAL should act as closed after device error
961 // But mStatus can be set to error by framework as well, so just log
962 // a warning here.
963 ALOGW("%s: received capture result in error state.", __FUNCTION__);
964 }
965
966 if (mProcessCaptureResultLock.tryLock() != OK) {
967 // This should never happen; it indicates a wrong client implementation
968 // that doesn't follow the contract. But, we can be tolerant here.
969 ALOGE("%s: callback overlapped! waiting 1s...",
970 __FUNCTION__);
971 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
972 ALOGE("%s: cannot acquire lock in 1s, dropping results",
973 __FUNCTION__);
974 // really don't know what to do, so bail out.
975 return hardware::Void();
976 }
977 }
978 for (const auto& result : results) {
979 processOneCaptureResultLocked(result, noPhysMetadata);
980 }
981 mProcessCaptureResultLock.unlock();
982 return hardware::Void();
983}
984
985status_t Camera3Device::readOneCameraMetadataLocked(
986 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
987 const hardware::camera::device::V3_2::CameraMetadata& result) {
988 if (fmqResultSize > 0) {
989 resultMetadata.resize(fmqResultSize);
990 if (mResultMetadataQueue == nullptr) {
991 return NO_MEMORY; // logged in initialize()
992 }
993 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
994 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
995 __FUNCTION__, fmqResultSize);
996 return INVALID_OPERATION;
997 }
998 } else {
999 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1000 result.size());
1001 }
1002
1003 if (resultMetadata.size() != 0) {
1004 status_t res;
1005 const camera_metadata_t* metadata =
1006 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1007 size_t expected_metadata_size = resultMetadata.size();
1008 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1009 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1010 __FUNCTION__, strerror(-res), res);
1011 return INVALID_OPERATION;
1012 }
1013 }
1014
1015 return OK;
1016}
1017
Yifan Honga640c5a2017-04-12 16:30:31 -07001018void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001019 const hardware::camera::device::V3_2::CaptureResult& result,
1020 const hardware::hidl_vec<
1021 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001022 camera3_capture_result r;
1023 status_t res;
1024 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001025
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001026 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001027 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001028 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1029 if (res != OK) {
1030 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1031 __FUNCTION__, result.frameNumber);
1032 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001033 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001034 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001035
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001036 // Read and validate physical camera metadata
1037 size_t physResultCount = physicalCameraMetadatas.size();
1038 std::vector<const char*> physCamIds(physResultCount);
1039 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1040 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1041 physResultMetadata.resize(physResultCount);
1042 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1043 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1044 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1045 if (res != OK) {
1046 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1047 __FUNCTION__, result.frameNumber,
1048 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001049 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001050 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001051 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1052 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1053 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001054 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001055 r.num_physcam_metadata = physResultCount;
1056 r.physcam_ids = physCamIds.data();
1057 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001058
1059 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1060 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1061 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1062 auto& bDst = outputBuffers[i];
1063 const StreamBuffer &bSrc = result.outputBuffers[i];
1064
1065 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001066 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001067 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1068 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001069 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001070 }
1071 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
1072
1073 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08001074 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001075 if (res != OK) {
1076 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1077 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001078 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001079 }
1080 bDst.buffer = buffer;
1081 bDst.status = mapHidlBufferStatus(bSrc.status);
1082 bDst.acquire_fence = -1;
1083 if (bSrc.releaseFence == nullptr) {
1084 bDst.release_fence = -1;
1085 } else if (bSrc.releaseFence->numFds == 1) {
1086 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1087 } else {
1088 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1089 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001090 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001091 }
1092 }
1093 r.num_output_buffers = outputBuffers.size();
1094 r.output_buffers = outputBuffers.data();
1095
1096 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001097 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001098 r.input_buffer = nullptr;
1099 } else {
1100 if (mInputStream->getId() != result.inputBuffer.streamId) {
1101 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1102 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001103 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001104 }
1105 inputBuffer.stream = mInputStream->asHalStream();
1106 buffer_handle_t *buffer;
1107 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1108 &buffer);
1109 if (res != OK) {
1110 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1111 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001112 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001113 }
1114 inputBuffer.buffer = buffer;
1115 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1116 inputBuffer.acquire_fence = -1;
1117 if (result.inputBuffer.releaseFence == nullptr) {
1118 inputBuffer.release_fence = -1;
1119 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1120 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1121 } else {
1122 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1123 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001124 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001125 }
1126 r.input_buffer = &inputBuffer;
1127 }
1128
1129 r.partial_result = result.partialResult;
1130
1131 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001132}
1133
1134hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001135 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001136 // Ideally we should grab mLock, but that can lead to deadlock, and
1137 // it's not super important to get up to date value of mStatus for this
1138 // warning print, hence skipping the lock here
1139 if (mStatus == STATUS_ERROR) {
1140 // Per API contract, HAL should act as closed after device error
1141 // But mStatus can be set to error by framework as well, so just log
1142 // a warning here.
1143 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001144 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001145
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001146 for (const auto& msg : msgs) {
1147 notify(msg);
1148 }
1149 return hardware::Void();
1150}
1151
1152void Camera3Device::notify(
1153 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1154
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001155 camera3_notify_msg m;
1156 switch (msg.type) {
1157 case MsgType::ERROR:
1158 m.type = CAMERA3_MSG_ERROR;
1159 m.message.error.frame_number = msg.msg.error.frameNumber;
1160 if (msg.msg.error.errorStreamId >= 0) {
1161 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001162 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001163 ALOGE("%s: Frame %d: Invalid error stream id %d",
1164 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001165 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001166 }
1167 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1168 } else {
1169 m.message.error.error_stream = nullptr;
1170 }
1171 switch (msg.msg.error.errorCode) {
1172 case ErrorCode::ERROR_DEVICE:
1173 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1174 break;
1175 case ErrorCode::ERROR_REQUEST:
1176 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1177 break;
1178 case ErrorCode::ERROR_RESULT:
1179 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1180 break;
1181 case ErrorCode::ERROR_BUFFER:
1182 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1183 break;
1184 }
1185 break;
1186 case MsgType::SHUTTER:
1187 m.type = CAMERA3_MSG_SHUTTER;
1188 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1189 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1190 break;
1191 }
1192 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001193}
1194
Emilian Peevaebbe412018-01-15 13:53:24 +00001195status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001196 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001197 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001198 ATRACE_CALL();
1199
Emilian Peevaebbe412018-01-15 13:53:24 +00001200 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001201}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001202
Jianing Weicb0652e2014-03-12 18:29:36 -07001203status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1204 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001205 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001206
Emilian Peevaebbe412018-01-15 13:53:24 +00001207 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001208 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001209 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001210
Emilian Peevaebbe412018-01-15 13:53:24 +00001211 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001212 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001213}
1214
Emilian Peevaebbe412018-01-15 13:53:24 +00001215status_t Camera3Device::setStreamingRequestList(
1216 const List<const PhysicalCameraSettingsList> &requestsList,
1217 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001218 ATRACE_CALL();
1219
Emilian Peevaebbe412018-01-15 13:53:24 +00001220 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001221}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222
1223sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001224 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225 status_t res;
1226
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001227 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001228 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1229 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001230 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1231 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001232 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001234 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001235 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001236 } else if (mStatus == STATUS_UNCONFIGURED) {
1237 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001238 CLOGE("No streams configured");
1239 return NULL;
1240 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001241 }
1242
Shuzhen Wang0129d522016-10-30 22:43:41 -07001243 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001244 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001245}
1246
Jianing Weicb0652e2014-03-12 18:29:36 -07001247status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001248 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001249 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001251
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001252 switch (mStatus) {
1253 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001254 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 return INVALID_OPERATION;
1256 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001257 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001259 case STATUS_UNCONFIGURED:
1260 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 case STATUS_ACTIVE:
1262 // OK
1263 break;
1264 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001265 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266 return INVALID_OPERATION;
1267 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001268 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001269
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001270 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001271}
1272
1273status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1274 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001275 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001276
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001277 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001278}
1279
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001280status_t Camera3Device::createInputStream(
1281 uint32_t width, uint32_t height, int format, int *id) {
1282 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001283 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001284 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001285 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001286 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1287 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001288
1289 status_t res;
1290 bool wasActive = false;
1291
1292 switch (mStatus) {
1293 case STATUS_ERROR:
1294 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1295 return INVALID_OPERATION;
1296 case STATUS_UNINITIALIZED:
1297 ALOGE("%s: Device not initialized", __FUNCTION__);
1298 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001299 case STATUS_UNCONFIGURED:
1300 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001301 // OK
1302 break;
1303 case STATUS_ACTIVE:
1304 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001305 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001306 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001307 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001308 return res;
1309 }
1310 wasActive = true;
1311 break;
1312 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001313 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001314 return INVALID_OPERATION;
1315 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001316 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001317
1318 if (mInputStream != 0) {
1319 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1320 return INVALID_OPERATION;
1321 }
1322
1323 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1324 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001325 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001326
1327 mInputStream = newStream;
1328
1329 *id = mNextStreamId++;
1330
1331 // Continue captures if active at start
1332 if (wasActive) {
1333 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001334 // Reuse current operating mode and session parameters for new stream config
1335 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001336 if (res != OK) {
1337 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1338 __FUNCTION__, mNextStreamId, strerror(-res), res);
1339 return res;
1340 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001341 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001342 }
1343
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001344 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001345 return OK;
1346}
1347
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001348status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001349 uint32_t width, uint32_t height, int format,
1350 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001351 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001352 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001353 ATRACE_CALL();
1354
1355 if (consumer == nullptr) {
1356 ALOGE("%s: consumer must not be null", __FUNCTION__);
1357 return BAD_VALUE;
1358 }
1359
1360 std::vector<sp<Surface>> consumers;
1361 consumers.push_back(consumer);
1362
1363 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001364 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1365 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001366}
1367
1368status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1369 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1370 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001371 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001372 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001373 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001374
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001375 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001376 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001377 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001378 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001379 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1380 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1381 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001382
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001383 status_t res;
1384 bool wasActive = false;
1385
1386 switch (mStatus) {
1387 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001388 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001389 return INVALID_OPERATION;
1390 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001391 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001392 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001393 case STATUS_UNCONFIGURED:
1394 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001395 // OK
1396 break;
1397 case STATUS_ACTIVE:
1398 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001399 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001400 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001401 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001402 return res;
1403 }
1404 wasActive = true;
1405 break;
1406 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001407 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001408 return INVALID_OPERATION;
1409 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001410 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001411
1412 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001413
Shuzhen Wang0129d522016-10-30 22:43:41 -07001414 if (consumers.size() == 0 && !hasDeferredConsumer) {
1415 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1416 return BAD_VALUE;
1417 }
Zhijun He5d677d12016-05-29 16:52:39 -07001418
Shuzhen Wang0129d522016-10-30 22:43:41 -07001419 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001420 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1421 return BAD_VALUE;
1422 }
1423
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001424 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001425 ssize_t blobBufferSize;
1426 if (dataSpace != HAL_DATASPACE_DEPTH) {
1427 blobBufferSize = getJpegBufferSize(width, height);
1428 if (blobBufferSize <= 0) {
1429 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1430 return BAD_VALUE;
1431 }
1432 } else {
1433 blobBufferSize = getPointCloudBufferSize();
1434 if (blobBufferSize <= 0) {
1435 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1436 return BAD_VALUE;
1437 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001438 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001439 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001440 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001441 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001442 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1443 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1444 if (rawOpaqueBufferSize <= 0) {
1445 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1446 return BAD_VALUE;
1447 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001448 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001449 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001450 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001451 } else if (isShared) {
1452 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1453 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001454 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001455 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001456 newStream = new Camera3OutputStream(mNextStreamId,
1457 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001458 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001460 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001461 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001462 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001463 }
Emilian Peev40ead602017-09-26 15:46:36 +01001464
1465 size_t consumerCount = consumers.size();
1466 for (size_t i = 0; i < consumerCount; i++) {
1467 int id = newStream->getSurfaceId(consumers[i]);
1468 if (id < 0) {
1469 SET_ERR_L("Invalid surface id");
1470 return BAD_VALUE;
1471 }
1472 if (surfaceIds != nullptr) {
1473 surfaceIds->push_back(id);
1474 }
1475 }
1476
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001477 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001478
Emilian Peev08dd2452017-04-06 16:55:14 +01001479 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001480
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 res = mOutputStreams.add(mNextStreamId, newStream);
1482 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001483 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 return res;
1485 }
1486
1487 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001488 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001489
1490 // Continue captures if active at start
1491 if (wasActive) {
1492 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001493 // Reuse current operating mode and session parameters for new stream config
1494 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001496 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1497 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 return res;
1499 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001500 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001501 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001502 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001504}
1505
Emilian Peev710c1422017-08-30 11:19:38 +01001506status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001507 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001508 if (nullptr == streamInfo) {
1509 return BAD_VALUE;
1510 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001511 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001512 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001513
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001514 switch (mStatus) {
1515 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001516 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001517 return INVALID_OPERATION;
1518 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001519 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001520 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001521 case STATUS_UNCONFIGURED:
1522 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 case STATUS_ACTIVE:
1524 // OK
1525 break;
1526 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001527 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 return INVALID_OPERATION;
1529 }
1530
1531 ssize_t idx = mOutputStreams.indexOfKey(id);
1532 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001533 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 return idx;
1535 }
1536
Emilian Peev710c1422017-08-30 11:19:38 +01001537 streamInfo->width = mOutputStreams[idx]->getWidth();
1538 streamInfo->height = mOutputStreams[idx]->getHeight();
1539 streamInfo->format = mOutputStreams[idx]->getFormat();
1540 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1541 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1542 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001543 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1544 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001546}
1547
1548status_t Camera3Device::setStreamTransform(int id,
1549 int transform) {
1550 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001551 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001553
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 switch (mStatus) {
1555 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001556 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001557 return INVALID_OPERATION;
1558 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001559 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001560 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001561 case STATUS_UNCONFIGURED:
1562 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001563 case STATUS_ACTIVE:
1564 // OK
1565 break;
1566 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001567 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001568 return INVALID_OPERATION;
1569 }
1570
1571 ssize_t idx = mOutputStreams.indexOfKey(id);
1572 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001573 CLOGE("Stream %d does not exist",
1574 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 return BAD_VALUE;
1576 }
1577
1578 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001579}
1580
1581status_t Camera3Device::deleteStream(int id) {
1582 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001583 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001584 Mutex::Autolock l(mLock);
1585 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001586
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001587 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001588
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001589 // CameraDevice semantics require device to already be idle before
1590 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001591 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001592 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001593 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001594 }
1595
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001596 if (mStatus == STATUS_ERROR) {
1597 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1598 __FUNCTION__, mId.string());
1599 return -EBUSY;
1600 }
1601
Igor Murashkin2fba5842013-04-22 14:03:54 -07001602 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001603 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001604 if (mInputStream != NULL && id == mInputStream->getId()) {
1605 deletedStream = mInputStream;
1606 mInputStream.clear();
1607 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001608 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001609 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001610 return BAD_VALUE;
1611 }
Zhijun He5f446352014-01-22 09:49:33 -08001612 }
1613
1614 // Delete output stream or the output part of a bi-directional stream.
1615 if (outputStreamIdx != NAME_NOT_FOUND) {
1616 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001617 mOutputStreams.removeItem(id);
1618 }
1619
1620 // Free up the stream endpoint so that it can be used by some other stream
1621 res = deletedStream->disconnect();
1622 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001623 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001624 // fall through since we want to still list the stream as deleted.
1625 }
1626 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001627 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001628
1629 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001630}
1631
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001632status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001633 ATRACE_CALL();
1634 ALOGV("%s: E", __FUNCTION__);
1635
1636 Mutex::Autolock il(mInterfaceLock);
1637 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001638
Emilian Peev811d2952018-05-25 11:08:40 +01001639 // In case the client doesn't include any session parameter, try a
1640 // speculative configuration using the values from the last cached
1641 // default request.
1642 if (sessionParams.isEmpty() &&
1643 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1644 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1645 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1646 mLastTemplateId);
1647 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1648 operatingMode);
1649 }
1650
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001651 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1652}
1653
1654status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1655 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001656 //Filter out any incoming session parameters
1657 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001658 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1659 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001660 CameraMetadata filteredParams(availableSessionKeys.count);
1661 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1662 filteredParams.getAndLock());
1663 set_camera_metadata_vendor_id(meta, mVendorTagId);
1664 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001665 if (availableSessionKeys.count > 0) {
1666 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1667 camera_metadata_ro_entry entry = params.find(
1668 availableSessionKeys.data.i32[i]);
1669 if (entry.count > 0) {
1670 filteredParams.update(entry);
1671 }
1672 }
1673 }
1674
1675 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001676}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001677
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001678status_t Camera3Device::getInputBufferProducer(
1679 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001680 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001681 Mutex::Autolock il(mInterfaceLock);
1682 Mutex::Autolock l(mLock);
1683
1684 if (producer == NULL) {
1685 return BAD_VALUE;
1686 } else if (mInputStream == NULL) {
1687 return INVALID_OPERATION;
1688 }
1689
1690 return mInputStream->getInputBufferProducer(producer);
1691}
1692
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001693status_t Camera3Device::createDefaultRequest(int templateId,
1694 CameraMetadata *request) {
1695 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001696 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001697
1698 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1699 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1700 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1701 return BAD_VALUE;
1702 }
1703
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001704 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001705
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001706 {
1707 Mutex::Autolock l(mLock);
1708 switch (mStatus) {
1709 case STATUS_ERROR:
1710 CLOGE("Device has encountered a serious error");
1711 return INVALID_OPERATION;
1712 case STATUS_UNINITIALIZED:
1713 CLOGE("Device is not initialized!");
1714 return INVALID_OPERATION;
1715 case STATUS_UNCONFIGURED:
1716 case STATUS_CONFIGURED:
1717 case STATUS_ACTIVE:
1718 // OK
1719 break;
1720 default:
1721 SET_ERR_L("Unexpected status: %d", mStatus);
1722 return INVALID_OPERATION;
1723 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001724
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001725 if (!mRequestTemplateCache[templateId].isEmpty()) {
1726 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001727 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001728 return OK;
1729 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001730 }
1731
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001732 camera_metadata_t *rawRequest;
1733 status_t res = mInterface->constructDefaultRequestSettings(
1734 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001735
1736 {
1737 Mutex::Autolock l(mLock);
1738 if (res == BAD_VALUE) {
1739 ALOGI("%s: template %d is not supported on this camera device",
1740 __FUNCTION__, templateId);
1741 return res;
1742 } else if (res != OK) {
1743 CLOGE("Unable to construct request template %d: %s (%d)",
1744 templateId, strerror(-res), res);
1745 return res;
1746 }
1747
1748 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1749 mRequestTemplateCache[templateId].acquire(rawRequest);
1750
1751 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001752 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001753 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001754 return OK;
1755}
1756
1757status_t Camera3Device::waitUntilDrained() {
1758 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001759 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001760 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001761 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001762
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001763 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001764}
1765
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001766status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001767 switch (mStatus) {
1768 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001769 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001770 ALOGV("%s: Already idle", __FUNCTION__);
1771 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001772 case STATUS_CONFIGURED:
1773 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001774 case STATUS_ERROR:
1775 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001776 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001777 break;
1778 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001779 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001780 return INVALID_OPERATION;
1781 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001782 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1783 maxExpectedDuration);
1784 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001785 if (res != OK) {
1786 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1787 res);
1788 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001789 return res;
1790}
1791
Ruben Brunk183f0562015-08-12 12:55:02 -07001792
1793void Camera3Device::internalUpdateStatusLocked(Status status) {
1794 mStatus = status;
1795 mRecentStatusUpdates.add(mStatus);
1796 mStatusChanged.broadcast();
1797}
1798
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001799void Camera3Device::pauseStateNotify(bool enable) {
1800 Mutex::Autolock il(mInterfaceLock);
1801 Mutex::Autolock l(mLock);
1802
1803 mPauseStateNotify = enable;
1804}
1805
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001806// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001807status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001808 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001809
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001810 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1811 maxExpectedDuration);
1812 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001813 if (res != OK) {
1814 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001815 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001816 }
1817
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001818 return res;
1819}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001820
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001821// Resume after internalPauseAndWaitLocked
1822status_t Camera3Device::internalResumeLocked() {
1823 status_t res;
1824
1825 mRequestThread->setPaused(false);
1826
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001827 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1828 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001829 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1830 if (res != OK) {
1831 SET_ERR_L("Can't transition to active in %f seconds!",
1832 kActiveTimeout/1e9);
1833 }
1834 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001835 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001836}
1837
Ruben Brunk183f0562015-08-12 12:55:02 -07001838status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001839 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001840
1841 size_t startIndex = 0;
1842 if (mStatusWaiters == 0) {
1843 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1844 // this status list
1845 mRecentStatusUpdates.clear();
1846 } else {
1847 // If other threads are waiting on updates to this status list, set the position of the
1848 // first element that this list will check rather than clearing the list.
1849 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001850 }
1851
Ruben Brunk183f0562015-08-12 12:55:02 -07001852 mStatusWaiters++;
1853
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001854 bool stateSeen = false;
1855 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001856 if (active == (mStatus == STATUS_ACTIVE)) {
1857 // Desired state is current
1858 break;
1859 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001860
1861 res = mStatusChanged.waitRelative(mLock, timeout);
1862 if (res != OK) break;
1863
Ruben Brunk183f0562015-08-12 12:55:02 -07001864 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1865 // transitions.
1866 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1867 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1868 __FUNCTION__);
1869
1870 // Encountered desired state since we began waiting
1871 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001872 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1873 stateSeen = true;
1874 break;
1875 }
1876 }
1877 } while (!stateSeen);
1878
Ruben Brunk183f0562015-08-12 12:55:02 -07001879 mStatusWaiters--;
1880
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001881 return res;
1882}
1883
1884
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001885status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001886 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001887 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001888
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001889 if (listener != NULL && mListener != NULL) {
1890 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1891 }
1892 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001893 mRequestThread->setNotificationListener(listener);
1894 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001895
1896 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001897}
1898
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001899bool Camera3Device::willNotify3A() {
1900 return false;
1901}
1902
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001903status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001904 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001905 status_t res;
1906 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001907
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001908 while (mResultQueue.empty()) {
1909 res = mResultSignal.waitRelative(mOutputLock, timeout);
1910 if (res == TIMED_OUT) {
1911 return res;
1912 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001913 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1914 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001915 return res;
1916 }
1917 }
1918 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001919}
1920
Jianing Weicb0652e2014-03-12 18:29:36 -07001921status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001922 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001923 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001924
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001925 if (mResultQueue.empty()) {
1926 return NOT_ENOUGH_DATA;
1927 }
1928
Jianing Weicb0652e2014-03-12 18:29:36 -07001929 if (frame == NULL) {
1930 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1931 return BAD_VALUE;
1932 }
1933
1934 CaptureResult &result = *(mResultQueue.begin());
1935 frame->mResultExtras = result.mResultExtras;
1936 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001937 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001938 mResultQueue.erase(mResultQueue.begin());
1939
1940 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001941}
1942
1943status_t Camera3Device::triggerAutofocus(uint32_t id) {
1944 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001945 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001946
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001947 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1948 // Mix-in this trigger into the next request and only the next request.
1949 RequestTrigger trigger[] = {
1950 {
1951 ANDROID_CONTROL_AF_TRIGGER,
1952 ANDROID_CONTROL_AF_TRIGGER_START
1953 },
1954 {
1955 ANDROID_CONTROL_AF_TRIGGER_ID,
1956 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001957 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001958 };
1959
1960 return mRequestThread->queueTrigger(trigger,
1961 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001962}
1963
1964status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1965 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001966 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001967
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001968 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1969 // Mix-in this trigger into the next request and only the next request.
1970 RequestTrigger trigger[] = {
1971 {
1972 ANDROID_CONTROL_AF_TRIGGER,
1973 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1974 },
1975 {
1976 ANDROID_CONTROL_AF_TRIGGER_ID,
1977 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001978 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001979 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001980
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001981 return mRequestThread->queueTrigger(trigger,
1982 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001983}
1984
1985status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1986 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001987 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001988
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001989 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1990 // Mix-in this trigger into the next request and only the next request.
1991 RequestTrigger trigger[] = {
1992 {
1993 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1994 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1995 },
1996 {
1997 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1998 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001999 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002000 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002001
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002002 return mRequestThread->queueTrigger(trigger,
2003 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002004}
2005
Jianing Weicb0652e2014-03-12 18:29:36 -07002006status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002007 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002008 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002009 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002010
Zhijun He7ef20392014-04-21 16:04:17 -07002011 {
2012 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002013 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002014 }
2015
Emilian Peev08dd2452017-04-06 16:55:14 +01002016 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002017}
2018
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002019status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002020 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2021}
2022
2023status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002024 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002025 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002026 Mutex::Autolock il(mInterfaceLock);
2027 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002028
2029 sp<Camera3StreamInterface> stream;
2030 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2031 if (outputStreamIdx == NAME_NOT_FOUND) {
2032 CLOGE("Stream %d does not exist", streamId);
2033 return BAD_VALUE;
2034 }
2035
2036 stream = mOutputStreams.editValueAt(outputStreamIdx);
2037
2038 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002039 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002040 return BAD_VALUE;
2041 }
2042
2043 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002044 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002045 return BAD_VALUE;
2046 }
2047
Ruben Brunkc78ac262015-08-13 17:58:46 -07002048 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002049}
2050
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002051status_t Camera3Device::tearDown(int streamId) {
2052 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002053 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002054 Mutex::Autolock il(mInterfaceLock);
2055 Mutex::Autolock l(mLock);
2056
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002057 sp<Camera3StreamInterface> stream;
2058 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2059 if (outputStreamIdx == NAME_NOT_FOUND) {
2060 CLOGE("Stream %d does not exist", streamId);
2061 return BAD_VALUE;
2062 }
2063
2064 stream = mOutputStreams.editValueAt(outputStreamIdx);
2065
2066 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2067 CLOGE("Stream %d is a target of a in-progress request", streamId);
2068 return BAD_VALUE;
2069 }
2070
2071 return stream->tearDown();
2072}
2073
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002074status_t Camera3Device::addBufferListenerForStream(int streamId,
2075 wp<Camera3StreamBufferListener> listener) {
2076 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002077 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002078 Mutex::Autolock il(mInterfaceLock);
2079 Mutex::Autolock l(mLock);
2080
2081 sp<Camera3StreamInterface> stream;
2082 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2083 if (outputStreamIdx == NAME_NOT_FOUND) {
2084 CLOGE("Stream %d does not exist", streamId);
2085 return BAD_VALUE;
2086 }
2087
2088 stream = mOutputStreams.editValueAt(outputStreamIdx);
2089 stream->addBufferListener(listener);
2090
2091 return OK;
2092}
2093
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002094/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002095 * Methods called by subclasses
2096 */
2097
2098void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002099 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002100 {
2101 // Need mLock to safely update state and synchronize to current
2102 // state of methods in flight.
2103 Mutex::Autolock l(mLock);
2104 // We can get various system-idle notices from the status tracker
2105 // while starting up. Only care about them if we've actually sent
2106 // in some requests recently.
2107 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2108 return;
2109 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002110 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2111 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002112 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002113
2114 // Skip notifying listener if we're doing some user-transparent
2115 // state changes
2116 if (mPauseStateNotify) return;
2117 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002118
2119 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002120 {
2121 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002122 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002123 }
2124 if (idle && listener != NULL) {
2125 listener->notifyIdle();
2126 }
2127}
2128
Shuzhen Wang758c2152017-01-10 18:26:18 -08002129status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002130 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002131 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002132 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2133 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002134
2135 if (surfaceIds == nullptr) {
2136 return BAD_VALUE;
2137 }
2138
Zhijun He5d677d12016-05-29 16:52:39 -07002139 Mutex::Autolock il(mInterfaceLock);
2140 Mutex::Autolock l(mLock);
2141
Shuzhen Wang758c2152017-01-10 18:26:18 -08002142 if (consumers.size() == 0) {
2143 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002144 return BAD_VALUE;
2145 }
2146
2147 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2148 if (idx == NAME_NOT_FOUND) {
2149 CLOGE("Stream %d is unknown", streamId);
2150 return idx;
2151 }
2152 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002153 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002154 if (res != OK) {
2155 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2156 return res;
2157 }
2158
Emilian Peev40ead602017-09-26 15:46:36 +01002159 for (auto &consumer : consumers) {
2160 int id = stream->getSurfaceId(consumer);
2161 if (id < 0) {
2162 CLOGE("Invalid surface id!");
2163 return BAD_VALUE;
2164 }
2165 surfaceIds->push_back(id);
2166 }
2167
Shuzhen Wang0129d522016-10-30 22:43:41 -07002168 if (stream->isConsumerConfigurationDeferred()) {
2169 if (!stream->isConfiguring()) {
2170 CLOGE("Stream %d was already fully configured.", streamId);
2171 return INVALID_OPERATION;
2172 }
Zhijun He5d677d12016-05-29 16:52:39 -07002173
Shuzhen Wang0129d522016-10-30 22:43:41 -07002174 res = stream->finishConfiguration();
2175 if (res != OK) {
2176 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2177 stream->getId(), strerror(-res), res);
2178 return res;
2179 }
Zhijun He5d677d12016-05-29 16:52:39 -07002180 }
2181
2182 return OK;
2183}
2184
Emilian Peev40ead602017-09-26 15:46:36 +01002185status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2186 const std::vector<OutputStreamInfo> &outputInfo,
2187 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2188 Mutex::Autolock il(mInterfaceLock);
2189 Mutex::Autolock l(mLock);
2190
2191 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2192 if (idx == NAME_NOT_FOUND) {
2193 CLOGE("Stream %d is unknown", streamId);
2194 return idx;
2195 }
2196
2197 for (const auto &it : removedSurfaceIds) {
2198 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2199 CLOGE("Shared surface still part of a pending request!");
2200 return -EBUSY;
2201 }
2202 }
2203
2204 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2205 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2206 if (res != OK) {
2207 CLOGE("Stream %d failed to update stream (error %d %s) ",
2208 streamId, res, strerror(-res));
2209 if (res == UNKNOWN_ERROR) {
2210 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2211 __FUNCTION__);
2212 }
2213 return res;
2214 }
2215
2216 return res;
2217}
2218
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002219status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2220 Mutex::Autolock il(mInterfaceLock);
2221 Mutex::Autolock l(mLock);
2222
2223 int idx = mOutputStreams.indexOfKey(streamId);
2224 if (idx == NAME_NOT_FOUND) {
2225 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2226 return BAD_VALUE;
2227 }
2228
2229 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2230 return stream->dropBuffers(dropping);
2231}
2232
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002233/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002234 * Camera3Device private methods
2235 */
2236
2237sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002238 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002239 ATRACE_CALL();
2240 status_t res;
2241
2242 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002243 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002244
2245 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002246 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002247 if (inputStreams.count > 0) {
2248 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002249 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002250 CLOGE("Request references unknown input stream %d",
2251 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002252 return NULL;
2253 }
2254 // Lazy completion of stream configuration (allocation/registration)
2255 // on first use
2256 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002257 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002258 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002259 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002260 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002261 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002262 return NULL;
2263 }
2264 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002265 // Check if stream is being prepared
2266 if (mInputStream->isPreparing()) {
2267 CLOGE("Request references an input stream that's being prepared!");
2268 return NULL;
2269 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002270
2271 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002272 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002273 }
2274
2275 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002276 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002277 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002278 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002279 return NULL;
2280 }
2281
2282 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002283 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002284 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002285 CLOGE("Request references unknown stream %d",
2286 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002287 return NULL;
2288 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002289 sp<Camera3OutputStreamInterface> stream =
2290 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002291
Zhijun He5d677d12016-05-29 16:52:39 -07002292 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002293 auto iter = surfaceMap.find(streams.data.i32[i]);
2294 if (iter != surfaceMap.end()) {
2295 const std::vector<size_t>& surfaces = iter->second;
2296 for (const auto& surface : surfaces) {
2297 if (stream->isConsumerConfigurationDeferred(surface)) {
2298 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2299 "due to deferred consumer", stream->getId(), surface);
2300 return NULL;
2301 }
2302 }
2303 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002304 }
2305
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002306 // Lazy completion of stream configuration (allocation/registration)
2307 // on first use
2308 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002309 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002310 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002311 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2312 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002313 return NULL;
2314 }
2315 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002316 // Check if stream is being prepared
2317 if (stream->isPreparing()) {
2318 CLOGE("Request references an output stream that's being prepared!");
2319 return NULL;
2320 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002321
2322 newRequest->mOutputStreams.push(stream);
2323 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002324 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002325 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002326
2327 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002328}
2329
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002330bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2331 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2332 Size size = mSupportedOpaqueInputSizes[i];
2333 if (size.width == width && size.height == height) {
2334 return true;
2335 }
2336 }
2337
2338 return false;
2339}
2340
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002341void Camera3Device::cancelStreamsConfigurationLocked() {
2342 int res = OK;
2343 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2344 res = mInputStream->cancelConfiguration();
2345 if (res != OK) {
2346 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2347 mInputStream->getId(), strerror(-res), res);
2348 }
2349 }
2350
2351 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2352 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2353 if (outputStream->isConfiguring()) {
2354 res = outputStream->cancelConfiguration();
2355 if (res != OK) {
2356 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2357 outputStream->getId(), strerror(-res), res);
2358 }
2359 }
2360 }
2361
2362 // Return state to that at start of call, so that future configures
2363 // properly clean things up
2364 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2365 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002366
2367 res = mPreparerThread->resume();
2368 if (res != OK) {
2369 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2370 }
2371}
2372
2373bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2374 ATRACE_CALL();
2375 bool ret = false;
2376
2377 Mutex::Autolock il(mInterfaceLock);
2378 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2379
2380 Mutex::Autolock l(mLock);
2381 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2382 if (rc == NO_ERROR) {
2383 mNeedConfig = true;
2384 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2385 if (rc == NO_ERROR) {
2386 ret = true;
2387 mPauseStateNotify = false;
2388 //Moving to active state while holding 'mLock' is important.
2389 //There could be pending calls to 'create-/deleteStream' which
2390 //will trigger another stream configuration while the already
2391 //present streams end up with outstanding buffers that will
2392 //not get drained.
2393 internalUpdateStatusLocked(STATUS_ACTIVE);
2394 } else {
2395 setErrorStateLocked("%s: Failed to re-configure camera: %d",
2396 __FUNCTION__, rc);
2397 }
2398 } else {
2399 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2400 }
2401
2402 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002403}
2404
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002405status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002406 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002407 ATRACE_CALL();
2408 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002409
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002410 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002411 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002412 return INVALID_OPERATION;
2413 }
2414
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002415 if (operatingMode < 0) {
2416 CLOGE("Invalid operating mode: %d", operatingMode);
2417 return BAD_VALUE;
2418 }
2419
2420 bool isConstrainedHighSpeed =
2421 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2422 operatingMode;
2423
2424 if (mOperatingMode != operatingMode) {
2425 mNeedConfig = true;
2426 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2427 mOperatingMode = operatingMode;
2428 }
2429
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002430 if (!mNeedConfig) {
2431 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2432 return OK;
2433 }
2434
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002435 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2436 // adding a dummy stream instead.
2437 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2438 if (mOutputStreams.size() == 0) {
2439 addDummyStreamLocked();
2440 } else {
2441 tryRemoveDummyStreamLocked();
2442 }
2443
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002444 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002445 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002446
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002447 mPreparerThread->pause();
2448
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002449 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002450 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002451 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2452
2453 Vector<camera3_stream_t*> streams;
2454 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002455 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002456
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002457
2458 if (mInputStream != NULL) {
2459 camera3_stream_t *inputStream;
2460 inputStream = mInputStream->startConfiguration();
2461 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002462 CLOGE("Can't start input stream configuration");
2463 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002464 return INVALID_OPERATION;
2465 }
2466 streams.add(inputStream);
2467 }
2468
2469 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002470
2471 // Don't configure bidi streams twice, nor add them twice to the list
2472 if (mOutputStreams[i].get() ==
2473 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2474
2475 config.num_streams--;
2476 continue;
2477 }
2478
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002479 camera3_stream_t *outputStream;
2480 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2481 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002482 CLOGE("Can't start output stream configuration");
2483 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002484 return INVALID_OPERATION;
2485 }
2486 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002487
2488 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2489 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002490 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2491 // always occupy the initial entry.
2492 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002493 getJpegBufferSize(outputStream->width, outputStream->height));
2494 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002495 }
2496
2497 config.streams = streams.editArray();
2498
2499 // Do the HAL configuration; will potentially touch stream
2500 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002501
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002502 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002503 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002504 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002505
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002506 if (res == BAD_VALUE) {
2507 // HAL rejected this set of streams as unsupported, clean up config
2508 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002509 CLOGE("Set of requested inputs/outputs not supported by HAL");
2510 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002511 return BAD_VALUE;
2512 } else if (res != OK) {
2513 // Some other kind of error from configure_streams - this is not
2514 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002515 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2516 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002517 return res;
2518 }
2519
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002520 // Finish all stream configuration immediately.
2521 // TODO: Try to relax this later back to lazy completion, which should be
2522 // faster
2523
Igor Murashkin073f8572013-05-02 14:59:28 -07002524 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002525 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002526 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002527 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002528 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002529 cancelStreamsConfigurationLocked();
2530 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002531 }
2532 }
2533
2534 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002535 sp<Camera3OutputStreamInterface> outputStream =
2536 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002537 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002538 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002539 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002540 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002541 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002542 cancelStreamsConfigurationLocked();
2543 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002544 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002545 }
2546 }
2547
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002548 // Request thread needs to know to avoid using repeat-last-settings protocol
2549 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002550 if (notifyRequestThread) {
2551 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2552 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002553
Zhijun He90f7c372016-08-16 16:19:43 -07002554 char value[PROPERTY_VALUE_MAX];
2555 property_get("camera.fifo.disable", value, "0");
2556 int32_t disableFifo = atoi(value);
2557 if (disableFifo != 1) {
2558 // Boost priority of request thread to SCHED_FIFO.
2559 pid_t requestThreadTid = mRequestThread->getTid();
2560 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002561 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002562 if (res != OK) {
2563 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2564 strerror(-res), res);
2565 } else {
2566 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2567 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002568 }
2569
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002570 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002571 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2572 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2573 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2574 sessionParams.unlock(newSessionParams);
2575 mSessionParams.unlock(currentSessionParams);
2576 if (updateSessionParams) {
2577 mSessionParams = sessionParams;
2578 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002579
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002580 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002581
Ruben Brunk183f0562015-08-12 12:55:02 -07002582 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2583 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002584
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002585 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002586
Zhijun He0a210512014-07-24 13:45:15 -07002587 // tear down the deleted streams after configure streams.
2588 mDeletedStreams.clear();
2589
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002590 auto rc = mPreparerThread->resume();
2591 if (rc != OK) {
2592 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2593 return rc;
2594 }
2595
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002596 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002597}
2598
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002599status_t Camera3Device::addDummyStreamLocked() {
2600 ATRACE_CALL();
2601 status_t res;
2602
2603 if (mDummyStreamId != NO_STREAM) {
2604 // Should never be adding a second dummy stream when one is already
2605 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002606 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2607 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002608 return INVALID_OPERATION;
2609 }
2610
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002611 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002612
2613 sp<Camera3OutputStreamInterface> dummyStream =
2614 new Camera3DummyStream(mNextStreamId);
2615
2616 res = mOutputStreams.add(mNextStreamId, dummyStream);
2617 if (res < 0) {
2618 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2619 return res;
2620 }
2621
2622 mDummyStreamId = mNextStreamId;
2623 mNextStreamId++;
2624
2625 return OK;
2626}
2627
2628status_t Camera3Device::tryRemoveDummyStreamLocked() {
2629 ATRACE_CALL();
2630 status_t res;
2631
2632 if (mDummyStreamId == NO_STREAM) return OK;
2633 if (mOutputStreams.size() == 1) return OK;
2634
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002635 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002636
2637 // Ok, have a dummy stream and there's at least one other output stream,
2638 // so remove the dummy
2639
2640 sp<Camera3StreamInterface> deletedStream;
2641 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2642 if (outputStreamIdx == NAME_NOT_FOUND) {
2643 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2644 return INVALID_OPERATION;
2645 }
2646
2647 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2648 mOutputStreams.removeItemsAt(outputStreamIdx);
2649
2650 // Free up the stream endpoint so that it can be used by some other stream
2651 res = deletedStream->disconnect();
2652 if (res != OK) {
2653 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2654 // fall through since we want to still list the stream as deleted.
2655 }
2656 mDeletedStreams.add(deletedStream);
2657 mDummyStreamId = NO_STREAM;
2658
2659 return res;
2660}
2661
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002662void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002663 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002664 Mutex::Autolock l(mLock);
2665 va_list args;
2666 va_start(args, fmt);
2667
2668 setErrorStateLockedV(fmt, args);
2669
2670 va_end(args);
2671}
2672
2673void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002674 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002675 Mutex::Autolock l(mLock);
2676 setErrorStateLockedV(fmt, args);
2677}
2678
2679void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2680 va_list args;
2681 va_start(args, fmt);
2682
2683 setErrorStateLockedV(fmt, args);
2684
2685 va_end(args);
2686}
2687
2688void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002689 // Print out all error messages to log
2690 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002691 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002692
2693 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002694 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002695
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002696 mErrorCause = errorCause;
2697
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002698 if (mRequestThread != nullptr) {
2699 mRequestThread->setPaused(true);
2700 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002701 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002702
2703 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002704 sp<NotificationListener> listener = mListener.promote();
2705 if (listener != NULL) {
2706 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002707 CaptureResultExtras());
2708 }
2709
2710 // Save stack trace. View by dumping it later.
2711 CameraTraces::saveTrace();
2712 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002713}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002714
2715/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002716 * In-flight request management
2717 */
2718
Jianing Weicb0652e2014-03-12 18:29:36 -07002719status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002720 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002721 bool hasAppCallback, nsecs_t maxExpectedDuration,
2722 std::set<String8>& physicalCameraIds) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002723 ATRACE_CALL();
2724 Mutex::Autolock l(mInFlightLock);
2725
2726 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002727 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002728 hasAppCallback, maxExpectedDuration, physicalCameraIds));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002729 if (res < 0) return res;
2730
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002731 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002732 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2733 // avoid a deadlock during reprocess requests.
2734 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002735 if (mStatusTracker != nullptr) {
2736 mStatusTracker->markComponentActive(mInFlightStatusId);
2737 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002738 }
2739
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002740 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002741 return OK;
2742}
2743
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002744void Camera3Device::returnOutputBuffers(
2745 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2746 nsecs_t timestamp) {
2747 for (size_t i = 0; i < numBuffers; i++)
2748 {
2749 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2750 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2751 // Note: stream may be deallocated at this point, if this buffer was
2752 // the last reference to it.
2753 if (res != OK) {
2754 ALOGE("Can't return buffer to its stream: %s (%d)",
2755 strerror(-res), res);
2756 }
2757 }
2758}
2759
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002760void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002761 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002762 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002763 mInFlightMap.removeItemsAt(idx, 1);
2764
2765 // Indicate idle inFlightMap to the status tracker
2766 if (mInFlightMap.size() == 0) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002767 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2768 // avoid a deadlock during reprocess requests.
2769 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002770 if (mStatusTracker != nullptr) {
2771 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2772 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002773 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002774 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002775}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002776
2777void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2778
2779 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2780 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2781
2782 nsecs_t sensorTimestamp = request.sensorTimestamp;
2783 nsecs_t shutterTimestamp = request.shutterTimestamp;
2784
2785 // Check if it's okay to remove the request from InFlightMap:
2786 // In the case of a successful request:
2787 // all input and output buffers, all result metadata, shutter callback
2788 // arrived.
2789 // In the case of a unsuccessful request:
2790 // all input and output buffers arrived.
2791 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002792 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002793 (request.haveResultMetadata && shutterTimestamp != 0))) {
2794 ATRACE_ASYNC_END("frame capture", frameNumber);
2795
Shuzhen Wang403044a2017-02-26 23:29:04 -08002796 // Sanity check - if sensor timestamp matches shutter timestamp in the
2797 // case of request having callback.
2798 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002799 sensorTimestamp != shutterTimestamp) {
2800 SET_ERR("sensor timestamp (%" PRId64
2801 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2802 sensorTimestamp, frameNumber, shutterTimestamp);
2803 }
2804
2805 // for an unsuccessful request, it may have pending output buffers to
2806 // return.
2807 assert(request.requestStatus != OK ||
2808 request.pendingOutputBuffers.size() == 0);
2809 returnOutputBuffers(request.pendingOutputBuffers.array(),
2810 request.pendingOutputBuffers.size(), 0);
2811
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002812 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002813 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2814 }
2815
2816 // Sanity check - if we have too many in-flight frames, something has
2817 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002818 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002819 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002820 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2821 kInFlightWarnLimitHighSpeed) {
2822 CLOGE("In-flight list too large for high speed configuration: %zu",
2823 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002824 }
2825}
2826
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002827void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002828 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002829 { // First return buffers cached in mInFlightMap
2830 Mutex::Autolock l(mInFlightLock);
2831 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2832 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2833 returnOutputBuffers(request.pendingOutputBuffers.array(),
2834 request.pendingOutputBuffers.size(), 0);
2835 }
2836 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002837 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002838 }
2839
2840 // Then return all inflight buffers not returned by HAL
2841 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2842 mInterface->getInflightBufferKeys(&inflightKeys);
2843
2844 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2845 for (auto& pair : inflightKeys) {
2846 int32_t frameNumber = pair.first;
2847 int32_t streamId = pair.second;
2848 buffer_handle_t* buffer;
2849 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2850 if (res != OK) {
2851 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2852 __FUNCTION__, frameNumber, streamId);
2853 continue;
2854 }
2855
2856 camera3_stream_buffer_t streamBuffer;
2857 streamBuffer.buffer = buffer;
2858 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2859 streamBuffer.acquire_fence = -1;
2860 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002861
2862 // First check if the buffer belongs to deleted stream
2863 bool streamDeleted = false;
2864 for (auto& stream : mDeletedStreams) {
2865 if (streamId == stream->getId()) {
2866 streamDeleted = true;
2867 // Return buffer to deleted stream
2868 camera3_stream* halStream = stream->asHalStream();
2869 streamBuffer.stream = halStream;
2870 switch (halStream->stream_type) {
2871 case CAMERA3_STREAM_OUTPUT:
2872 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2873 if (res != OK) {
2874 ALOGE("%s: Can't return output buffer for frame %d to"
2875 " stream %d: %s (%d)", __FUNCTION__,
2876 frameNumber, streamId, strerror(-res), res);
2877 }
2878 break;
2879 case CAMERA3_STREAM_INPUT:
2880 res = stream->returnInputBuffer(streamBuffer);
2881 if (res != OK) {
2882 ALOGE("%s: Can't return input buffer for frame %d to"
2883 " stream %d: %s (%d)", __FUNCTION__,
2884 frameNumber, streamId, strerror(-res), res);
2885 }
2886 break;
2887 default: // Bi-direcitonal stream is deprecated
2888 ALOGE("%s: stream %d has unknown stream type %d",
2889 __FUNCTION__, streamId, halStream->stream_type);
2890 break;
2891 }
2892 break;
2893 }
2894 }
2895 if (streamDeleted) {
2896 continue;
2897 }
2898
2899 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002900 if (streamId == inputStreamId) {
2901 streamBuffer.stream = mInputStream->asHalStream();
2902 res = mInputStream->returnInputBuffer(streamBuffer);
2903 if (res != OK) {
2904 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002905 " stream %d: %s (%d)", __FUNCTION__,
2906 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002907 }
2908 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002909 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2910 if (idx == NAME_NOT_FOUND) {
2911 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2912 continue;
2913 }
2914 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002915 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2916 }
2917 }
2918}
2919
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002920void Camera3Device::insertResultLocked(CaptureResult *result,
2921 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002922 if (result == nullptr) return;
2923
Emilian Peev71c73a22017-03-21 16:35:51 +00002924 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2925 result->mMetadata.getAndLock());
2926 set_camera_metadata_vendor_id(meta, mVendorTagId);
2927 result->mMetadata.unlock(meta);
2928
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002929 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2930 (int32_t*)&frameNumber, 1) != OK) {
2931 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2932 return;
2933 }
2934
2935 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2936 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2937 return;
2938 }
2939
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002940 // Valid result, insert into queue
2941 List<CaptureResult>::iterator queuedResult =
2942 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2943 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2944 ", burstId = %" PRId32, __FUNCTION__,
2945 queuedResult->mResultExtras.requestId,
2946 queuedResult->mResultExtras.frameNumber,
2947 queuedResult->mResultExtras.burstId);
2948
2949 mResultSignal.signal();
2950}
2951
2952
2953void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002954 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002955 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002956 Mutex::Autolock l(mOutputLock);
2957
2958 CaptureResult captureResult;
2959 captureResult.mResultExtras = resultExtras;
2960 captureResult.mMetadata = partialResult;
2961
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002962 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002963}
2964
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002965
2966void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2967 CaptureResultExtras &resultExtras,
2968 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002969 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002970 bool reprocess,
2971 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002972 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002973 if (pendingMetadata.isEmpty())
2974 return;
2975
2976 Mutex::Autolock l(mOutputLock);
2977
2978 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002979 if (reprocess) {
2980 if (frameNumber < mNextReprocessResultFrameNumber) {
2981 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002982 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002983 frameNumber, mNextReprocessResultFrameNumber);
2984 return;
2985 }
2986 mNextReprocessResultFrameNumber = frameNumber + 1;
2987 } else {
2988 if (frameNumber < mNextResultFrameNumber) {
2989 SET_ERR("Out-of-order capture result metadata submitted! "
2990 "(got frame number %d, expecting %d)",
2991 frameNumber, mNextResultFrameNumber);
2992 return;
2993 }
2994 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002995 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002996
2997 CaptureResult captureResult;
2998 captureResult.mResultExtras = resultExtras;
2999 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003000 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003001
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003002 // Append any previous partials to form a complete result
3003 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3004 captureResult.mMetadata.append(collectedPartialResult);
3005 }
3006
3007 captureResult.mMetadata.sort();
3008
3009 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003010 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3011 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003012 SET_ERR("No timestamp provided by HAL for frame %d!",
3013 frameNumber);
3014 return;
3015 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003016 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3017 camera_metadata_entry timestamp =
3018 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3019 if (timestamp.count == 0) {
3020 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3021 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3022 return;
3023 }
3024 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003025
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003026 // Fix up some result metadata to account for HAL-level distortion correction
3027 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3028 if (res != OK) {
3029 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3030 frameNumber, strerror(res), res);
3031 return;
3032 }
3033
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003034 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3035 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3036
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003037 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003038}
3039
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003040/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003041 * Camera HAL device callback methods
3042 */
3043
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003044void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003045 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003046
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003047 status_t res;
3048
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003049 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003050 if (result->result == NULL && result->num_output_buffers == 0 &&
3051 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003052 SET_ERR("No result data provided by HAL for frame %d",
3053 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003054 return;
3055 }
Zhijun He204e3292014-07-14 17:09:23 -07003056
Zhijun He204e3292014-07-14 17:09:23 -07003057 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003058 result->result != NULL &&
3059 result->partial_result != 1) {
3060 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3061 " if partial result is not supported",
3062 frameNumber, result->partial_result);
3063 return;
3064 }
3065
3066 bool isPartialResult = false;
3067 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003068 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003069
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003070 // Get shutter timestamp and resultExtras from list of in-flight requests,
3071 // where it was added by the shutter notification for this frame. If the
3072 // shutter timestamp isn't received yet, append the output buffers to the
3073 // in-flight request and they will be returned when the shutter timestamp
3074 // arrives. Update the in-flight status and remove the in-flight entry if
3075 // all result data and shutter timestamp have been received.
3076 nsecs_t shutterTimestamp = 0;
3077
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003078 {
3079 Mutex::Autolock l(mInFlightLock);
3080 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3081 if (idx == NAME_NOT_FOUND) {
3082 SET_ERR("Unknown frame number for capture result: %d",
3083 frameNumber);
3084 return;
3085 }
3086 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003087 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3088 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003089 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003090 __FUNCTION__, request.resultExtras.requestId,
3091 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003092 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003093 // Always update the partial count to the latest one if it's not 0
3094 // (buffers only). When framework aggregates adjacent partial results
3095 // into one, the latest partial count will be used.
3096 if (result->partial_result != 0)
3097 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003098
3099 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003100 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003101 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3102 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3103 " the range of [1, %d] when metadata is included in the result",
3104 frameNumber, result->partial_result, mNumPartialResults);
3105 return;
3106 }
3107 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003108 if (isPartialResult && result->num_physcam_metadata) {
3109 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3110 " physical camera result", frameNumber);
3111 return;
3112 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003113 if (isPartialResult) {
3114 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003115 }
3116
Shuzhen Wang4a472662017-02-26 23:29:04 -08003117 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003118 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003119 sendPartialCaptureResult(result->result, request.resultExtras,
3120 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003121 }
3122 }
3123
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003124 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003125 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003126
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003127 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003128 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003129 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3130 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3131 request.physicalCameraIds.size(), result->num_physcam_metadata);
3132 return;
3133 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003134 if (request.haveResultMetadata) {
3135 SET_ERR("Called multiple times with metadata for frame %d",
3136 frameNumber);
3137 return;
3138 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003139 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3140 String8 physicalId(result->physcam_ids[i]);
3141 std::set<String8>::iterator cameraIdIter =
3142 request.physicalCameraIds.find(physicalId);
3143 if (cameraIdIter != request.physicalCameraIds.end()) {
3144 request.physicalCameraIds.erase(cameraIdIter);
3145 } else {
3146 SET_ERR("Total result for frame %d has already returned for camera %s",
3147 frameNumber, physicalId.c_str());
3148 return;
3149 }
3150 }
Zhijun He204e3292014-07-14 17:09:23 -07003151 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003152 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003153 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003154 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003155 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003156 request.haveResultMetadata = true;
3157 }
3158
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003159 uint32_t numBuffersReturned = result->num_output_buffers;
3160 if (result->input_buffer != NULL) {
3161 if (hasInputBufferInRequest) {
3162 numBuffersReturned += 1;
3163 } else {
3164 ALOGW("%s: Input buffer should be NULL if there is no input"
3165 " buffer sent in the request",
3166 __FUNCTION__);
3167 }
3168 }
3169 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003170 if (request.numBuffersLeft < 0) {
3171 SET_ERR("Too many buffers returned for frame %d",
3172 frameNumber);
3173 return;
3174 }
3175
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003176 camera_metadata_ro_entry_t entry;
3177 res = find_camera_metadata_ro_entry(result->result,
3178 ANDROID_SENSOR_TIMESTAMP, &entry);
3179 if (res == OK && entry.count == 1) {
3180 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003181 }
3182
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003183 // If shutter event isn't received yet, append the output buffers to
3184 // the in-flight request. Otherwise, return the output buffers to
3185 // streams.
3186 if (shutterTimestamp == 0) {
3187 request.pendingOutputBuffers.appendArray(result->output_buffers,
3188 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003189 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003190 returnOutputBuffers(result->output_buffers,
3191 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07003192 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003193
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003194 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003195 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3196 CameraMetadata physicalMetadata;
3197 physicalMetadata.append(result->physcam_metadata[i]);
3198 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3199 physicalMetadata});
3200 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003201 if (shutterTimestamp == 0) {
3202 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003203 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003204 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003205 CameraMetadata metadata;
3206 metadata = result->result;
3207 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003208 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003209 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003210 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003211 }
3212
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003213 removeInFlightRequestIfReadyLocked(idx);
3214 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003215
Zhijun Hef0d962a2014-06-30 10:24:11 -07003216 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003217 if (hasInputBufferInRequest) {
3218 Camera3Stream *stream =
3219 Camera3Stream::cast(result->input_buffer->stream);
3220 res = stream->returnInputBuffer(*(result->input_buffer));
3221 // Note: stream may be deallocated at this point, if this buffer was the
3222 // last reference to it.
3223 if (res != OK) {
3224 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3225 " its stream:%s (%d)", __FUNCTION__,
3226 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003227 }
3228 } else {
3229 ALOGW("%s: Input buffer should be NULL if there is no input"
3230 " buffer sent in the request, skipping input buffer return.",
3231 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003232 }
3233 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003234}
3235
3236void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003237 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003238 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003239 {
3240 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003241 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003242 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003243
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003244 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003245 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003246 return;
3247 }
3248
3249 switch (msg->type) {
3250 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003251 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003252 break;
3253 }
3254 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003255 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003256 break;
3257 }
3258 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003259 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003260 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003261 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003262}
3263
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003264void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003265 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003266 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003267 // Map camera HAL error codes to ICameraDeviceCallback error codes
3268 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003269 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003270 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003271 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003272 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003273 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003274 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003275 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003276 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003277 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003278 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003279 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003280 };
3281
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003282 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003283 ((msg.error_code >= 0) &&
3284 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3285 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003286 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003287
3288 int streamId = 0;
3289 if (msg.error_stream != NULL) {
3290 Camera3Stream *stream =
3291 Camera3Stream::cast(msg.error_stream);
3292 streamId = stream->getId();
3293 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003294 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3295 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003296 streamId, msg.error_code);
3297
3298 CaptureResultExtras resultExtras;
3299 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003300 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003301 // SET_ERR calls notifyError
3302 SET_ERR("Camera HAL reported serious device error");
3303 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003304 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3305 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3306 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003307 {
3308 Mutex::Autolock l(mInFlightLock);
3309 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3310 if (idx >= 0) {
3311 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3312 r.requestStatus = msg.error_code;
3313 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003314 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3315 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3316 errorCode) {
3317 r.skipResultMetadata = true;
3318 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003319 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3320 errorCode) {
3321 // In case of missing result check whether the buffers
3322 // returned. If they returned, then remove inflight
3323 // request.
3324 removeInFlightRequestIfReadyLocked(idx);
3325 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003326 } else {
3327 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003328 ALOGE("Camera %s: %s: cannot find in-flight request on "
3329 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003330 resultExtras.frameNumber);
3331 }
3332 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003333 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003334 if (listener != NULL) {
3335 listener->notifyError(errorCode, resultExtras);
3336 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003337 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003338 }
3339 break;
3340 default:
3341 // SET_ERR calls notifyError
3342 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3343 break;
3344 }
3345}
3346
3347void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003348 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003349 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003350 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003351
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003352 // Set timestamp for the request in the in-flight tracking
3353 // and get the request ID to send upstream
3354 {
3355 Mutex::Autolock l(mInFlightLock);
3356 idx = mInFlightMap.indexOfKey(msg.frame_number);
3357 if (idx >= 0) {
3358 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003359
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003360 // Verify ordering of shutter notifications
3361 {
3362 Mutex::Autolock l(mOutputLock);
3363 // TODO: need to track errors for tighter bounds on expected frame number.
3364 if (r.hasInputBuffer) {
3365 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3366 SET_ERR("Shutter notification out-of-order. Expected "
3367 "notification for frame %d, got frame %d",
3368 mNextReprocessShutterFrameNumber, msg.frame_number);
3369 return;
3370 }
3371 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3372 } else {
3373 if (msg.frame_number < mNextShutterFrameNumber) {
3374 SET_ERR("Shutter notification out-of-order. Expected "
3375 "notification for frame %d, got frame %d",
3376 mNextShutterFrameNumber, msg.frame_number);
3377 return;
3378 }
3379 mNextShutterFrameNumber = msg.frame_number + 1;
3380 }
3381 }
3382
Shuzhen Wang4a472662017-02-26 23:29:04 -08003383 r.shutterTimestamp = msg.timestamp;
3384 if (r.hasCallback) {
3385 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003386 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003387 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003388 // Call listener, if any
3389 if (listener != NULL) {
3390 listener->notifyShutter(r.resultExtras, msg.timestamp);
3391 }
3392 // send pending result and buffers
3393 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3394 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003395 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003396 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003397 returnOutputBuffers(r.pendingOutputBuffers.array(),
3398 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3399 r.pendingOutputBuffers.clear();
3400
3401 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003402 }
3403 }
3404 if (idx < 0) {
3405 SET_ERR("Shutter notification for non-existent frame number %d",
3406 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003407 }
3408}
3409
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003410CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003411 ALOGV("%s", __FUNCTION__);
3412
Igor Murashkin1e479c02013-09-06 16:55:14 -07003413 CameraMetadata retVal;
3414
3415 if (mRequestThread != NULL) {
3416 retVal = mRequestThread->getLatestRequest();
3417 }
3418
Igor Murashkin1e479c02013-09-06 16:55:14 -07003419 return retVal;
3420}
3421
Jianing Weicb0652e2014-03-12 18:29:36 -07003422
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003423void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3424 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3425 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3426}
3427
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003428/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003429 * HalInterface inner class methods
3430 */
3431
Yifan Hongf79b5542017-04-11 14:44:25 -07003432Camera3Device::HalInterface::HalInterface(
3433 sp<ICameraDeviceSession> &session,
3434 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003435 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003436 mRequestMetadataQueue(queue) {
3437 // Check with hardware service manager if we can downcast these interfaces
3438 // Somewhat expensive, so cache the results at startup
3439 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3440 if (castResult_3_4.isOk()) {
3441 mHidlSession_3_4 = castResult_3_4;
3442 }
3443 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3444 if (castResult_3_3.isOk()) {
3445 mHidlSession_3_3 = castResult_3_3;
3446 }
3447}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003448
Emilian Peev31abd0a2017-05-11 18:37:46 +01003449Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003450
3451Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003452 mHidlSession(other.mHidlSession),
3453 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003454
3455bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003456 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003457}
3458
3459void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003460 mHidlSession_3_4.clear();
3461 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003462 mHidlSession.clear();
3463}
3464
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003465bool Camera3Device::HalInterface::supportBatchRequest() {
3466 return mHidlSession != nullptr;
3467}
3468
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003469status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3470 camera3_request_template_t templateId,
3471 /*out*/ camera_metadata_t **requestTemplate) {
3472 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3473 if (!valid()) return INVALID_OPERATION;
3474 status_t res = OK;
3475
Emilian Peev31abd0a2017-05-11 18:37:46 +01003476 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003477
3478 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003479 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003480 status = s;
3481 if (status == common::V1_0::Status::OK) {
3482 const camera_metadata *r =
3483 reinterpret_cast<const camera_metadata_t*>(request.data());
3484 size_t expectedSize = request.size();
3485 int ret = validate_camera_metadata_structure(r, &expectedSize);
3486 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3487 *requestTemplate = clone_camera_metadata(r);
3488 if (*requestTemplate == nullptr) {
3489 ALOGE("%s: Unable to clone camera metadata received from HAL",
3490 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003491 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003492 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003493 } else {
3494 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3495 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003496 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003497 }
3498 };
3499 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003500 RequestTemplate id;
3501 switch (templateId) {
3502 case CAMERA3_TEMPLATE_PREVIEW:
3503 id = RequestTemplate::PREVIEW;
3504 break;
3505 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3506 id = RequestTemplate::STILL_CAPTURE;
3507 break;
3508 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3509 id = RequestTemplate::VIDEO_RECORD;
3510 break;
3511 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3512 id = RequestTemplate::VIDEO_SNAPSHOT;
3513 break;
3514 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3515 id = RequestTemplate::ZERO_SHUTTER_LAG;
3516 break;
3517 case CAMERA3_TEMPLATE_MANUAL:
3518 id = RequestTemplate::MANUAL;
3519 break;
3520 default:
3521 // Unknown template ID, or this HAL is too old to support it
3522 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003523 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003524 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003525
Emilian Peev31abd0a2017-05-11 18:37:46 +01003526 if (!err.isOk()) {
3527 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3528 res = DEAD_OBJECT;
3529 } else {
3530 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003531 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003532
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003533 return res;
3534}
3535
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003536status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003537 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003538 ATRACE_NAME("CameraHal::configureStreams");
3539 if (!valid()) return INVALID_OPERATION;
3540 status_t res = OK;
3541
Emilian Peev31abd0a2017-05-11 18:37:46 +01003542 // Convert stream config to HIDL
3543 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003544 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3545 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3546 requestedConfiguration3_2.streams.resize(config->num_streams);
3547 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003548 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003549 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3550 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003551 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003552
Emilian Peev31abd0a2017-05-11 18:37:46 +01003553 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3554 cam3stream->setBufferFreedListener(this);
3555 int streamId = cam3stream->getId();
3556 StreamType streamType;
3557 switch (src->stream_type) {
3558 case CAMERA3_STREAM_OUTPUT:
3559 streamType = StreamType::OUTPUT;
3560 break;
3561 case CAMERA3_STREAM_INPUT:
3562 streamType = StreamType::INPUT;
3563 break;
3564 default:
3565 ALOGE("%s: Stream %d: Unsupported stream type %d",
3566 __FUNCTION__, streamId, config->streams[i]->stream_type);
3567 return BAD_VALUE;
3568 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003569 dst3_2.id = streamId;
3570 dst3_2.streamType = streamType;
3571 dst3_2.width = src->width;
3572 dst3_2.height = src->height;
3573 dst3_2.format = mapToPixelFormat(src->format);
3574 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3575 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3576 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3577 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003578 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003579 if (src->physical_camera_id != nullptr) {
3580 dst3_4.physicalCameraId = src->physical_camera_id;
3581 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003582
3583 activeStreams.insert(streamId);
3584 // Create Buffer ID map if necessary
3585 if (mBufferIdMaps.count(streamId) == 0) {
3586 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3587 }
3588 }
3589 // remove BufferIdMap for deleted streams
3590 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3591 int streamId = it->first;
3592 bool active = activeStreams.count(streamId) > 0;
3593 if (!active) {
3594 it = mBufferIdMaps.erase(it);
3595 } else {
3596 ++it;
3597 }
3598 }
3599
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003600 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003601 res = mapToStreamConfigurationMode(
3602 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003603 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003604 if (res != OK) {
3605 return res;
3606 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003607 requestedConfiguration3_2.operationMode = operationMode;
3608 requestedConfiguration3_4.operationMode = operationMode;
3609 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003610 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3611 get_camera_metadata_size(sessionParams));
3612
Emilian Peev31abd0a2017-05-11 18:37:46 +01003613 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003614 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003615 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003616
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003617 // See if we have v3.4 or v3.3 HAL
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003618 if (mHidlSession_3_4 != nullptr) {
3619 // We do; use v3.4 for the call
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003620 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003621 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003622 auto err = mHidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003623 [&status, &finalConfiguration3_4]
3624 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3625 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003626 status = s;
3627 });
3628 if (!err.isOk()) {
3629 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3630 return DEAD_OBJECT;
3631 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003632 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3633 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3634 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3635 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003636 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003637 // We do; use v3.3 for the call
3638 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003639 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003640 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003641 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003642 finalConfiguration = halConfiguration;
3643 status = s;
3644 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003645 if (!err.isOk()) {
3646 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3647 return DEAD_OBJECT;
3648 }
3649 } else {
3650 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3651 ALOGV("%s: v3.2 device found", __FUNCTION__);
3652 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003653 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003654 [&status, &finalConfiguration_3_2]
3655 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3656 finalConfiguration_3_2 = halConfiguration;
3657 status = s;
3658 });
3659 if (!err.isOk()) {
3660 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3661 return DEAD_OBJECT;
3662 }
3663 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3664 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3665 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3666 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003667 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003668 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003669 }
3670
3671 if (status != common::V1_0::Status::OK ) {
3672 return CameraProviderManager::mapToStatusT(status);
3673 }
3674
3675 // And convert output stream configuration from HIDL
3676
3677 for (size_t i = 0; i < config->num_streams; i++) {
3678 camera3_stream_t *dst = config->streams[i];
3679 int streamId = Camera3Stream::cast(dst)->getId();
3680
3681 // Start scan at i, with the assumption that the stream order matches
3682 size_t realIdx = i;
3683 bool found = false;
3684 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003685 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003686 found = true;
3687 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003688 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003689 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3690 }
3691 if (!found) {
3692 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3693 __FUNCTION__, streamId);
3694 return INVALID_OPERATION;
3695 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003696 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003697
Emilian Peev710c1422017-08-30 11:19:38 +01003698 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3699 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003700 dstStream->setDataSpaceOverride(false);
3701 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3702 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3703
Emilian Peev31abd0a2017-05-11 18:37:46 +01003704 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3705 if (dst->format != overrideFormat) {
3706 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3707 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003708 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003709 if (dst->data_space != overrideDataSpace) {
3710 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3711 streamId, dst->format);
3712 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003713 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003714 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003715 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3716
Emilian Peev31abd0a2017-05-11 18:37:46 +01003717 // Override allowed with IMPLEMENTATION_DEFINED
3718 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003719 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003720 }
3721
Emilian Peev31abd0a2017-05-11 18:37:46 +01003722 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003723 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003724 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003725 __FUNCTION__, streamId);
3726 return INVALID_OPERATION;
3727 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003728 dstStream->setUsage(
3729 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003730 } else {
3731 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003732 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003733 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3734 __FUNCTION__, streamId);
3735 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003736 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003737 dstStream->setUsage(
3738 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003739 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003740 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003741 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003742
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003743 return res;
3744}
3745
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003746void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3747 /*out*/device::V3_2::CaptureRequest* captureRequest,
3748 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003749 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003750 if (captureRequest == nullptr || handlesCreated == nullptr) {
3751 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3752 __FUNCTION__, captureRequest, handlesCreated);
3753 return;
3754 }
3755
3756 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003757
3758 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003759
3760 {
3761 std::lock_guard<std::mutex> lock(mInflightLock);
3762 if (request->input_buffer != nullptr) {
3763 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3764 buffer_handle_t buf = *(request->input_buffer->buffer);
3765 auto pair = getBufferId(buf, streamId);
3766 bool isNewBuffer = pair.first;
3767 uint64_t bufferId = pair.second;
3768 captureRequest->inputBuffer.streamId = streamId;
3769 captureRequest->inputBuffer.bufferId = bufferId;
3770 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3771 captureRequest->inputBuffer.status = BufferStatus::OK;
3772 native_handle_t *acquireFence = nullptr;
3773 if (request->input_buffer->acquire_fence != -1) {
3774 acquireFence = native_handle_create(1,0);
3775 acquireFence->data[0] = request->input_buffer->acquire_fence;
3776 handlesCreated->push_back(acquireFence);
3777 }
3778 captureRequest->inputBuffer.acquireFence = acquireFence;
3779 captureRequest->inputBuffer.releaseFence = nullptr;
3780
3781 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3782 request->input_buffer->buffer,
3783 request->input_buffer->acquire_fence);
3784 } else {
3785 captureRequest->inputBuffer.streamId = -1;
3786 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3787 }
3788
3789 captureRequest->outputBuffers.resize(request->num_output_buffers);
3790 for (size_t i = 0; i < request->num_output_buffers; i++) {
3791 const camera3_stream_buffer_t *src = request->output_buffers + i;
3792 StreamBuffer &dst = captureRequest->outputBuffers[i];
3793 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3794 buffer_handle_t buf = *(src->buffer);
3795 auto pair = getBufferId(buf, streamId);
3796 bool isNewBuffer = pair.first;
3797 dst.streamId = streamId;
3798 dst.bufferId = pair.second;
3799 dst.buffer = isNewBuffer ? buf : nullptr;
3800 dst.status = BufferStatus::OK;
3801 native_handle_t *acquireFence = nullptr;
3802 if (src->acquire_fence != -1) {
3803 acquireFence = native_handle_create(1,0);
3804 acquireFence->data[0] = src->acquire_fence;
3805 handlesCreated->push_back(acquireFence);
3806 }
3807 dst.acquireFence = acquireFence;
3808 dst.releaseFence = nullptr;
3809
3810 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3811 src->buffer, src->acquire_fence);
3812 }
3813 }
3814}
3815
3816status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3817 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3818 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3819 if (!valid()) return INVALID_OPERATION;
3820
Emilian Peevaebbe412018-01-15 13:53:24 +00003821 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3822 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3823 if (castResult_3_4.isOk()) {
3824 hidlSession_3_4 = castResult_3_4;
3825 }
3826
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003827 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003828 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003829 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003830 if (hidlSession_3_4 != nullptr) {
3831 captureRequests_3_4.resize(batchSize);
3832 } else {
3833 captureRequests.resize(batchSize);
3834 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003835 std::vector<native_handle_t*> handlesCreated;
3836
3837 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003838 if (hidlSession_3_4 != nullptr) {
3839 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
3840 /*out*/&handlesCreated);
3841 } else {
3842 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3843 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003844 }
3845
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003846 std::vector<device::V3_2::BufferCache> cachesToRemove;
3847 {
3848 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3849 for (auto& pair : mFreedBuffers) {
3850 // The stream might have been removed since onBufferFreed
3851 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3852 cachesToRemove.push_back({pair.first, pair.second});
3853 }
3854 }
3855 mFreedBuffers.clear();
3856 }
3857
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003858 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3859 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003860
3861 // Write metadata to FMQ.
3862 for (size_t i = 0; i < batchSize; i++) {
3863 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003864 device::V3_2::CaptureRequest* captureRequest;
3865 if (hidlSession_3_4 != nullptr) {
3866 captureRequest = &captureRequests_3_4[i].v3_2;
3867 } else {
3868 captureRequest = &captureRequests[i];
3869 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003870
3871 if (request->settings != nullptr) {
3872 size_t settingsSize = get_camera_metadata_size(request->settings);
3873 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3874 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3875 captureRequest->settings.resize(0);
3876 captureRequest->fmqSettingsSize = settingsSize;
3877 } else {
3878 if (mRequestMetadataQueue != nullptr) {
3879 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3880 }
3881 captureRequest->settings.setToExternal(
3882 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3883 get_camera_metadata_size(request->settings));
3884 captureRequest->fmqSettingsSize = 0u;
3885 }
3886 } else {
3887 // A null request settings maps to a size-0 CameraMetadata
3888 captureRequest->settings.resize(0);
3889 captureRequest->fmqSettingsSize = 0u;
3890 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003891
3892 if (hidlSession_3_4 != nullptr) {
3893 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3894 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003895 if (request->physcam_settings != nullptr) {
3896 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3897 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3898 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3899 settingsSize)) {
3900 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3901 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3902 settingsSize;
3903 } else {
3904 if (mRequestMetadataQueue != nullptr) {
3905 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3906 }
3907 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3908 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3909 request->physcam_settings[j])),
3910 get_camera_metadata_size(request->physcam_settings[j]));
3911 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003912 }
Emilian Peev00420d22018-02-05 21:33:13 +00003913 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003914 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003915 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003916 }
3917 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3918 request->physcam_id[j];
3919 }
3920 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003921 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003922
3923 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003924 auto resultCallback =
3925 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3926 status = s;
3927 *numRequestProcessed = n;
3928 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003929 if (hidlSession_3_4 != nullptr) {
3930 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003931 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003932 } else {
3933 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003934 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003935 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003936 if (!err.isOk()) {
3937 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3938 return DEAD_OBJECT;
3939 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003940 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3941 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3942 __FUNCTION__, *numRequestProcessed, batchSize);
3943 status = common::V1_0::Status::INTERNAL_ERROR;
3944 }
3945
3946 for (auto& handle : handlesCreated) {
3947 native_handle_delete(handle);
3948 }
3949 return CameraProviderManager::mapToStatusT(status);
3950}
3951
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003952status_t Camera3Device::HalInterface::processCaptureRequest(
3953 camera3_capture_request_t *request) {
3954 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003955 if (!valid()) return INVALID_OPERATION;
3956 status_t res = OK;
3957
Emilian Peev31abd0a2017-05-11 18:37:46 +01003958 uint32_t numRequestProcessed = 0;
3959 std::vector<camera3_capture_request_t*> requests(1);
3960 requests[0] = request;
3961 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3962
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003963 return res;
3964}
3965
3966status_t Camera3Device::HalInterface::flush() {
3967 ATRACE_NAME("CameraHal::flush");
3968 if (!valid()) return INVALID_OPERATION;
3969 status_t res = OK;
3970
Emilian Peev31abd0a2017-05-11 18:37:46 +01003971 auto err = mHidlSession->flush();
3972 if (!err.isOk()) {
3973 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3974 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003975 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003976 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003977 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003978
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003979 return res;
3980}
3981
Emilian Peev31abd0a2017-05-11 18:37:46 +01003982status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003983 ATRACE_NAME("CameraHal::dump");
3984 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003985
Emilian Peev31abd0a2017-05-11 18:37:46 +01003986 // Handled by CameraProviderManager::dump
3987
3988 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003989}
3990
3991status_t Camera3Device::HalInterface::close() {
3992 ATRACE_NAME("CameraHal::close()");
3993 if (!valid()) return INVALID_OPERATION;
3994 status_t res = OK;
3995
Emilian Peev31abd0a2017-05-11 18:37:46 +01003996 auto err = mHidlSession->close();
3997 // Interface will be dead shortly anyway, so don't log errors
3998 if (!err.isOk()) {
3999 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004000 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004001
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004002 return res;
4003}
4004
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004005void Camera3Device::HalInterface::getInflightBufferKeys(
4006 std::vector<std::pair<int32_t, int32_t>>* out) {
4007 std::lock_guard<std::mutex> lock(mInflightLock);
4008 out->clear();
4009 out->reserve(mInflightBufferMap.size());
4010 for (auto& pair : mInflightBufferMap) {
4011 uint64_t key = pair.first;
4012 int32_t streamId = key & 0xFFFFFFFF;
4013 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4014 out->push_back(std::make_pair(frameNumber, streamId));
4015 }
4016 return;
4017}
4018
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004019status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004020 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004021 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004022 auto pair = std::make_pair(buffer, acquireFence);
4023 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004024 return OK;
4025}
4026
4027status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004028 int32_t frameNumber, int32_t streamId,
4029 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004030 std::lock_guard<std::mutex> lock(mInflightLock);
4031
4032 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4033 auto it = mInflightBufferMap.find(key);
4034 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004035 auto pair = it->second;
4036 *buffer = pair.first;
4037 int acquireFence = pair.second;
4038 if (acquireFence > 0) {
4039 ::close(acquireFence);
4040 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004041 mInflightBufferMap.erase(it);
4042 return OK;
4043}
4044
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004045std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4046 const buffer_handle_t& buf, int streamId) {
4047 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4048
4049 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4050 auto it = bIdMap.find(buf);
4051 if (it == bIdMap.end()) {
4052 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004053 ALOGV("stream %d now have %zu buffer caches, buf %p",
4054 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004055 return std::make_pair(true, mNextBufferId - 1);
4056 } else {
4057 return std::make_pair(false, it->second);
4058 }
4059}
4060
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004061void Camera3Device::HalInterface::onBufferFreed(
4062 int streamId, const native_handle_t* handle) {
4063 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4064 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4065 auto mapIt = mBufferIdMaps.find(streamId);
4066 if (mapIt == mBufferIdMaps.end()) {
4067 // streamId might be from a deleted stream here
4068 ALOGI("%s: stream %d has been removed",
4069 __FUNCTION__, streamId);
4070 return;
4071 }
4072 BufferIdMap& bIdMap = mapIt->second;
4073 auto it = bIdMap.find(handle);
4074 if (it == bIdMap.end()) {
4075 ALOGW("%s: cannot find buffer %p in stream %d",
4076 __FUNCTION__, handle, streamId);
4077 return;
4078 } else {
4079 bufferId = it->second;
4080 bIdMap.erase(it);
4081 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4082 __FUNCTION__, streamId, bIdMap.size(), handle);
4083 }
4084 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4085}
4086
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004087/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004088 * RequestThread inner class methods
4089 */
4090
4091Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004092 sp<StatusTracker> statusTracker,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004093 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004094 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004095 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004096 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004097 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004098 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004099 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004100 mReconfigured(false),
4101 mDoPause(false),
4102 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004103 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004104 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004105 mCurrentAfTriggerId(0),
4106 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004107 mRepeatingLastFrameNumber(
4108 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004109 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004110 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004111 mRequestLatency(kRequestLatencyBinSize),
4112 mSessionParamKeys(sessionParamKeys),
4113 mLatestSessionParams(sessionParamKeys.size()) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004114 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004115}
4116
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004117Camera3Device::RequestThread::~RequestThread() {}
4118
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004119void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004120 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004121 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004122 Mutex::Autolock l(mRequestLock);
4123 mListener = listener;
4124}
4125
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004126void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4127 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004128 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004129 Mutex::Autolock l(mRequestLock);
4130 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004131 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004132 // Prepare video stream for high speed recording.
4133 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004134 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004135}
4136
Jianing Wei90e59c92014-03-12 18:29:36 -07004137status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004138 List<sp<CaptureRequest> > &requests,
4139 /*out*/
4140 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004141 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004142 Mutex::Autolock l(mRequestLock);
4143 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4144 ++it) {
4145 mRequestQueue.push_back(*it);
4146 }
4147
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004148 if (lastFrameNumber != NULL) {
4149 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4150 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4151 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4152 *lastFrameNumber);
4153 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004154
Jianing Wei90e59c92014-03-12 18:29:36 -07004155 unpauseForNewRequests();
4156
4157 return OK;
4158}
4159
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004160
4161status_t Camera3Device::RequestThread::queueTrigger(
4162 RequestTrigger trigger[],
4163 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004164 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004165 Mutex::Autolock l(mTriggerMutex);
4166 status_t ret;
4167
4168 for (size_t i = 0; i < count; ++i) {
4169 ret = queueTriggerLocked(trigger[i]);
4170
4171 if (ret != OK) {
4172 return ret;
4173 }
4174 }
4175
4176 return OK;
4177}
4178
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004179const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4180 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004181 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004182 if (d != nullptr) return d->mId;
4183 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004184}
4185
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004186status_t Camera3Device::RequestThread::queueTriggerLocked(
4187 RequestTrigger trigger) {
4188
4189 uint32_t tag = trigger.metadataTag;
4190 ssize_t index = mTriggerMap.indexOfKey(tag);
4191
4192 switch (trigger.getTagType()) {
4193 case TYPE_BYTE:
4194 // fall-through
4195 case TYPE_INT32:
4196 break;
4197 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004198 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4199 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004200 return INVALID_OPERATION;
4201 }
4202
4203 /**
4204 * Collect only the latest trigger, since we only have 1 field
4205 * in the request settings per trigger tag, and can't send more than 1
4206 * trigger per request.
4207 */
4208 if (index != NAME_NOT_FOUND) {
4209 mTriggerMap.editValueAt(index) = trigger;
4210 } else {
4211 mTriggerMap.add(tag, trigger);
4212 }
4213
4214 return OK;
4215}
4216
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004217status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004218 const RequestList &requests,
4219 /*out*/
4220 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004221 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004222 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004223 if (lastFrameNumber != NULL) {
4224 *lastFrameNumber = mRepeatingLastFrameNumber;
4225 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004226 mRepeatingRequests.clear();
4227 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4228 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004229
4230 unpauseForNewRequests();
4231
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004232 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004233 return OK;
4234}
4235
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004236bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004237 if (mRepeatingRequests.empty()) {
4238 return false;
4239 }
4240 int32_t requestId = requestIn->mResultExtras.requestId;
4241 const RequestList &repeatRequests = mRepeatingRequests;
4242 // All repeating requests are guaranteed to have same id so only check first quest
4243 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4244 return (firstRequest->mResultExtras.requestId == requestId);
4245}
4246
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004247status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004248 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004249 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004250 return clearRepeatingRequestsLocked(lastFrameNumber);
4251
4252}
4253
4254status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004255 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004256 if (lastFrameNumber != NULL) {
4257 *lastFrameNumber = mRepeatingLastFrameNumber;
4258 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004259 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004260 return OK;
4261}
4262
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004263status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004264 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004265 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004266 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004267 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004268
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004269 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004270
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004271 // Send errors for all requests pending in the request queue, including
4272 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004273 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004274 if (listener != NULL) {
4275 for (RequestList::iterator it = mRequestQueue.begin();
4276 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004277 // Abort the input buffers for reprocess requests.
4278 if ((*it)->mInputStream != NULL) {
4279 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004280 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4281 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004282 if (res != OK) {
4283 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4284 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4285 } else {
4286 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4287 if (res != OK) {
4288 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4289 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4290 }
4291 }
4292 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004293 // Set the frame number this request would have had, if it
4294 // had been submitted; this frame number will not be reused.
4295 // The requestId and burstId fields were set when the request was
4296 // submitted originally (in convertMetadataListToRequestListLocked)
4297 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004298 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004299 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004300 }
4301 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004302 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004303
4304 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004305 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004306 if (lastFrameNumber != NULL) {
4307 *lastFrameNumber = mRepeatingLastFrameNumber;
4308 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004309 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004310 return OK;
4311}
4312
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004313status_t Camera3Device::RequestThread::flush() {
4314 ATRACE_CALL();
4315 Mutex::Autolock l(mFlushLock);
4316
Emilian Peev08dd2452017-04-06 16:55:14 +01004317 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004318}
4319
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004320void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004321 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004322 Mutex::Autolock l(mPauseLock);
4323 mDoPause = paused;
4324 mDoPauseSignal.signal();
4325}
4326
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004327status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4328 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004329 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004330 Mutex::Autolock l(mLatestRequestMutex);
4331 status_t res;
4332 while (mLatestRequestId != requestId) {
4333 nsecs_t startTime = systemTime();
4334
4335 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4336 if (res != OK) return res;
4337
4338 timeout -= (systemTime() - startTime);
4339 }
4340
4341 return OK;
4342}
4343
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004344void Camera3Device::RequestThread::requestExit() {
4345 // Call parent to set up shutdown
4346 Thread::requestExit();
4347 // The exit from any possible waits
4348 mDoPauseSignal.signal();
4349 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004350
4351 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4352 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004353}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004354
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004355void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004356 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004357 bool surfaceAbandoned = false;
4358 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004359 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004360 {
4361 Mutex::Autolock l(mRequestLock);
4362 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4363 // repeating requests.
4364 for (const auto& request : mRepeatingRequests) {
4365 for (const auto& s : request->mOutputStreams) {
4366 if (s->isAbandoned()) {
4367 surfaceAbandoned = true;
4368 clearRepeatingRequestsLocked(&lastFrameNumber);
4369 break;
4370 }
4371 }
4372 if (surfaceAbandoned) {
4373 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004374 }
4375 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004376 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004377 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004378
4379 if (listener != NULL && surfaceAbandoned) {
4380 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004381 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004382}
4383
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004384bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004385 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004386 status_t res;
4387 size_t batchSize = mNextRequests.size();
4388 std::vector<camera3_capture_request_t*> requests(batchSize);
4389 uint32_t numRequestProcessed = 0;
4390 for (size_t i = 0; i < batchSize; i++) {
4391 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004392 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004393 }
4394
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004395 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4396
4397 bool triggerRemoveFailed = false;
4398 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4399 for (size_t i = 0; i < numRequestProcessed; i++) {
4400 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4401 nextRequest.submitted = true;
4402
4403
4404 // Update the latest request sent to HAL
4405 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4406 Mutex::Autolock al(mLatestRequestMutex);
4407
4408 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4409 mLatestRequest.acquire(cloned);
4410
4411 sp<Camera3Device> parent = mParent.promote();
4412 if (parent != NULL) {
4413 parent->monitorMetadata(TagMonitor::REQUEST,
4414 nextRequest.halRequest.frame_number,
4415 0, mLatestRequest);
4416 }
4417 }
4418
4419 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004420 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4421 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004422 }
4423
Emilian Peevaebbe412018-01-15 13:53:24 +00004424 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4425
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004426 if (!triggerRemoveFailed) {
4427 // Remove any previously queued triggers (after unlock)
4428 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4429 if (removeTriggerRes != OK) {
4430 triggerRemoveFailed = true;
4431 triggerFailedRequest = nextRequest;
4432 }
4433 }
4434 }
4435
4436 if (triggerRemoveFailed) {
4437 SET_ERR("RequestThread: Unable to remove triggers "
4438 "(capture request %d, HAL device: %s (%d)",
4439 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4440 cleanUpFailedRequests(/*sendRequestError*/ false);
4441 return false;
4442 }
4443
4444 if (res != OK) {
4445 // Should only get a failure here for malformed requests or device-level
4446 // errors, so consider all errors fatal. Bad metadata failures should
4447 // come through notify.
4448 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4449 mNextRequests[numRequestProcessed].halRequest.frame_number,
4450 strerror(-res), res);
4451 cleanUpFailedRequests(/*sendRequestError*/ false);
4452 return false;
4453 }
4454 return true;
4455}
4456
4457bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4458 status_t res;
4459
4460 for (auto& nextRequest : mNextRequests) {
4461 // Submit request and block until ready for next one
4462 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4463 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4464
4465 if (res != OK) {
4466 // Should only get a failure here for malformed requests or device-level
4467 // errors, so consider all errors fatal. Bad metadata failures should
4468 // come through notify.
4469 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4470 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4471 res);
4472 cleanUpFailedRequests(/*sendRequestError*/ false);
4473 return false;
4474 }
4475
4476 // Mark that the request has be submitted successfully.
4477 nextRequest.submitted = true;
4478
4479 // Update the latest request sent to HAL
4480 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4481 Mutex::Autolock al(mLatestRequestMutex);
4482
4483 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4484 mLatestRequest.acquire(cloned);
4485
4486 sp<Camera3Device> parent = mParent.promote();
4487 if (parent != NULL) {
4488 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4489 0, mLatestRequest);
4490 }
4491 }
4492
4493 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004494 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4495 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004496 }
4497
Emilian Peevaebbe412018-01-15 13:53:24 +00004498 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4499
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004500 // Remove any previously queued triggers (after unlock)
4501 res = removeTriggers(mPrevRequest);
4502 if (res != OK) {
4503 SET_ERR("RequestThread: Unable to remove triggers "
4504 "(capture request %d, HAL device: %s (%d)",
4505 nextRequest.halRequest.frame_number, strerror(-res), res);
4506 cleanUpFailedRequests(/*sendRequestError*/ false);
4507 return false;
4508 }
4509 }
4510 return true;
4511}
4512
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004513nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4514 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4515 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4516 find_camera_metadata_ro_entry(request,
4517 ANDROID_CONTROL_AE_MODE,
4518 &e);
4519 if (e.count == 0) return maxExpectedDuration;
4520
4521 switch (e.data.u8[0]) {
4522 case ANDROID_CONTROL_AE_MODE_OFF:
4523 find_camera_metadata_ro_entry(request,
4524 ANDROID_SENSOR_EXPOSURE_TIME,
4525 &e);
4526 if (e.count > 0) {
4527 maxExpectedDuration = e.data.i64[0];
4528 }
4529 find_camera_metadata_ro_entry(request,
4530 ANDROID_SENSOR_FRAME_DURATION,
4531 &e);
4532 if (e.count > 0) {
4533 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4534 }
4535 break;
4536 default:
4537 find_camera_metadata_ro_entry(request,
4538 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4539 &e);
4540 if (e.count > 1) {
4541 maxExpectedDuration = 1e9 / e.data.u8[0];
4542 }
4543 break;
4544 }
4545
4546 return maxExpectedDuration;
4547}
4548
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004549bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4550 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4551 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4552 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4553 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4554 return true;
4555 }
4556
4557 return false;
4558}
4559
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004560bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4561 ATRACE_CALL();
4562 bool updatesDetected = false;
4563
4564 for (auto tag : mSessionParamKeys) {
4565 camera_metadata_ro_entry entry = settings.find(tag);
4566 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4567
4568 if (entry.count > 0) {
4569 bool isDifferent = false;
4570 if (lastEntry.count > 0) {
4571 // Have a last value, compare to see if changed
4572 if (lastEntry.type == entry.type &&
4573 lastEntry.count == entry.count) {
4574 // Same type and count, compare values
4575 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4576 size_t entryBytes = bytesPerValue * lastEntry.count;
4577 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4578 if (cmp != 0) {
4579 isDifferent = true;
4580 }
4581 } else {
4582 // Count or type has changed
4583 isDifferent = true;
4584 }
4585 } else {
4586 // No last entry, so always consider to be different
4587 isDifferent = true;
4588 }
4589
4590 if (isDifferent) {
4591 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004592 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4593 updatesDetected = true;
4594 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004595 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004596 }
4597 } else if (lastEntry.count > 0) {
4598 // Value has been removed
4599 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4600 mLatestSessionParams.erase(tag);
4601 updatesDetected = true;
4602 }
4603 }
4604
4605 return updatesDetected;
4606}
4607
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004608bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004609 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004610 status_t res;
4611
4612 // Handle paused state.
4613 if (waitIfPaused()) {
4614 return true;
4615 }
4616
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004617 // Wait for the next batch of requests.
4618 waitForNextRequestBatch();
4619 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004620 return true;
4621 }
4622
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004623 // Get the latest request ID, if any
4624 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004625 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004626 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004627 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004628 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004629 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004630 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4631 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004632 }
4633
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004634 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4635 // or a single request from streaming or burst. In either case the first element
4636 // should contain the latest camera settings that we need to check for any session
4637 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004638 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004639 res = OK;
4640
4641 //Input stream buffers are already acquired at this point so an input stream
4642 //will not be able to move to idle state unless we force it.
4643 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4644 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4645 if (res != OK) {
4646 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4647 cleanUpFailedRequests(/*sendRequestError*/ false);
4648 return false;
4649 }
4650 }
4651
4652 if (res == OK) {
4653 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4654 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004655 sp<Camera3Device> parent = mParent.promote();
4656 if (parent != nullptr) {
4657 parent->pauseStateNotify(true);
4658 }
4659
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004660 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4661
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004662 if (parent != nullptr) {
4663 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4664 }
4665
4666 statusTracker->markComponentActive(mStatusId);
4667 setPaused(false);
4668 }
4669
4670 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4671 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4672 if (res != OK) {
4673 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4674 cleanUpFailedRequests(/*sendRequestError*/ false);
4675 return false;
4676 }
4677 }
4678 }
4679 }
4680
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004681 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004682 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004683 if (res == TIMED_OUT) {
4684 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004685 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004686 // Check if any stream is abandoned.
4687 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004688 return true;
4689 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004690 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004691 return false;
4692 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004693
Zhijun Hecc27e112013-10-03 16:12:43 -07004694 // Inform waitUntilRequestProcessed thread of a new request ID
4695 {
4696 Mutex::Autolock al(mLatestRequestMutex);
4697
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004698 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004699 mLatestRequestSignal.signal();
4700 }
4701
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004702 // Submit a batch of requests to HAL.
4703 // Use flush lock only when submitting multilple requests in a batch.
4704 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4705 // which may take a long time to finish so synchronizing flush() and
4706 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4707 // For now, only synchronize for high speed recording and we should figure something out for
4708 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004709 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004710
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004711 if (useFlushLock) {
4712 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004713 }
4714
Zhijun Hef0645c12016-08-02 00:58:11 -07004715 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004716 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004717
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004718 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004719 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004720 if (mInterface->supportBatchRequest()) {
4721 submitRequestSuccess = sendRequestsBatch();
4722 } else {
4723 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004724 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004725 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4726 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004727
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004728 if (useFlushLock) {
4729 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004730 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004731
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004732 // Unset as current request
4733 {
4734 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004735 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004736 }
4737
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004738 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004739}
4740
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004741status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004742 ATRACE_CALL();
4743
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004744 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004745 for (size_t i = 0; i < mNextRequests.size(); i++) {
4746 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004747 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4748 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4749 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4750
4751 // Prepare a request to HAL
4752 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4753
4754 // Insert any queued triggers (before metadata is locked)
4755 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004756 if (res < 0) {
4757 SET_ERR("RequestThread: Unable to insert triggers "
4758 "(capture request %d, HAL device: %s (%d)",
4759 halRequest->frame_number, strerror(-res), res);
4760 return INVALID_OPERATION;
4761 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004762
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004763 int triggerCount = res;
4764 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4765 mPrevTriggers = triggerCount;
4766
4767 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004768 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
4769 // Request settings are all the same within one batch, so only treat the first
4770 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004771 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004772 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004773 /**
4774 * HAL workaround:
4775 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4776 */
4777 res = addDummyTriggerIds(captureRequest);
4778 if (res != OK) {
4779 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4780 "(capture request %d, HAL device: %s (%d)",
4781 halRequest->frame_number, strerror(-res), res);
4782 return INVALID_OPERATION;
4783 }
4784
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004785 {
4786 // Correct metadata regions for distortion correction if enabled
4787 sp<Camera3Device> parent = mParent.promote();
4788 if (parent != nullptr) {
4789 res = parent->mDistortionMapper.correctCaptureRequest(
4790 &(captureRequest->mSettingsList.begin()->metadata));
4791 if (res != OK) {
4792 SET_ERR("RequestThread: Unable to correct capture requests "
4793 "for lens distortion for request %d: %s (%d)",
4794 halRequest->frame_number, strerror(-res), res);
4795 return INVALID_OPERATION;
4796 }
4797 }
4798 }
4799
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004800 /**
4801 * The request should be presorted so accesses in HAL
4802 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4803 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004804 captureRequest->mSettingsList.begin()->metadata.sort();
4805 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004806 mPrevRequest = captureRequest;
4807 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4808
4809 IF_ALOGV() {
4810 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4811 find_camera_metadata_ro_entry(
4812 halRequest->settings,
4813 ANDROID_CONTROL_AF_TRIGGER,
4814 &e
4815 );
4816 if (e.count > 0) {
4817 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4818 __FUNCTION__,
4819 halRequest->frame_number,
4820 e.data.u8[0]);
4821 }
4822 }
4823 } else {
4824 // leave request.settings NULL to indicate 'reuse latest given'
4825 ALOGVV("%s: Request settings are REUSED",
4826 __FUNCTION__);
4827 }
4828
Emilian Peevaebbe412018-01-15 13:53:24 +00004829 if (captureRequest->mSettingsList.size() > 1) {
4830 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4831 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004832 if (newRequest) {
4833 halRequest->physcam_settings =
4834 new const camera_metadata* [halRequest->num_physcam_settings];
4835 } else {
4836 halRequest->physcam_settings = nullptr;
4837 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004838 auto it = ++captureRequest->mSettingsList.begin();
4839 size_t i = 0;
4840 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4841 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004842 if (newRequest) {
4843 it->metadata.sort();
4844 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4845 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004846 }
4847 }
4848
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004849 uint32_t totalNumBuffers = 0;
4850
4851 // Fill in buffers
4852 if (captureRequest->mInputStream != NULL) {
4853 halRequest->input_buffer = &captureRequest->mInputBuffer;
4854 totalNumBuffers += 1;
4855 } else {
4856 halRequest->input_buffer = NULL;
4857 }
4858
4859 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4860 captureRequest->mOutputStreams.size());
4861 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004862 std::set<String8> requestedPhysicalCameras;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004863 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4864 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004865
4866 // Prepare video buffers for high speed recording on the first video request.
4867 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4868 // Only try to prepare video stream on the first video request.
4869 mPrepareVideoStream = false;
4870
4871 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4872 while (res == NOT_ENOUGH_DATA) {
4873 res = outputStream->prepareNextBuffer();
4874 }
4875 if (res != OK) {
4876 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4877 __FUNCTION__, strerror(-res), res);
4878 outputStream->cancelPrepare();
4879 }
4880 }
4881
Shuzhen Wang4a472662017-02-26 23:29:04 -08004882 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4883 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004884 if (res != OK) {
4885 // Can't get output buffer from gralloc queue - this could be due to
4886 // abandoned queue or other consumer misbehavior, so not a fatal
4887 // error
4888 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4889 " %s (%d)", strerror(-res), res);
4890
4891 return TIMED_OUT;
4892 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004893
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004894 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4895
4896 if (!physicalCameraId.isEmpty()) {
4897 // Physical stream isn't supported for input request.
4898 if (halRequest->input_buffer) {
4899 CLOGE("Physical stream is not supported for input request");
4900 return INVALID_OPERATION;
4901 }
4902 requestedPhysicalCameras.insert(physicalCameraId);
4903 }
4904 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004905 }
4906 totalNumBuffers += halRequest->num_output_buffers;
4907
4908 // Log request in the in-flight queue
4909 sp<Camera3Device> parent = mParent.promote();
4910 if (parent == NULL) {
4911 // Should not happen, and nowhere to send errors to, so just log it
4912 CLOGE("RequestThread: Parent is gone");
4913 return INVALID_OPERATION;
4914 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004915
4916 // If this request list is for constrained high speed recording (not
4917 // preview), and the current request is not the last one in the batch,
4918 // do not send callback to the app.
4919 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004920 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004921 hasCallback = false;
4922 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004923 res = parent->registerInFlight(halRequest->frame_number,
4924 totalNumBuffers, captureRequest->mResultExtras,
4925 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004926 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004927 calculateMaxExpectedDuration(halRequest->settings),
4928 requestedPhysicalCameras);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004929 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4930 ", burstId = %" PRId32 ".",
4931 __FUNCTION__,
4932 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4933 captureRequest->mResultExtras.burstId);
4934 if (res != OK) {
4935 SET_ERR("RequestThread: Unable to register new in-flight request:"
4936 " %s (%d)", strerror(-res), res);
4937 return INVALID_OPERATION;
4938 }
4939 }
4940
4941 return OK;
4942}
4943
Igor Murashkin1e479c02013-09-06 16:55:14 -07004944CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004945 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004946 Mutex::Autolock al(mLatestRequestMutex);
4947
4948 ALOGV("RequestThread::%s", __FUNCTION__);
4949
4950 return mLatestRequest;
4951}
4952
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004953bool Camera3Device::RequestThread::isStreamPending(
4954 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004955 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004956 Mutex::Autolock l(mRequestLock);
4957
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004958 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004959 if (!nextRequest.submitted) {
4960 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4961 if (stream == s) return true;
4962 }
4963 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004964 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004965 }
4966
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004967 for (const auto& request : mRequestQueue) {
4968 for (const auto& s : request->mOutputStreams) {
4969 if (stream == s) return true;
4970 }
4971 if (stream == request->mInputStream) return true;
4972 }
4973
4974 for (const auto& request : mRepeatingRequests) {
4975 for (const auto& s : request->mOutputStreams) {
4976 if (stream == s) return true;
4977 }
4978 if (stream == request->mInputStream) return true;
4979 }
4980
4981 return false;
4982}
Jianing Weicb0652e2014-03-12 18:29:36 -07004983
Emilian Peev40ead602017-09-26 15:46:36 +01004984bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
4985 ATRACE_CALL();
4986 Mutex::Autolock l(mRequestLock);
4987
4988 for (const auto& nextRequest : mNextRequests) {
4989 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
4990 if (s.first == streamId) {
4991 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
4992 if (it != s.second.end()) {
4993 return true;
4994 }
4995 }
4996 }
4997 }
4998
4999 for (const auto& request : mRequestQueue) {
5000 for (const auto& s : request->mOutputSurfaces) {
5001 if (s.first == streamId) {
5002 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5003 if (it != s.second.end()) {
5004 return true;
5005 }
5006 }
5007 }
5008 }
5009
5010 for (const auto& request : mRepeatingRequests) {
5011 for (const auto& s : request->mOutputSurfaces) {
5012 if (s.first == streamId) {
5013 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5014 if (it != s.second.end()) {
5015 return true;
5016 }
5017 }
5018 }
5019 }
5020
5021 return false;
5022}
5023
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005024nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005025 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005026 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005027 return mExpectedInflightDuration > kMinInflightDuration ?
5028 mExpectedInflightDuration : kMinInflightDuration;
5029}
5030
Emilian Peevaebbe412018-01-15 13:53:24 +00005031void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5032 camera3_capture_request_t *halRequest) {
5033 if ((request == nullptr) || (halRequest == nullptr)) {
5034 ALOGE("%s: Invalid request!", __FUNCTION__);
5035 return;
5036 }
5037
5038 if (halRequest->num_physcam_settings > 0) {
5039 if (halRequest->physcam_id != nullptr) {
5040 delete [] halRequest->physcam_id;
5041 halRequest->physcam_id = nullptr;
5042 }
5043 if (halRequest->physcam_settings != nullptr) {
5044 auto it = ++(request->mSettingsList.begin());
5045 size_t i = 0;
5046 for (; it != request->mSettingsList.end(); it++, i++) {
5047 it->metadata.unlock(halRequest->physcam_settings[i]);
5048 }
5049 delete [] halRequest->physcam_settings;
5050 halRequest->physcam_settings = nullptr;
5051 }
5052 }
5053}
5054
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005055void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5056 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005057 return;
5058 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005059
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005060 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005061 // Skip the ones that have been submitted successfully.
5062 if (nextRequest.submitted) {
5063 continue;
5064 }
5065
5066 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5067 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5068 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5069
5070 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005071 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005072 }
5073
Emilian Peevaebbe412018-01-15 13:53:24 +00005074 cleanupPhysicalSettings(captureRequest, halRequest);
5075
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005076 if (captureRequest->mInputStream != NULL) {
5077 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5078 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5079 }
5080
5081 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005082 //Buffers that failed processing could still have
5083 //valid acquire fence.
5084 int acquireFence = (*outputBuffers)[i].acquire_fence;
5085 if (0 <= acquireFence) {
5086 close(acquireFence);
5087 outputBuffers->editItemAt(i).acquire_fence = -1;
5088 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005089 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5090 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5091 }
5092
5093 if (sendRequestError) {
5094 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005095 sp<NotificationListener> listener = mListener.promote();
5096 if (listener != NULL) {
5097 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005098 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005099 captureRequest->mResultExtras);
5100 }
5101 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005102
5103 // Remove yet-to-be submitted inflight request from inflightMap
5104 {
5105 sp<Camera3Device> parent = mParent.promote();
5106 if (parent != NULL) {
5107 Mutex::Autolock l(parent->mInFlightLock);
5108 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5109 if (idx >= 0) {
5110 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5111 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5112 parent->removeInFlightMapEntryLocked(idx);
5113 }
5114 }
5115 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005116 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005117
5118 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005119 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005120}
5121
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005122void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005123 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005124 // Optimized a bit for the simple steady-state case (single repeating
5125 // request), to avoid putting that request in the queue temporarily.
5126 Mutex::Autolock l(mRequestLock);
5127
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005128 assert(mNextRequests.empty());
5129
5130 NextRequest nextRequest;
5131 nextRequest.captureRequest = waitForNextRequestLocked();
5132 if (nextRequest.captureRequest == nullptr) {
5133 return;
5134 }
5135
5136 nextRequest.halRequest = camera3_capture_request_t();
5137 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005138 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005139
5140 // Wait for additional requests
5141 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5142
5143 for (size_t i = 1; i < batchSize; i++) {
5144 NextRequest additionalRequest;
5145 additionalRequest.captureRequest = waitForNextRequestLocked();
5146 if (additionalRequest.captureRequest == nullptr) {
5147 break;
5148 }
5149
5150 additionalRequest.halRequest = camera3_capture_request_t();
5151 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005152 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005153 }
5154
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005155 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005156 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005157 mNextRequests.size(), batchSize);
5158 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005159 }
5160
5161 return;
5162}
5163
5164sp<Camera3Device::CaptureRequest>
5165 Camera3Device::RequestThread::waitForNextRequestLocked() {
5166 status_t res;
5167 sp<CaptureRequest> nextRequest;
5168
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005169 while (mRequestQueue.empty()) {
5170 if (!mRepeatingRequests.empty()) {
5171 // Always atomically enqueue all requests in a repeating request
5172 // list. Guarantees a complete in-sequence set of captures to
5173 // application.
5174 const RequestList &requests = mRepeatingRequests;
5175 RequestList::const_iterator firstRequest =
5176 requests.begin();
5177 nextRequest = *firstRequest;
5178 mRequestQueue.insert(mRequestQueue.end(),
5179 ++firstRequest,
5180 requests.end());
5181 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005182
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005183 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005184
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005185 break;
5186 }
5187
5188 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5189
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005190 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5191 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005192 Mutex::Autolock pl(mPauseLock);
5193 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005194 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005195 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005196 // Let the tracker know
5197 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5198 if (statusTracker != 0) {
5199 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5200 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005201 }
5202 // Stop waiting for now and let thread management happen
5203 return NULL;
5204 }
5205 }
5206
5207 if (nextRequest == NULL) {
5208 // Don't have a repeating request already in hand, so queue
5209 // must have an entry now.
5210 RequestList::iterator firstRequest =
5211 mRequestQueue.begin();
5212 nextRequest = *firstRequest;
5213 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005214 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5215 sp<NotificationListener> listener = mListener.promote();
5216 if (listener != NULL) {
5217 listener->notifyRequestQueueEmpty();
5218 }
5219 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005220 }
5221
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005222 // In case we've been unpaused by setPaused clearing mDoPause, need to
5223 // update internal pause state (capture/setRepeatingRequest unpause
5224 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005225 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005226 if (mPaused) {
5227 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5228 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5229 if (statusTracker != 0) {
5230 statusTracker->markComponentActive(mStatusId);
5231 }
5232 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005233 mPaused = false;
5234
5235 // Check if we've reconfigured since last time, and reset the preview
5236 // request if so. Can't use 'NULL request == repeat' across configure calls.
5237 if (mReconfigured) {
5238 mPrevRequest.clear();
5239 mReconfigured = false;
5240 }
5241
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005242 if (nextRequest != NULL) {
5243 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005244 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5245 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005246
5247 // Since RequestThread::clear() removes buffers from the input stream,
5248 // get the right buffer here before unlocking mRequestLock
5249 if (nextRequest->mInputStream != NULL) {
5250 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5251 if (res != OK) {
5252 // Can't get input buffer from gralloc queue - this could be due to
5253 // disconnected queue or other producer misbehavior, so not a fatal
5254 // error
5255 ALOGE("%s: Can't get input buffer, skipping request:"
5256 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005257
5258 sp<NotificationListener> listener = mListener.promote();
5259 if (listener != NULL) {
5260 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005261 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005262 nextRequest->mResultExtras);
5263 }
5264 return NULL;
5265 }
5266 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005267 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005268
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005269 return nextRequest;
5270}
5271
5272bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005273 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005274 status_t res;
5275 Mutex::Autolock l(mPauseLock);
5276 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005277 if (mPaused == false) {
5278 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005279 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5280 // Let the tracker know
5281 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5282 if (statusTracker != 0) {
5283 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5284 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005285 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005286
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005287 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005288 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005289 return true;
5290 }
5291 }
5292 // We don't set mPaused to false here, because waitForNextRequest needs
5293 // to further manage the paused state in case of starvation.
5294 return false;
5295}
5296
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005297void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005298 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005299 // With work to do, mark thread as unpaused.
5300 // If paused by request (setPaused), don't resume, to avoid
5301 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005302 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005303 Mutex::Autolock p(mPauseLock);
5304 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005305 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5306 if (mPaused) {
5307 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5308 if (statusTracker != 0) {
5309 statusTracker->markComponentActive(mStatusId);
5310 }
5311 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005312 mPaused = false;
5313 }
5314}
5315
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005316void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5317 sp<Camera3Device> parent = mParent.promote();
5318 if (parent != NULL) {
5319 va_list args;
5320 va_start(args, fmt);
5321
5322 parent->setErrorStateV(fmt, args);
5323
5324 va_end(args);
5325 }
5326}
5327
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005328status_t Camera3Device::RequestThread::insertTriggers(
5329 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005330 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005331 Mutex::Autolock al(mTriggerMutex);
5332
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005333 sp<Camera3Device> parent = mParent.promote();
5334 if (parent == NULL) {
5335 CLOGE("RequestThread: Parent is gone");
5336 return DEAD_OBJECT;
5337 }
5338
Emilian Peevaebbe412018-01-15 13:53:24 +00005339 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005340 size_t count = mTriggerMap.size();
5341
5342 for (size_t i = 0; i < count; ++i) {
5343 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005344 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005345
5346 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5347 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5348 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005349 if (isAeTrigger) {
5350 request->mResultExtras.precaptureTriggerId = triggerId;
5351 mCurrentPreCaptureTriggerId = triggerId;
5352 } else {
5353 request->mResultExtras.afTriggerId = triggerId;
5354 mCurrentAfTriggerId = triggerId;
5355 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005356 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005357 }
5358
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005359 camera_metadata_entry entry = metadata.find(tag);
5360
5361 if (entry.count > 0) {
5362 /**
5363 * Already has an entry for this trigger in the request.
5364 * Rewrite it with our requested trigger value.
5365 */
5366 RequestTrigger oldTrigger = trigger;
5367
5368 oldTrigger.entryValue = entry.data.u8[0];
5369
5370 mTriggerReplacedMap.add(tag, oldTrigger);
5371 } else {
5372 /**
5373 * More typical, no trigger entry, so we just add it
5374 */
5375 mTriggerRemovedMap.add(tag, trigger);
5376 }
5377
5378 status_t res;
5379
5380 switch (trigger.getTagType()) {
5381 case TYPE_BYTE: {
5382 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5383 res = metadata.update(tag,
5384 &entryValue,
5385 /*count*/1);
5386 break;
5387 }
5388 case TYPE_INT32:
5389 res = metadata.update(tag,
5390 &trigger.entryValue,
5391 /*count*/1);
5392 break;
5393 default:
5394 ALOGE("%s: Type not supported: 0x%x",
5395 __FUNCTION__,
5396 trigger.getTagType());
5397 return INVALID_OPERATION;
5398 }
5399
5400 if (res != OK) {
5401 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5402 ", value %d", __FUNCTION__, trigger.getTagName(),
5403 trigger.entryValue);
5404 return res;
5405 }
5406
5407 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5408 trigger.getTagName(),
5409 trigger.entryValue);
5410 }
5411
5412 mTriggerMap.clear();
5413
5414 return count;
5415}
5416
5417status_t Camera3Device::RequestThread::removeTriggers(
5418 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005419 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005420 Mutex::Autolock al(mTriggerMutex);
5421
Emilian Peevaebbe412018-01-15 13:53:24 +00005422 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005423
5424 /**
5425 * Replace all old entries with their old values.
5426 */
5427 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5428 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5429
5430 status_t res;
5431
5432 uint32_t tag = trigger.metadataTag;
5433 switch (trigger.getTagType()) {
5434 case TYPE_BYTE: {
5435 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5436 res = metadata.update(tag,
5437 &entryValue,
5438 /*count*/1);
5439 break;
5440 }
5441 case TYPE_INT32:
5442 res = metadata.update(tag,
5443 &trigger.entryValue,
5444 /*count*/1);
5445 break;
5446 default:
5447 ALOGE("%s: Type not supported: 0x%x",
5448 __FUNCTION__,
5449 trigger.getTagType());
5450 return INVALID_OPERATION;
5451 }
5452
5453 if (res != OK) {
5454 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5455 ", trigger value %d", __FUNCTION__,
5456 trigger.getTagName(), trigger.entryValue);
5457 return res;
5458 }
5459 }
5460 mTriggerReplacedMap.clear();
5461
5462 /**
5463 * Remove all new entries.
5464 */
5465 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5466 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5467 status_t res = metadata.erase(trigger.metadataTag);
5468
5469 if (res != OK) {
5470 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5471 ", trigger value %d", __FUNCTION__,
5472 trigger.getTagName(), trigger.entryValue);
5473 return res;
5474 }
5475 }
5476 mTriggerRemovedMap.clear();
5477
5478 return OK;
5479}
5480
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005481status_t Camera3Device::RequestThread::addDummyTriggerIds(
5482 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005483 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005484 static const int32_t dummyTriggerId = 1;
5485 status_t res;
5486
Emilian Peevaebbe412018-01-15 13:53:24 +00005487 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005488
5489 // If AF trigger is active, insert a dummy AF trigger ID if none already
5490 // exists
5491 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5492 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5493 if (afTrigger.count > 0 &&
5494 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5495 afId.count == 0) {
5496 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5497 if (res != OK) return res;
5498 }
5499
5500 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5501 // if none already exists
5502 camera_metadata_entry pcTrigger =
5503 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5504 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5505 if (pcTrigger.count > 0 &&
5506 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5507 pcId.count == 0) {
5508 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5509 &dummyTriggerId, 1);
5510 if (res != OK) return res;
5511 }
5512
5513 return OK;
5514}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005515
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005516/**
5517 * PreparerThread inner class methods
5518 */
5519
5520Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005521 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005522 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005523}
5524
5525Camera3Device::PreparerThread::~PreparerThread() {
5526 Thread::requestExitAndWait();
5527 if (mCurrentStream != nullptr) {
5528 mCurrentStream->cancelPrepare();
5529 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5530 mCurrentStream.clear();
5531 }
5532 clear();
5533}
5534
Ruben Brunkc78ac262015-08-13 17:58:46 -07005535status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005536 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005537 status_t res;
5538
5539 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005540 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005541
Ruben Brunkc78ac262015-08-13 17:58:46 -07005542 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005543 if (res == OK) {
5544 // No preparation needed, fire listener right off
5545 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005546 if (listener != NULL) {
5547 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005548 }
5549 return OK;
5550 } else if (res != NOT_ENOUGH_DATA) {
5551 return res;
5552 }
5553
5554 // Need to prepare, start up thread if necessary
5555 if (!mActive) {
5556 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5557 // isn't running
5558 Thread::requestExitAndWait();
5559 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5560 if (res != OK) {
5561 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005562 if (listener != NULL) {
5563 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005564 }
5565 return res;
5566 }
5567 mCancelNow = false;
5568 mActive = true;
5569 ALOGV("%s: Preparer stream started", __FUNCTION__);
5570 }
5571
5572 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005573 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005574 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5575
5576 return OK;
5577}
5578
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005579void Camera3Device::PreparerThread::pause() {
5580 ATRACE_CALL();
5581
5582 Mutex::Autolock l(mLock);
5583
5584 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5585 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5586 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5587 int currentMaxCount = mCurrentMaxCount;
5588 mPendingStreams.clear();
5589 mCancelNow = true;
5590 while (mActive) {
5591 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5592 if (res == TIMED_OUT) {
5593 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5594 return;
5595 } else if (res != OK) {
5596 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5597 return;
5598 }
5599 }
5600
5601 //Check whether the prepare thread was able to complete the current
5602 //stream. In case work is still pending emplace it along with the rest
5603 //of the streams in the pending list.
5604 if (currentStream != nullptr) {
5605 if (!mCurrentPrepareComplete) {
5606 pendingStreams.emplace(currentMaxCount, currentStream);
5607 }
5608 }
5609
5610 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5611 for (const auto& it : mPendingStreams) {
5612 it.second->cancelPrepare();
5613 }
5614}
5615
5616status_t Camera3Device::PreparerThread::resume() {
5617 ATRACE_CALL();
5618 status_t res;
5619
5620 Mutex::Autolock l(mLock);
5621 sp<NotificationListener> listener = mListener.promote();
5622
5623 if (mActive) {
5624 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5625 return NO_INIT;
5626 }
5627
5628 auto it = mPendingStreams.begin();
5629 for (; it != mPendingStreams.end();) {
5630 res = it->second->startPrepare(it->first);
5631 if (res == OK) {
5632 if (listener != NULL) {
5633 listener->notifyPrepared(it->second->getId());
5634 }
5635 it = mPendingStreams.erase(it);
5636 } else if (res != NOT_ENOUGH_DATA) {
5637 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5638 res, strerror(-res));
5639 it = mPendingStreams.erase(it);
5640 } else {
5641 it++;
5642 }
5643 }
5644
5645 if (mPendingStreams.empty()) {
5646 return OK;
5647 }
5648
5649 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5650 if (res != OK) {
5651 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5652 __FUNCTION__, res, strerror(-res));
5653 return res;
5654 }
5655 mCancelNow = false;
5656 mActive = true;
5657 ALOGV("%s: Preparer stream started", __FUNCTION__);
5658
5659 return OK;
5660}
5661
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005662status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005663 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005664 Mutex::Autolock l(mLock);
5665
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005666 for (const auto& it : mPendingStreams) {
5667 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005668 }
5669 mPendingStreams.clear();
5670 mCancelNow = true;
5671
5672 return OK;
5673}
5674
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005675void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005676 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005677 Mutex::Autolock l(mLock);
5678 mListener = listener;
5679}
5680
5681bool Camera3Device::PreparerThread::threadLoop() {
5682 status_t res;
5683 {
5684 Mutex::Autolock l(mLock);
5685 if (mCurrentStream == nullptr) {
5686 // End thread if done with work
5687 if (mPendingStreams.empty()) {
5688 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5689 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5690 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5691 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005692 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005693 return false;
5694 }
5695
5696 // Get next stream to prepare
5697 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005698 mCurrentStream = it->second;
5699 mCurrentMaxCount = it->first;
5700 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005701 mPendingStreams.erase(it);
5702 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5703 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5704 } else if (mCancelNow) {
5705 mCurrentStream->cancelPrepare();
5706 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5707 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5708 mCurrentStream.clear();
5709 mCancelNow = false;
5710 return true;
5711 }
5712 }
5713
5714 res = mCurrentStream->prepareNextBuffer();
5715 if (res == NOT_ENOUGH_DATA) return true;
5716 if (res != OK) {
5717 // Something bad happened; try to recover by cancelling prepare and
5718 // signalling listener anyway
5719 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5720 mCurrentStream->getId(), res, strerror(-res));
5721 mCurrentStream->cancelPrepare();
5722 }
5723
5724 // This stream has finished, notify listener
5725 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005726 sp<NotificationListener> listener = mListener.promote();
5727 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005728 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5729 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005730 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005731 }
5732
5733 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5734 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005735 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005736
5737 return true;
5738}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005739
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005740/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005741 * Static callback forwarding methods from HAL to instance
5742 */
5743
5744void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5745 const camera3_capture_result *result) {
5746 Camera3Device *d =
5747 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005748
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005749 d->processCaptureResult(result);
5750}
5751
5752void Camera3Device::sNotify(const camera3_callback_ops *cb,
5753 const camera3_notify_msg *msg) {
5754 Camera3Device *d =
5755 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5756 d->notify(msg);
5757}
5758
5759}; // namespace android