blob: 82672e5fbceac5687f128ff36ef4819f965e4cb6 [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 Wang2bfffde2018-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 Wang2bfffde2018-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);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800280
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700281 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800282
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700283 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700284 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700285 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700286 {
287 Mutex::Autolock l(mLock);
288 if (mStatus == STATUS_UNINITIALIZED) return res;
289
290 if (mStatus == STATUS_ACTIVE ||
291 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
292 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700293 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700294 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700295 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700296 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700297 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700298 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700299 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
300 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700301 // Continue to close device even in case of error
302 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700303 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800304 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800305
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700306 if (mStatus == STATUS_ERROR) {
307 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700308 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700309
310 if (mStatusTracker != NULL) {
311 mStatusTracker->requestExit();
312 }
313
314 if (mRequestThread != NULL) {
315 mRequestThread->requestExit();
316 }
317
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700318 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
319 for (size_t i = 0; i < mOutputStreams.size(); i++) {
320 streams.push_back(mOutputStreams[i]);
321 }
322 if (mInputStream != nullptr) {
323 streams.push_back(mInputStream);
324 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700325 }
326
327 // Joining done without holding mLock, otherwise deadlocks may ensue
328 // as the threads try to access parent state
329 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
330 // HAL may be in a bad state, so waiting for request thread
331 // (which may be stuck in the HAL processCaptureRequest call)
332 // could be dangerous.
333 mRequestThread->join();
334 }
335
336 if (mStatusTracker != NULL) {
337 mStatusTracker->join();
338 }
339
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800340 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700341 {
342 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800343 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700344 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800345 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700346 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800347
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700348 // Call close without internal mutex held, as the HAL close may need to
349 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800350 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700351
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700352 flushInflightRequests();
353
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700354 {
355 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800356 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700357 mOutputStreams.clear();
358 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700359 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700360 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700361 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700362 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800363
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700364 for (auto& weakStream : streams) {
365 sp<Camera3StreamInterface> stream = weakStream.promote();
366 if (stream != nullptr) {
367 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
368 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
369 }
370 }
371
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700372 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700373 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800374}
375
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700376// For dumping/debugging only -
377// try to acquire a lock a few times, eventually give up to proceed with
378// debug/dump operations
379bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
380 bool gotLock = false;
381 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
382 if (lock.tryLock() == NO_ERROR) {
383 gotLock = true;
384 break;
385 } else {
386 usleep(kDumpSleepDuration);
387 }
388 }
389 return gotLock;
390}
391
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700392Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
393 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100394 const int STREAM_CONFIGURATION_SIZE = 4;
395 const int STREAM_FORMAT_OFFSET = 0;
396 const int STREAM_WIDTH_OFFSET = 1;
397 const int STREAM_HEIGHT_OFFSET = 2;
398 const int STREAM_IS_INPUT_OFFSET = 3;
399 camera_metadata_ro_entry_t availableStreamConfigs =
400 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
401 if (availableStreamConfigs.count == 0 ||
402 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
403 return Size(0, 0);
404 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700405
Emilian Peev08dd2452017-04-06 16:55:14 +0100406 // Get max jpeg size (area-wise).
407 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
408 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
409 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
410 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
411 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
412 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
413 && format == HAL_PIXEL_FORMAT_BLOB &&
414 (width * height > maxJpegWidth * maxJpegHeight)) {
415 maxJpegWidth = width;
416 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700417 }
418 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100419
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700420 return Size(maxJpegWidth, maxJpegHeight);
421}
422
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800423nsecs_t Camera3Device::getMonoToBoottimeOffset() {
424 // try three times to get the clock offset, choose the one
425 // with the minimum gap in measurements.
426 const int tries = 3;
427 nsecs_t bestGap, measured;
428 for (int i = 0; i < tries; ++i) {
429 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
430 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
431 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
432 const nsecs_t gap = tmono2 - tmono;
433 if (i == 0 || gap < bestGap) {
434 bestGap = gap;
435 measured = tbase - ((tmono + tmono2) >> 1);
436 }
437 }
438 return measured;
439}
440
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800441hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
442 int frameworkFormat) {
443 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
444}
445
446DataspaceFlags Camera3Device::mapToHidlDataspace(
447 android_dataspace dataSpace) {
448 return dataSpace;
449}
450
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700451BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100452 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700453 return usage;
454}
455
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800456StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
457 switch (rotation) {
458 case CAMERA3_STREAM_ROTATION_0:
459 return StreamRotation::ROTATION_0;
460 case CAMERA3_STREAM_ROTATION_90:
461 return StreamRotation::ROTATION_90;
462 case CAMERA3_STREAM_ROTATION_180:
463 return StreamRotation::ROTATION_180;
464 case CAMERA3_STREAM_ROTATION_270:
465 return StreamRotation::ROTATION_270;
466 }
467 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
468 return StreamRotation::ROTATION_0;
469}
470
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800471status_t Camera3Device::mapToStreamConfigurationMode(
472 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
473 if (mode == nullptr) return BAD_VALUE;
474 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
475 switch(operationMode) {
476 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
477 *mode = StreamConfigurationMode::NORMAL_MODE;
478 break;
479 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
480 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
481 break;
482 default:
483 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
484 return BAD_VALUE;
485 }
486 } else {
487 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800488 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800489 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800490}
491
492camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
493 switch (status) {
494 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
495 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
496 }
497 return CAMERA3_BUFFER_STATUS_ERROR;
498}
499
500int Camera3Device::mapToFrameworkFormat(
501 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
502 return static_cast<uint32_t>(pixelFormat);
503}
504
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700505android_dataspace Camera3Device::mapToFrameworkDataspace(
506 DataspaceFlags dataSpace) {
507 return static_cast<android_dataspace>(dataSpace);
508}
509
Emilian Peev050f5dc2017-05-18 14:43:56 +0100510uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700511 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700512 return usage;
513}
514
Emilian Peev050f5dc2017-05-18 14:43:56 +0100515uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700516 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700517 return usage;
518}
519
Zhijun Hef7da0962014-04-24 13:27:56 -0700520ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700521 // Get max jpeg size (area-wise).
522 Size maxJpegResolution = getMaxJpegResolution();
523 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800524 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
525 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700526 return BAD_VALUE;
527 }
528
Zhijun Hef7da0962014-04-24 13:27:56 -0700529 // Get max jpeg buffer size
530 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700531 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
532 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800533 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
534 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700535 return BAD_VALUE;
536 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700537 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800538 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700539
540 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700541 float scaleFactor = ((float) (width * height)) /
542 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800543 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
544 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700545 if (jpegBufferSize > maxJpegBufferSize) {
546 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700547 }
548
549 return jpegBufferSize;
550}
551
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700552ssize_t Camera3Device::getPointCloudBufferSize() const {
553 const int FLOATS_PER_POINT=4;
554 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
555 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800556 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
557 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700558 return BAD_VALUE;
559 }
560 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
561 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
562 return maxBytesForPointCloud;
563}
564
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800565ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800566 const int PER_CONFIGURATION_SIZE = 3;
567 const int WIDTH_OFFSET = 0;
568 const int HEIGHT_OFFSET = 1;
569 const int SIZE_OFFSET = 2;
570 camera_metadata_ro_entry rawOpaqueSizes =
571 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800572 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800573 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800574 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
575 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800576 return BAD_VALUE;
577 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700578
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800579 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
580 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
581 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
582 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
583 }
584 }
585
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800586 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
587 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800588 return BAD_VALUE;
589}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700590
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800591status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
592 ATRACE_CALL();
593 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700594
595 // Try to lock, but continue in case of failure (to avoid blocking in
596 // deadlocks)
597 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
598 bool gotLock = tryLockSpinRightRound(mLock);
599
600 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800601 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
602 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700603 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800604 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
605 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700606
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800607 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700608
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800609 String16 templatesOption("-t");
610 int n = args.size();
611 for (int i = 0; i < n; i++) {
612 if (args[i] == templatesOption) {
613 dumpTemplates = true;
614 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000615 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700616 if (i + 1 < n) {
617 String8 monitorTags = String8(args[i + 1]);
618 if (monitorTags == "off") {
619 mTagMonitor.disableMonitoring();
620 } else {
621 mTagMonitor.parseTagsToMonitor(monitorTags);
622 }
623 } else {
624 mTagMonitor.disableMonitoring();
625 }
626 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800627 }
628
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800629 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800630
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800631 const char *status =
632 mStatus == STATUS_ERROR ? "ERROR" :
633 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700634 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
635 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800636 mStatus == STATUS_ACTIVE ? "ACTIVE" :
637 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700638
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800639 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700640 if (mStatus == STATUS_ERROR) {
641 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
642 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800643 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800644 const char *mode =
645 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
646 mOperatingMode == static_cast<int>(
647 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
648 "CUSTOM";
649 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800650
651 if (mInputStream != NULL) {
652 write(fd, lines.string(), lines.size());
653 mInputStream->dump(fd, args);
654 } else {
655 lines.appendFormat(" No input stream.\n");
656 write(fd, lines.string(), lines.size());
657 }
658 for (size_t i = 0; i < mOutputStreams.size(); i++) {
659 mOutputStreams[i]->dump(fd,args);
660 }
661
Zhijun He431503c2016-03-07 17:30:16 -0800662 if (mBufferManager != NULL) {
663 lines = String8(" Camera3 Buffer Manager:\n");
664 write(fd, lines.string(), lines.size());
665 mBufferManager->dump(fd, args);
666 }
Zhijun He125684a2015-12-26 15:07:30 -0800667
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700668 lines = String8(" In-flight requests:\n");
669 if (mInFlightMap.size() == 0) {
670 lines.append(" None\n");
671 } else {
672 for (size_t i = 0; i < mInFlightMap.size(); i++) {
673 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700674 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700675 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800676 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700677 r.numBuffersLeft);
678 }
679 }
680 write(fd, lines.string(), lines.size());
681
Shuzhen Wang686f6442017-06-20 16:16:04 -0700682 if (mRequestThread != NULL) {
683 mRequestThread->dumpCaptureRequestLatency(fd,
684 " ProcessCaptureRequest latency histogram:");
685 }
686
Igor Murashkin1e479c02013-09-06 16:55:14 -0700687 {
688 lines = String8(" Last request sent:\n");
689 write(fd, lines.string(), lines.size());
690
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700691 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700692 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
693 }
694
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800695 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800696 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800697 "TEMPLATE_PREVIEW",
698 "TEMPLATE_STILL_CAPTURE",
699 "TEMPLATE_VIDEO_RECORD",
700 "TEMPLATE_VIDEO_SNAPSHOT",
701 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800702 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800703 };
704
705 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800706 camera_metadata_t *templateRequest = nullptr;
707 mInterface->constructDefaultRequestSettings(
708 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800709 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800710 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800711 lines.append(" Not supported\n");
712 write(fd, lines.string(), lines.size());
713 } else {
714 write(fd, lines.string(), lines.size());
715 dump_indented_camera_metadata(templateRequest,
716 fd, /*verbosity*/2, /*indentation*/8);
717 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800718 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800719 }
720 }
721
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700722 mTagMonitor.dumpMonitoredMetadata(fd);
723
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800724 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800725 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800726 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800727 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800728 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800729
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700730 if (gotLock) mLock.unlock();
731 if (gotInterfaceLock) mInterfaceLock.unlock();
732
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800733 return OK;
734}
735
Shuzhen Wang2bfffde2018-07-11 14:00:29 -0700736const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800737 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800738 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
739 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700740 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800741 mStatus == STATUS_ERROR ?
742 "when in error state" : "before init");
743 }
Shuzhen Wang2bfffde2018-07-11 14:00:29 -0700744 if (physicalId.isEmpty()) {
745 return mDeviceInfo;
746 } else {
747 std::string id(physicalId.c_str());
748 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
749 return mPhysicalDeviceInfoMap.at(id);
750 } else {
751 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
752 return mDeviceInfo;
753 }
754 }
755}
756
757const CameraMetadata& Camera3Device::info() const {
758 String8 emptyId;
759 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800760}
761
Jianing Wei90e59c92014-03-12 18:29:36 -0700762status_t Camera3Device::checkStatusOkToCaptureLocked() {
763 switch (mStatus) {
764 case STATUS_ERROR:
765 CLOGE("Device has encountered a serious error");
766 return INVALID_OPERATION;
767 case STATUS_UNINITIALIZED:
768 CLOGE("Device not initialized");
769 return INVALID_OPERATION;
770 case STATUS_UNCONFIGURED:
771 case STATUS_CONFIGURED:
772 case STATUS_ACTIVE:
773 // OK
774 break;
775 default:
776 SET_ERR_L("Unexpected status: %d", mStatus);
777 return INVALID_OPERATION;
778 }
779 return OK;
780}
781
782status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000783 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700784 const std::list<const SurfaceMap> &surfaceMaps,
785 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700786 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700787 if (requestList == NULL) {
788 CLOGE("requestList cannot be NULL.");
789 return BAD_VALUE;
790 }
791
Jianing Weicb0652e2014-03-12 18:29:36 -0700792 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000793 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700794 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
795 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
796 ++metadataIt, ++surfaceMapIt) {
797 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700798 if (newRequest == 0) {
799 CLOGE("Can't create capture request");
800 return BAD_VALUE;
801 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700802
Shuzhen Wang9d066012016-09-30 11:30:20 -0700803 newRequest->mRepeating = repeating;
804
Jianing Weicb0652e2014-03-12 18:29:36 -0700805 // Setup burst Id and request Id
806 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000807 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
808 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700809 CLOGE("RequestID entry exists; but must not be empty in metadata");
810 return BAD_VALUE;
811 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000812 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
813 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700814 } else {
815 CLOGE("RequestID does not exist in metadata");
816 return BAD_VALUE;
817 }
818
Jianing Wei90e59c92014-03-12 18:29:36 -0700819 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700820
821 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700822 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700823 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
824 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
825 return BAD_VALUE;
826 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700827
828 // Setup batch size if this is a high speed video recording request.
829 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
830 auto firstRequest = requestList->begin();
831 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
832 if (outputStream->isVideoStream()) {
833 (*firstRequest)->mBatchSize = requestList->size();
834 break;
835 }
836 }
837 }
838
Jianing Wei90e59c92014-03-12 18:29:36 -0700839 return OK;
840}
841
Jianing Weicb0652e2014-03-12 18:29:36 -0700842status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800843 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800844
Emilian Peevaebbe412018-01-15 13:53:24 +0000845 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700846 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000847 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700848
Emilian Peevaebbe412018-01-15 13:53:24 +0000849 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700850}
851
Emilian Peevaebbe412018-01-15 13:53:24 +0000852void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700853 std::list<const SurfaceMap>& surfaceMaps,
854 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000855 PhysicalCameraSettingsList requestList;
856 requestList.push_back({std::string(getId().string()), request});
857 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858
859 SurfaceMap surfaceMap;
860 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
861 // With no surface list passed in, stream and surface will have 1-to-1
862 // mapping. So the surface index is 0 for each stream in the surfaceMap.
863 for (size_t i = 0; i < streams.count; i++) {
864 surfaceMap[streams.data.i32[i]].push_back(0);
865 }
866 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800867}
868
Jianing Wei90e59c92014-03-12 18:29:36 -0700869status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000870 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700871 const std::list<const SurfaceMap> &surfaceMaps,
872 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700873 /*out*/
874 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700875 ATRACE_CALL();
876 Mutex::Autolock il(mInterfaceLock);
877 Mutex::Autolock l(mLock);
878
879 status_t res = checkStatusOkToCaptureLocked();
880 if (res != OK) {
881 // error logged by previous call
882 return res;
883 }
884
885 RequestList requestList;
886
Shuzhen Wang0129d522016-10-30 22:43:41 -0700887 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
888 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700889 if (res != OK) {
890 // error logged by previous call
891 return res;
892 }
893
894 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700895 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700896 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700897 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700898 }
899
900 if (res == OK) {
901 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
902 if (res != OK) {
903 SET_ERR_L("Can't transition to active in %f seconds!",
904 kActiveTimeout/1e9);
905 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800906 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700907 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700908 } else {
909 CLOGE("Cannot queue request. Impossible.");
910 return BAD_VALUE;
911 }
912
913 return res;
914}
915
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800916hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800917 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800918 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700919 // Ideally we should grab mLock, but that can lead to deadlock, and
920 // it's not super important to get up to date value of mStatus for this
921 // warning print, hence skipping the lock here
922 if (mStatus == STATUS_ERROR) {
923 // Per API contract, HAL should act as closed after device error
924 // But mStatus can be set to error by framework as well, so just log
925 // a warning here.
926 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700927 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700928
929 if (mProcessCaptureResultLock.tryLock() != OK) {
930 // This should never happen; it indicates a wrong client implementation
931 // that doesn't follow the contract. But, we can be tolerant here.
932 ALOGE("%s: callback overlapped! waiting 1s...",
933 __FUNCTION__);
934 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
935 ALOGE("%s: cannot acquire lock in 1s, dropping results",
936 __FUNCTION__);
937 // really don't know what to do, so bail out.
938 return hardware::Void();
939 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800940 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700941 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800942 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -0700943 }
944 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800945 return hardware::Void();
946}
947
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800948// Only one processCaptureResult should be called at a time, so
949// the locks won't block. The locks are present here simply to enforce this.
950hardware::Return<void> Camera3Device::processCaptureResult(
951 const hardware::hidl_vec<
952 hardware::camera::device::V3_2::CaptureResult>& results) {
953 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
954
955 // Ideally we should grab mLock, but that can lead to deadlock, and
956 // it's not super important to get up to date value of mStatus for this
957 // warning print, hence skipping the lock here
958 if (mStatus == STATUS_ERROR) {
959 // Per API contract, HAL should act as closed after device error
960 // But mStatus can be set to error by framework as well, so just log
961 // a warning here.
962 ALOGW("%s: received capture result in error state.", __FUNCTION__);
963 }
964
965 if (mProcessCaptureResultLock.tryLock() != OK) {
966 // This should never happen; it indicates a wrong client implementation
967 // that doesn't follow the contract. But, we can be tolerant here.
968 ALOGE("%s: callback overlapped! waiting 1s...",
969 __FUNCTION__);
970 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
971 ALOGE("%s: cannot acquire lock in 1s, dropping results",
972 __FUNCTION__);
973 // really don't know what to do, so bail out.
974 return hardware::Void();
975 }
976 }
977 for (const auto& result : results) {
978 processOneCaptureResultLocked(result, noPhysMetadata);
979 }
980 mProcessCaptureResultLock.unlock();
981 return hardware::Void();
982}
983
984status_t Camera3Device::readOneCameraMetadataLocked(
985 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
986 const hardware::camera::device::V3_2::CameraMetadata& result) {
987 if (fmqResultSize > 0) {
988 resultMetadata.resize(fmqResultSize);
989 if (mResultMetadataQueue == nullptr) {
990 return NO_MEMORY; // logged in initialize()
991 }
992 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
993 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
994 __FUNCTION__, fmqResultSize);
995 return INVALID_OPERATION;
996 }
997 } else {
998 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
999 result.size());
1000 }
1001
1002 if (resultMetadata.size() != 0) {
1003 status_t res;
1004 const camera_metadata_t* metadata =
1005 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1006 size_t expected_metadata_size = resultMetadata.size();
1007 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1008 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1009 __FUNCTION__, strerror(-res), res);
1010 return INVALID_OPERATION;
1011 }
1012 }
1013
1014 return OK;
1015}
1016
Yifan Honga640c5a2017-04-12 16:30:31 -07001017void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001018 const hardware::camera::device::V3_2::CaptureResult& result,
1019 const hardware::hidl_vec<
1020 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001021 camera3_capture_result r;
1022 status_t res;
1023 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001024
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001025 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001026 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001027 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1028 if (res != OK) {
1029 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1030 __FUNCTION__, result.frameNumber);
1031 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001032 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001033 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001034
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001035 // Read and validate physical camera metadata
1036 size_t physResultCount = physicalCameraMetadatas.size();
1037 std::vector<const char*> physCamIds(physResultCount);
1038 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1039 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1040 physResultMetadata.resize(physResultCount);
1041 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1042 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1043 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1044 if (res != OK) {
1045 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1046 __FUNCTION__, result.frameNumber,
1047 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001048 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001049 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001050 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1051 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1052 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001053 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001054 r.num_physcam_metadata = physResultCount;
1055 r.physcam_ids = physCamIds.data();
1056 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001057
1058 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1059 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1060 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1061 auto& bDst = outputBuffers[i];
1062 const StreamBuffer &bSrc = result.outputBuffers[i];
1063
1064 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001065 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001066 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1067 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001068 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001069 }
1070 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
1071
1072 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08001073 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001074 if (res != OK) {
1075 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1076 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001077 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001078 }
1079 bDst.buffer = buffer;
1080 bDst.status = mapHidlBufferStatus(bSrc.status);
1081 bDst.acquire_fence = -1;
1082 if (bSrc.releaseFence == nullptr) {
1083 bDst.release_fence = -1;
1084 } else if (bSrc.releaseFence->numFds == 1) {
1085 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1086 } else {
1087 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1088 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001089 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001090 }
1091 }
1092 r.num_output_buffers = outputBuffers.size();
1093 r.output_buffers = outputBuffers.data();
1094
1095 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001096 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001097 r.input_buffer = nullptr;
1098 } else {
1099 if (mInputStream->getId() != result.inputBuffer.streamId) {
1100 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1101 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001102 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001103 }
1104 inputBuffer.stream = mInputStream->asHalStream();
1105 buffer_handle_t *buffer;
1106 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1107 &buffer);
1108 if (res != OK) {
1109 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1110 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001111 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001112 }
1113 inputBuffer.buffer = buffer;
1114 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1115 inputBuffer.acquire_fence = -1;
1116 if (result.inputBuffer.releaseFence == nullptr) {
1117 inputBuffer.release_fence = -1;
1118 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1119 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1120 } else {
1121 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1122 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001123 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001124 }
1125 r.input_buffer = &inputBuffer;
1126 }
1127
1128 r.partial_result = result.partialResult;
1129
1130 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001131}
1132
1133hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001134 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001135 // Ideally we should grab mLock, but that can lead to deadlock, and
1136 // it's not super important to get up to date value of mStatus for this
1137 // warning print, hence skipping the lock here
1138 if (mStatus == STATUS_ERROR) {
1139 // Per API contract, HAL should act as closed after device error
1140 // But mStatus can be set to error by framework as well, so just log
1141 // a warning here.
1142 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001143 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001144
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001145 for (const auto& msg : msgs) {
1146 notify(msg);
1147 }
1148 return hardware::Void();
1149}
1150
1151void Camera3Device::notify(
1152 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1153
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001154 camera3_notify_msg m;
1155 switch (msg.type) {
1156 case MsgType::ERROR:
1157 m.type = CAMERA3_MSG_ERROR;
1158 m.message.error.frame_number = msg.msg.error.frameNumber;
1159 if (msg.msg.error.errorStreamId >= 0) {
1160 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001161 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001162 ALOGE("%s: Frame %d: Invalid error stream id %d",
1163 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001164 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001165 }
1166 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1167 } else {
1168 m.message.error.error_stream = nullptr;
1169 }
1170 switch (msg.msg.error.errorCode) {
1171 case ErrorCode::ERROR_DEVICE:
1172 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1173 break;
1174 case ErrorCode::ERROR_REQUEST:
1175 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1176 break;
1177 case ErrorCode::ERROR_RESULT:
1178 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1179 break;
1180 case ErrorCode::ERROR_BUFFER:
1181 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1182 break;
1183 }
1184 break;
1185 case MsgType::SHUTTER:
1186 m.type = CAMERA3_MSG_SHUTTER;
1187 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1188 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1189 break;
1190 }
1191 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001192}
1193
Emilian Peevaebbe412018-01-15 13:53:24 +00001194status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001195 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001196 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001197 ATRACE_CALL();
1198
Emilian Peevaebbe412018-01-15 13:53:24 +00001199 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001200}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001201
Jianing Weicb0652e2014-03-12 18:29:36 -07001202status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1203 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001204 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001205
Emilian Peevaebbe412018-01-15 13:53:24 +00001206 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001207 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001208 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001209
Emilian Peevaebbe412018-01-15 13:53:24 +00001210 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001211 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001212}
1213
Emilian Peevaebbe412018-01-15 13:53:24 +00001214status_t Camera3Device::setStreamingRequestList(
1215 const List<const PhysicalCameraSettingsList> &requestsList,
1216 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001217 ATRACE_CALL();
1218
Emilian Peevaebbe412018-01-15 13:53:24 +00001219 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001220}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001221
1222sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001223 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001224 status_t res;
1225
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001226 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001227 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1228 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001229 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1230 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001231 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001232 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001233 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001234 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001235 } else if (mStatus == STATUS_UNCONFIGURED) {
1236 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001237 CLOGE("No streams configured");
1238 return NULL;
1239 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001240 }
1241
Shuzhen Wang0129d522016-10-30 22:43:41 -07001242 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001243 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001244}
1245
Jianing Weicb0652e2014-03-12 18:29:36 -07001246status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001247 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001248 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001249 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001250
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001251 switch (mStatus) {
1252 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001253 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001254 return INVALID_OPERATION;
1255 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001256 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001257 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001258 case STATUS_UNCONFIGURED:
1259 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001260 case STATUS_ACTIVE:
1261 // OK
1262 break;
1263 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001264 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 return INVALID_OPERATION;
1266 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001267 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001268
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001269 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001270}
1271
1272status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1273 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001274 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001275
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001276 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001277}
1278
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001279status_t Camera3Device::createInputStream(
1280 uint32_t width, uint32_t height, int format, int *id) {
1281 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001282 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001283 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001284 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001285 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1286 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001287
1288 status_t res;
1289 bool wasActive = false;
1290
1291 switch (mStatus) {
1292 case STATUS_ERROR:
1293 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1294 return INVALID_OPERATION;
1295 case STATUS_UNINITIALIZED:
1296 ALOGE("%s: Device not initialized", __FUNCTION__);
1297 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001298 case STATUS_UNCONFIGURED:
1299 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001300 // OK
1301 break;
1302 case STATUS_ACTIVE:
1303 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001304 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001305 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001306 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001307 return res;
1308 }
1309 wasActive = true;
1310 break;
1311 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001312 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001313 return INVALID_OPERATION;
1314 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001315 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001316
1317 if (mInputStream != 0) {
1318 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1319 return INVALID_OPERATION;
1320 }
1321
1322 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1323 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001324 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001325
1326 mInputStream = newStream;
1327
1328 *id = mNextStreamId++;
1329
1330 // Continue captures if active at start
1331 if (wasActive) {
1332 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001333 // Reuse current operating mode and session parameters for new stream config
1334 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001335 if (res != OK) {
1336 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1337 __FUNCTION__, mNextStreamId, strerror(-res), res);
1338 return res;
1339 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001340 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001341 }
1342
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001343 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001344 return OK;
1345}
1346
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001347status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001348 uint32_t width, uint32_t height, int format,
1349 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001350 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001351 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001352 ATRACE_CALL();
1353
1354 if (consumer == nullptr) {
1355 ALOGE("%s: consumer must not be null", __FUNCTION__);
1356 return BAD_VALUE;
1357 }
1358
1359 std::vector<sp<Surface>> consumers;
1360 consumers.push_back(consumer);
1361
1362 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001363 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1364 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001365}
1366
1367status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1368 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1369 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001370 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001371 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001372 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001373
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001374 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001375 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001376 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001377 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001378 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1379 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1380 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001381
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001382 status_t res;
1383 bool wasActive = false;
1384
1385 switch (mStatus) {
1386 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001387 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001388 return INVALID_OPERATION;
1389 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001390 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001391 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001392 case STATUS_UNCONFIGURED:
1393 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001394 // OK
1395 break;
1396 case STATUS_ACTIVE:
1397 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001398 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001399 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001400 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001401 return res;
1402 }
1403 wasActive = true;
1404 break;
1405 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001406 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001407 return INVALID_OPERATION;
1408 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001409 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001410
1411 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001412
Shuzhen Wang0129d522016-10-30 22:43:41 -07001413 if (consumers.size() == 0 && !hasDeferredConsumer) {
1414 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1415 return BAD_VALUE;
1416 }
Zhijun He5d677d12016-05-29 16:52:39 -07001417
Shuzhen Wang0129d522016-10-30 22:43:41 -07001418 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001419 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1420 return BAD_VALUE;
1421 }
1422
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001423 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001424 ssize_t blobBufferSize;
1425 if (dataSpace != HAL_DATASPACE_DEPTH) {
1426 blobBufferSize = getJpegBufferSize(width, height);
1427 if (blobBufferSize <= 0) {
1428 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1429 return BAD_VALUE;
1430 }
1431 } else {
1432 blobBufferSize = getPointCloudBufferSize();
1433 if (blobBufferSize <= 0) {
1434 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1435 return BAD_VALUE;
1436 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001437 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001438 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001439 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001440 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001441 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1442 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1443 if (rawOpaqueBufferSize <= 0) {
1444 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1445 return BAD_VALUE;
1446 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001447 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001448 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001449 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001450 } else if (isShared) {
1451 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1452 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001453 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001454 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001455 newStream = new Camera3OutputStream(mNextStreamId,
1456 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001457 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001458 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001459 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001460 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001461 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001462 }
Emilian Peev40ead602017-09-26 15:46:36 +01001463
1464 size_t consumerCount = consumers.size();
1465 for (size_t i = 0; i < consumerCount; i++) {
1466 int id = newStream->getSurfaceId(consumers[i]);
1467 if (id < 0) {
1468 SET_ERR_L("Invalid surface id");
1469 return BAD_VALUE;
1470 }
1471 if (surfaceIds != nullptr) {
1472 surfaceIds->push_back(id);
1473 }
1474 }
1475
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001476 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001477
Emilian Peev08dd2452017-04-06 16:55:14 +01001478 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001479
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001480 res = mOutputStreams.add(mNextStreamId, newStream);
1481 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001482 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001483 return res;
1484 }
1485
1486 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001487 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001488
1489 // Continue captures if active at start
1490 if (wasActive) {
1491 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001492 // Reuse current operating mode and session parameters for new stream config
1493 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001494 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001495 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1496 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001497 return res;
1498 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001499 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001500 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001501 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001503}
1504
Emilian Peev710c1422017-08-30 11:19:38 +01001505status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001506 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001507 if (nullptr == streamInfo) {
1508 return BAD_VALUE;
1509 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001510 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001511 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001512
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001513 switch (mStatus) {
1514 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001515 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001516 return INVALID_OPERATION;
1517 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001518 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001519 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001520 case STATUS_UNCONFIGURED:
1521 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001522 case STATUS_ACTIVE:
1523 // OK
1524 break;
1525 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001526 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001527 return INVALID_OPERATION;
1528 }
1529
1530 ssize_t idx = mOutputStreams.indexOfKey(id);
1531 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001532 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001533 return idx;
1534 }
1535
Emilian Peev710c1422017-08-30 11:19:38 +01001536 streamInfo->width = mOutputStreams[idx]->getWidth();
1537 streamInfo->height = mOutputStreams[idx]->getHeight();
1538 streamInfo->format = mOutputStreams[idx]->getFormat();
1539 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1540 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1541 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001542 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1543 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001544 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001545}
1546
1547status_t Camera3Device::setStreamTransform(int id,
1548 int transform) {
1549 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001550 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001552
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 switch (mStatus) {
1554 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001555 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 return INVALID_OPERATION;
1557 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001558 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001559 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001560 case STATUS_UNCONFIGURED:
1561 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001562 case STATUS_ACTIVE:
1563 // OK
1564 break;
1565 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001566 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001567 return INVALID_OPERATION;
1568 }
1569
1570 ssize_t idx = mOutputStreams.indexOfKey(id);
1571 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001572 CLOGE("Stream %d does not exist",
1573 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001574 return BAD_VALUE;
1575 }
1576
1577 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001578}
1579
1580status_t Camera3Device::deleteStream(int id) {
1581 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001582 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583 Mutex::Autolock l(mLock);
1584 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001585
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001586 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001587
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001588 // CameraDevice semantics require device to already be idle before
1589 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001590 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001591 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001592 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593 }
1594
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001595 if (mStatus == STATUS_ERROR) {
1596 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1597 __FUNCTION__, mId.string());
1598 return -EBUSY;
1599 }
1600
Igor Murashkin2fba5842013-04-22 14:03:54 -07001601 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001602 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001603 if (mInputStream != NULL && id == mInputStream->getId()) {
1604 deletedStream = mInputStream;
1605 mInputStream.clear();
1606 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001607 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001608 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001609 return BAD_VALUE;
1610 }
Zhijun He5f446352014-01-22 09:49:33 -08001611 }
1612
1613 // Delete output stream or the output part of a bi-directional stream.
1614 if (outputStreamIdx != NAME_NOT_FOUND) {
1615 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001616 mOutputStreams.removeItem(id);
1617 }
1618
1619 // Free up the stream endpoint so that it can be used by some other stream
1620 res = deletedStream->disconnect();
1621 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001622 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001623 // fall through since we want to still list the stream as deleted.
1624 }
1625 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001626 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001627
1628 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001629}
1630
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001631status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001632 ATRACE_CALL();
1633 ALOGV("%s: E", __FUNCTION__);
1634
1635 Mutex::Autolock il(mInterfaceLock);
1636 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001637
Emilian Peev811d2952018-05-25 11:08:40 +01001638 // In case the client doesn't include any session parameter, try a
1639 // speculative configuration using the values from the last cached
1640 // default request.
1641 if (sessionParams.isEmpty() &&
1642 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1643 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1644 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1645 mLastTemplateId);
1646 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1647 operatingMode);
1648 }
1649
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001650 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1651}
1652
1653status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1654 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001655 //Filter out any incoming session parameters
1656 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001657 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1658 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001659 CameraMetadata filteredParams(availableSessionKeys.count);
1660 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1661 filteredParams.getAndLock());
1662 set_camera_metadata_vendor_id(meta, mVendorTagId);
1663 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001664 if (availableSessionKeys.count > 0) {
1665 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1666 camera_metadata_ro_entry entry = params.find(
1667 availableSessionKeys.data.i32[i]);
1668 if (entry.count > 0) {
1669 filteredParams.update(entry);
1670 }
1671 }
1672 }
1673
1674 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001675}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001676
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001677status_t Camera3Device::getInputBufferProducer(
1678 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001679 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001680 Mutex::Autolock il(mInterfaceLock);
1681 Mutex::Autolock l(mLock);
1682
1683 if (producer == NULL) {
1684 return BAD_VALUE;
1685 } else if (mInputStream == NULL) {
1686 return INVALID_OPERATION;
1687 }
1688
1689 return mInputStream->getInputBufferProducer(producer);
1690}
1691
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001692status_t Camera3Device::createDefaultRequest(int templateId,
1693 CameraMetadata *request) {
1694 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001695 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001696
1697 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1698 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1699 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1700 return BAD_VALUE;
1701 }
1702
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001703 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001704
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001705 {
1706 Mutex::Autolock l(mLock);
1707 switch (mStatus) {
1708 case STATUS_ERROR:
1709 CLOGE("Device has encountered a serious error");
1710 return INVALID_OPERATION;
1711 case STATUS_UNINITIALIZED:
1712 CLOGE("Device is not initialized!");
1713 return INVALID_OPERATION;
1714 case STATUS_UNCONFIGURED:
1715 case STATUS_CONFIGURED:
1716 case STATUS_ACTIVE:
1717 // OK
1718 break;
1719 default:
1720 SET_ERR_L("Unexpected status: %d", mStatus);
1721 return INVALID_OPERATION;
1722 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001723
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001724 if (!mRequestTemplateCache[templateId].isEmpty()) {
1725 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001726 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001727 return OK;
1728 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001729 }
1730
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001731 camera_metadata_t *rawRequest;
1732 status_t res = mInterface->constructDefaultRequestSettings(
1733 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001734
1735 {
1736 Mutex::Autolock l(mLock);
1737 if (res == BAD_VALUE) {
1738 ALOGI("%s: template %d is not supported on this camera device",
1739 __FUNCTION__, templateId);
1740 return res;
1741 } else if (res != OK) {
1742 CLOGE("Unable to construct request template %d: %s (%d)",
1743 templateId, strerror(-res), res);
1744 return res;
1745 }
1746
1747 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1748 mRequestTemplateCache[templateId].acquire(rawRequest);
1749
1750 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001751 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001752 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001753 return OK;
1754}
1755
1756status_t Camera3Device::waitUntilDrained() {
1757 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001758 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001759 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001760 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001761
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001762 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001763}
1764
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001765status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001766 switch (mStatus) {
1767 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001768 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001769 ALOGV("%s: Already idle", __FUNCTION__);
1770 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001771 case STATUS_CONFIGURED:
1772 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001773 case STATUS_ERROR:
1774 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001775 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001776 break;
1777 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001778 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001779 return INVALID_OPERATION;
1780 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001781 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1782 maxExpectedDuration);
1783 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001784 if (res != OK) {
1785 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1786 res);
1787 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001788 return res;
1789}
1790
Ruben Brunk183f0562015-08-12 12:55:02 -07001791
1792void Camera3Device::internalUpdateStatusLocked(Status status) {
1793 mStatus = status;
1794 mRecentStatusUpdates.add(mStatus);
1795 mStatusChanged.broadcast();
1796}
1797
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001798void Camera3Device::pauseStateNotify(bool enable) {
1799 Mutex::Autolock il(mInterfaceLock);
1800 Mutex::Autolock l(mLock);
1801
1802 mPauseStateNotify = enable;
1803}
1804
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001805// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001806status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001807 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001808
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001809 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1810 maxExpectedDuration);
1811 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001812 if (res != OK) {
1813 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001814 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001815 }
1816
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001817 return res;
1818}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001819
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001820// Resume after internalPauseAndWaitLocked
1821status_t Camera3Device::internalResumeLocked() {
1822 status_t res;
1823
1824 mRequestThread->setPaused(false);
1825
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001826 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1827 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001828 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1829 if (res != OK) {
1830 SET_ERR_L("Can't transition to active in %f seconds!",
1831 kActiveTimeout/1e9);
1832 }
1833 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001834 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001835}
1836
Ruben Brunk183f0562015-08-12 12:55:02 -07001837status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001838 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001839
1840 size_t startIndex = 0;
1841 if (mStatusWaiters == 0) {
1842 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1843 // this status list
1844 mRecentStatusUpdates.clear();
1845 } else {
1846 // If other threads are waiting on updates to this status list, set the position of the
1847 // first element that this list will check rather than clearing the list.
1848 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001849 }
1850
Ruben Brunk183f0562015-08-12 12:55:02 -07001851 mStatusWaiters++;
1852
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001853 bool stateSeen = false;
1854 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001855 if (active == (mStatus == STATUS_ACTIVE)) {
1856 // Desired state is current
1857 break;
1858 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001859
1860 res = mStatusChanged.waitRelative(mLock, timeout);
1861 if (res != OK) break;
1862
Ruben Brunk183f0562015-08-12 12:55:02 -07001863 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1864 // transitions.
1865 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1866 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1867 __FUNCTION__);
1868
1869 // Encountered desired state since we began waiting
1870 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001871 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1872 stateSeen = true;
1873 break;
1874 }
1875 }
1876 } while (!stateSeen);
1877
Ruben Brunk183f0562015-08-12 12:55:02 -07001878 mStatusWaiters--;
1879
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001880 return res;
1881}
1882
1883
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001884status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001885 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001886 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001887
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001888 if (listener != NULL && mListener != NULL) {
1889 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1890 }
1891 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001892 mRequestThread->setNotificationListener(listener);
1893 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001894
1895 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001896}
1897
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001898bool Camera3Device::willNotify3A() {
1899 return false;
1900}
1901
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001902status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001903 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001904 status_t res;
1905 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001906
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001907 while (mResultQueue.empty()) {
1908 res = mResultSignal.waitRelative(mOutputLock, timeout);
1909 if (res == TIMED_OUT) {
1910 return res;
1911 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001912 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1913 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001914 return res;
1915 }
1916 }
1917 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001918}
1919
Jianing Weicb0652e2014-03-12 18:29:36 -07001920status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001921 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001922 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001923
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001924 if (mResultQueue.empty()) {
1925 return NOT_ENOUGH_DATA;
1926 }
1927
Jianing Weicb0652e2014-03-12 18:29:36 -07001928 if (frame == NULL) {
1929 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1930 return BAD_VALUE;
1931 }
1932
1933 CaptureResult &result = *(mResultQueue.begin());
1934 frame->mResultExtras = result.mResultExtras;
1935 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001936 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001937 mResultQueue.erase(mResultQueue.begin());
1938
1939 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001940}
1941
1942status_t Camera3Device::triggerAutofocus(uint32_t id) {
1943 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001944 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001945
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001946 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1947 // Mix-in this trigger into the next request and only the next request.
1948 RequestTrigger trigger[] = {
1949 {
1950 ANDROID_CONTROL_AF_TRIGGER,
1951 ANDROID_CONTROL_AF_TRIGGER_START
1952 },
1953 {
1954 ANDROID_CONTROL_AF_TRIGGER_ID,
1955 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001956 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001957 };
1958
1959 return mRequestThread->queueTrigger(trigger,
1960 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001961}
1962
1963status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1964 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001965 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001966
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001967 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1968 // Mix-in this trigger into the next request and only the next request.
1969 RequestTrigger trigger[] = {
1970 {
1971 ANDROID_CONTROL_AF_TRIGGER,
1972 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1973 },
1974 {
1975 ANDROID_CONTROL_AF_TRIGGER_ID,
1976 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001977 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001978 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001979
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001980 return mRequestThread->queueTrigger(trigger,
1981 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001982}
1983
1984status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1985 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001986 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001987
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001988 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1989 // Mix-in this trigger into the next request and only the next request.
1990 RequestTrigger trigger[] = {
1991 {
1992 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1993 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1994 },
1995 {
1996 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1997 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001998 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001999 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002000
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002001 return mRequestThread->queueTrigger(trigger,
2002 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002003}
2004
Jianing Weicb0652e2014-03-12 18:29:36 -07002005status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002006 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002007 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002008 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002009
Zhijun He7ef20392014-04-21 16:04:17 -07002010 {
2011 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002012 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002013 }
2014
Emilian Peev08dd2452017-04-06 16:55:14 +01002015 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002016}
2017
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002018status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002019 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2020}
2021
2022status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002023 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002024 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002025 Mutex::Autolock il(mInterfaceLock);
2026 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002027
2028 sp<Camera3StreamInterface> stream;
2029 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2030 if (outputStreamIdx == NAME_NOT_FOUND) {
2031 CLOGE("Stream %d does not exist", streamId);
2032 return BAD_VALUE;
2033 }
2034
2035 stream = mOutputStreams.editValueAt(outputStreamIdx);
2036
2037 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002038 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002039 return BAD_VALUE;
2040 }
2041
2042 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002043 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002044 return BAD_VALUE;
2045 }
2046
Ruben Brunkc78ac262015-08-13 17:58:46 -07002047 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002048}
2049
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002050status_t Camera3Device::tearDown(int streamId) {
2051 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002052 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002053 Mutex::Autolock il(mInterfaceLock);
2054 Mutex::Autolock l(mLock);
2055
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002056 sp<Camera3StreamInterface> stream;
2057 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2058 if (outputStreamIdx == NAME_NOT_FOUND) {
2059 CLOGE("Stream %d does not exist", streamId);
2060 return BAD_VALUE;
2061 }
2062
2063 stream = mOutputStreams.editValueAt(outputStreamIdx);
2064
2065 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2066 CLOGE("Stream %d is a target of a in-progress request", streamId);
2067 return BAD_VALUE;
2068 }
2069
2070 return stream->tearDown();
2071}
2072
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002073status_t Camera3Device::addBufferListenerForStream(int streamId,
2074 wp<Camera3StreamBufferListener> listener) {
2075 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002076 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002077 Mutex::Autolock il(mInterfaceLock);
2078 Mutex::Autolock l(mLock);
2079
2080 sp<Camera3StreamInterface> stream;
2081 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2082 if (outputStreamIdx == NAME_NOT_FOUND) {
2083 CLOGE("Stream %d does not exist", streamId);
2084 return BAD_VALUE;
2085 }
2086
2087 stream = mOutputStreams.editValueAt(outputStreamIdx);
2088 stream->addBufferListener(listener);
2089
2090 return OK;
2091}
2092
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002093/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002094 * Methods called by subclasses
2095 */
2096
2097void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002098 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002099 {
2100 // Need mLock to safely update state and synchronize to current
2101 // state of methods in flight.
2102 Mutex::Autolock l(mLock);
2103 // We can get various system-idle notices from the status tracker
2104 // while starting up. Only care about them if we've actually sent
2105 // in some requests recently.
2106 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2107 return;
2108 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002109 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2110 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002111 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002112
2113 // Skip notifying listener if we're doing some user-transparent
2114 // state changes
2115 if (mPauseStateNotify) return;
2116 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002117
2118 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002119 {
2120 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002121 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002122 }
2123 if (idle && listener != NULL) {
2124 listener->notifyIdle();
2125 }
2126}
2127
Shuzhen Wang758c2152017-01-10 18:26:18 -08002128status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002129 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002130 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002131 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2132 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002133
2134 if (surfaceIds == nullptr) {
2135 return BAD_VALUE;
2136 }
2137
Zhijun He5d677d12016-05-29 16:52:39 -07002138 Mutex::Autolock il(mInterfaceLock);
2139 Mutex::Autolock l(mLock);
2140
Shuzhen Wang758c2152017-01-10 18:26:18 -08002141 if (consumers.size() == 0) {
2142 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002143 return BAD_VALUE;
2144 }
2145
2146 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2147 if (idx == NAME_NOT_FOUND) {
2148 CLOGE("Stream %d is unknown", streamId);
2149 return idx;
2150 }
2151 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002152 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002153 if (res != OK) {
2154 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2155 return res;
2156 }
2157
Emilian Peev40ead602017-09-26 15:46:36 +01002158 for (auto &consumer : consumers) {
2159 int id = stream->getSurfaceId(consumer);
2160 if (id < 0) {
2161 CLOGE("Invalid surface id!");
2162 return BAD_VALUE;
2163 }
2164 surfaceIds->push_back(id);
2165 }
2166
Shuzhen Wang0129d522016-10-30 22:43:41 -07002167 if (stream->isConsumerConfigurationDeferred()) {
2168 if (!stream->isConfiguring()) {
2169 CLOGE("Stream %d was already fully configured.", streamId);
2170 return INVALID_OPERATION;
2171 }
Zhijun He5d677d12016-05-29 16:52:39 -07002172
Shuzhen Wang0129d522016-10-30 22:43:41 -07002173 res = stream->finishConfiguration();
2174 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002175 // If finishConfiguration fails due to abandoned surface, do not set
2176 // device to error state.
2177 bool isSurfaceAbandoned =
2178 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2179 if (!isSurfaceAbandoned) {
2180 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2181 stream->getId(), strerror(-res), res);
2182 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002183 return res;
2184 }
Zhijun He5d677d12016-05-29 16:52:39 -07002185 }
2186
2187 return OK;
2188}
2189
Emilian Peev40ead602017-09-26 15:46:36 +01002190status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2191 const std::vector<OutputStreamInfo> &outputInfo,
2192 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2193 Mutex::Autolock il(mInterfaceLock);
2194 Mutex::Autolock l(mLock);
2195
2196 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2197 if (idx == NAME_NOT_FOUND) {
2198 CLOGE("Stream %d is unknown", streamId);
2199 return idx;
2200 }
2201
2202 for (const auto &it : removedSurfaceIds) {
2203 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2204 CLOGE("Shared surface still part of a pending request!");
2205 return -EBUSY;
2206 }
2207 }
2208
2209 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2210 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2211 if (res != OK) {
2212 CLOGE("Stream %d failed to update stream (error %d %s) ",
2213 streamId, res, strerror(-res));
2214 if (res == UNKNOWN_ERROR) {
2215 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2216 __FUNCTION__);
2217 }
2218 return res;
2219 }
2220
2221 return res;
2222}
2223
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002224status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2225 Mutex::Autolock il(mInterfaceLock);
2226 Mutex::Autolock l(mLock);
2227
2228 int idx = mOutputStreams.indexOfKey(streamId);
2229 if (idx == NAME_NOT_FOUND) {
2230 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2231 return BAD_VALUE;
2232 }
2233
2234 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2235 return stream->dropBuffers(dropping);
2236}
2237
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002238/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002239 * Camera3Device private methods
2240 */
2241
2242sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002243 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002244 ATRACE_CALL();
2245 status_t res;
2246
2247 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002248 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002249
2250 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002251 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002252 if (inputStreams.count > 0) {
2253 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002254 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002255 CLOGE("Request references unknown input stream %d",
2256 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002257 return NULL;
2258 }
2259 // Lazy completion of stream configuration (allocation/registration)
2260 // on first use
2261 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002262 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002263 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002264 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002265 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002266 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002267 return NULL;
2268 }
2269 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002270 // Check if stream prepare is blocking requests.
2271 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002272 CLOGE("Request references an input stream that's being prepared!");
2273 return NULL;
2274 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002275
2276 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002277 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002278 }
2279
2280 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002281 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002282 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002283 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002284 return NULL;
2285 }
2286
2287 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002288 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002289 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002290 CLOGE("Request references unknown stream %d",
2291 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002292 return NULL;
2293 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002294 sp<Camera3OutputStreamInterface> stream =
2295 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002296
Zhijun He5d677d12016-05-29 16:52:39 -07002297 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002298 auto iter = surfaceMap.find(streams.data.i32[i]);
2299 if (iter != surfaceMap.end()) {
2300 const std::vector<size_t>& surfaces = iter->second;
2301 for (const auto& surface : surfaces) {
2302 if (stream->isConsumerConfigurationDeferred(surface)) {
2303 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2304 "due to deferred consumer", stream->getId(), surface);
2305 return NULL;
2306 }
2307 }
2308 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002309 }
2310
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002311 // Lazy completion of stream configuration (allocation/registration)
2312 // on first use
2313 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002314 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002315 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002316 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2317 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002318 return NULL;
2319 }
2320 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002321 // Check if stream prepare is blocking requests.
2322 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002323 CLOGE("Request references an output stream that's being prepared!");
2324 return NULL;
2325 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002326
2327 newRequest->mOutputStreams.push(stream);
2328 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002329 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002330 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002331
2332 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002333}
2334
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002335bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2336 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2337 Size size = mSupportedOpaqueInputSizes[i];
2338 if (size.width == width && size.height == height) {
2339 return true;
2340 }
2341 }
2342
2343 return false;
2344}
2345
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002346void Camera3Device::cancelStreamsConfigurationLocked() {
2347 int res = OK;
2348 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2349 res = mInputStream->cancelConfiguration();
2350 if (res != OK) {
2351 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2352 mInputStream->getId(), strerror(-res), res);
2353 }
2354 }
2355
2356 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2357 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2358 if (outputStream->isConfiguring()) {
2359 res = outputStream->cancelConfiguration();
2360 if (res != OK) {
2361 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2362 outputStream->getId(), strerror(-res), res);
2363 }
2364 }
2365 }
2366
2367 // Return state to that at start of call, so that future configures
2368 // properly clean things up
2369 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2370 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002371
2372 res = mPreparerThread->resume();
2373 if (res != OK) {
2374 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2375 }
2376}
2377
2378bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2379 ATRACE_CALL();
2380 bool ret = false;
2381
2382 Mutex::Autolock il(mInterfaceLock);
2383 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2384
2385 Mutex::Autolock l(mLock);
2386 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2387 if (rc == NO_ERROR) {
2388 mNeedConfig = true;
2389 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2390 if (rc == NO_ERROR) {
2391 ret = true;
2392 mPauseStateNotify = false;
2393 //Moving to active state while holding 'mLock' is important.
2394 //There could be pending calls to 'create-/deleteStream' which
2395 //will trigger another stream configuration while the already
2396 //present streams end up with outstanding buffers that will
2397 //not get drained.
2398 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002399 } else if (rc == DEAD_OBJECT) {
2400 // DEAD_OBJECT can be returned if either the consumer surface is
2401 // abandoned, or the HAL has died.
2402 // - If the HAL has died, configureStreamsLocked call will set
2403 // device to error state,
2404 // - If surface is abandoned, we should not set device to error
2405 // state.
2406 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002407 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002408 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002409 }
2410 } else {
2411 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2412 }
2413
2414 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002415}
2416
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002417status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002418 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002419 ATRACE_CALL();
2420 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002421
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002422 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002423 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002424 return INVALID_OPERATION;
2425 }
2426
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002427 if (operatingMode < 0) {
2428 CLOGE("Invalid operating mode: %d", operatingMode);
2429 return BAD_VALUE;
2430 }
2431
2432 bool isConstrainedHighSpeed =
2433 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2434 operatingMode;
2435
2436 if (mOperatingMode != operatingMode) {
2437 mNeedConfig = true;
2438 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2439 mOperatingMode = operatingMode;
2440 }
2441
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002442 if (!mNeedConfig) {
2443 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2444 return OK;
2445 }
2446
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002447 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2448 // adding a dummy stream instead.
2449 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2450 if (mOutputStreams.size() == 0) {
2451 addDummyStreamLocked();
2452 } else {
2453 tryRemoveDummyStreamLocked();
2454 }
2455
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002456 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002457 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002458
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002459 mPreparerThread->pause();
2460
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002461 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002462 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002463 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2464
2465 Vector<camera3_stream_t*> streams;
2466 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002467 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002468
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002469
2470 if (mInputStream != NULL) {
2471 camera3_stream_t *inputStream;
2472 inputStream = mInputStream->startConfiguration();
2473 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002474 CLOGE("Can't start input stream configuration");
2475 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002476 return INVALID_OPERATION;
2477 }
2478 streams.add(inputStream);
2479 }
2480
2481 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002482
2483 // Don't configure bidi streams twice, nor add them twice to the list
2484 if (mOutputStreams[i].get() ==
2485 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2486
2487 config.num_streams--;
2488 continue;
2489 }
2490
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002491 camera3_stream_t *outputStream;
2492 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2493 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002494 CLOGE("Can't start output stream configuration");
2495 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002496 return INVALID_OPERATION;
2497 }
2498 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002499
2500 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2501 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002502 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2503 // always occupy the initial entry.
2504 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002505 getJpegBufferSize(outputStream->width, outputStream->height));
2506 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002507 }
2508
2509 config.streams = streams.editArray();
2510
2511 // Do the HAL configuration; will potentially touch stream
2512 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002513
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002514 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002515 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002516 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002517
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002518 if (res == BAD_VALUE) {
2519 // HAL rejected this set of streams as unsupported, clean up config
2520 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002521 CLOGE("Set of requested inputs/outputs not supported by HAL");
2522 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002523 return BAD_VALUE;
2524 } else if (res != OK) {
2525 // Some other kind of error from configure_streams - this is not
2526 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002527 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2528 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002529 return res;
2530 }
2531
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002532 // Finish all stream configuration immediately.
2533 // TODO: Try to relax this later back to lazy completion, which should be
2534 // faster
2535
Igor Murashkin073f8572013-05-02 14:59:28 -07002536 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002537 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002538 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002539 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002540 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002541 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002542 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2543 return DEAD_OBJECT;
2544 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002545 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002546 }
2547 }
2548
2549 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002550 sp<Camera3OutputStreamInterface> outputStream =
2551 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002552 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002553 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002554 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002555 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002556 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002557 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002558 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2559 return DEAD_OBJECT;
2560 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002561 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002562 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002563 }
2564 }
2565
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002566 // Request thread needs to know to avoid using repeat-last-settings protocol
2567 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002568 if (notifyRequestThread) {
2569 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2570 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002571
Zhijun He90f7c372016-08-16 16:19:43 -07002572 char value[PROPERTY_VALUE_MAX];
2573 property_get("camera.fifo.disable", value, "0");
2574 int32_t disableFifo = atoi(value);
2575 if (disableFifo != 1) {
2576 // Boost priority of request thread to SCHED_FIFO.
2577 pid_t requestThreadTid = mRequestThread->getTid();
2578 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002579 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002580 if (res != OK) {
2581 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2582 strerror(-res), res);
2583 } else {
2584 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2585 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002586 }
2587
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002588 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002589 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2590 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2591 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2592 sessionParams.unlock(newSessionParams);
2593 mSessionParams.unlock(currentSessionParams);
2594 if (updateSessionParams) {
2595 mSessionParams = sessionParams;
2596 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002597
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002598 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002599
Ruben Brunk183f0562015-08-12 12:55:02 -07002600 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2601 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002602
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002603 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002604
Zhijun He0a210512014-07-24 13:45:15 -07002605 // tear down the deleted streams after configure streams.
2606 mDeletedStreams.clear();
2607
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002608 auto rc = mPreparerThread->resume();
2609 if (rc != OK) {
2610 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2611 return rc;
2612 }
2613
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002614 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002615}
2616
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002617status_t Camera3Device::addDummyStreamLocked() {
2618 ATRACE_CALL();
2619 status_t res;
2620
2621 if (mDummyStreamId != NO_STREAM) {
2622 // Should never be adding a second dummy stream when one is already
2623 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002624 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2625 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002626 return INVALID_OPERATION;
2627 }
2628
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002629 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002630
2631 sp<Camera3OutputStreamInterface> dummyStream =
2632 new Camera3DummyStream(mNextStreamId);
2633
2634 res = mOutputStreams.add(mNextStreamId, dummyStream);
2635 if (res < 0) {
2636 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2637 return res;
2638 }
2639
2640 mDummyStreamId = mNextStreamId;
2641 mNextStreamId++;
2642
2643 return OK;
2644}
2645
2646status_t Camera3Device::tryRemoveDummyStreamLocked() {
2647 ATRACE_CALL();
2648 status_t res;
2649
2650 if (mDummyStreamId == NO_STREAM) return OK;
2651 if (mOutputStreams.size() == 1) return OK;
2652
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002653 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002654
2655 // Ok, have a dummy stream and there's at least one other output stream,
2656 // so remove the dummy
2657
2658 sp<Camera3StreamInterface> deletedStream;
2659 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2660 if (outputStreamIdx == NAME_NOT_FOUND) {
2661 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2662 return INVALID_OPERATION;
2663 }
2664
2665 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2666 mOutputStreams.removeItemsAt(outputStreamIdx);
2667
2668 // Free up the stream endpoint so that it can be used by some other stream
2669 res = deletedStream->disconnect();
2670 if (res != OK) {
2671 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2672 // fall through since we want to still list the stream as deleted.
2673 }
2674 mDeletedStreams.add(deletedStream);
2675 mDummyStreamId = NO_STREAM;
2676
2677 return res;
2678}
2679
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002680void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002681 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002682 Mutex::Autolock l(mLock);
2683 va_list args;
2684 va_start(args, fmt);
2685
2686 setErrorStateLockedV(fmt, args);
2687
2688 va_end(args);
2689}
2690
2691void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002692 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002693 Mutex::Autolock l(mLock);
2694 setErrorStateLockedV(fmt, args);
2695}
2696
2697void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2698 va_list args;
2699 va_start(args, fmt);
2700
2701 setErrorStateLockedV(fmt, args);
2702
2703 va_end(args);
2704}
2705
2706void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002707 // Print out all error messages to log
2708 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002709 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002710
2711 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002712 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002713
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002714 mErrorCause = errorCause;
2715
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002716 if (mRequestThread != nullptr) {
2717 mRequestThread->setPaused(true);
2718 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002719 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002720
2721 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002722 sp<NotificationListener> listener = mListener.promote();
2723 if (listener != NULL) {
2724 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002725 CaptureResultExtras());
2726 }
2727
2728 // Save stack trace. View by dumping it later.
2729 CameraTraces::saveTrace();
2730 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002731}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002732
2733/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002734 * In-flight request management
2735 */
2736
Jianing Weicb0652e2014-03-12 18:29:36 -07002737status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002738 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002739 bool hasAppCallback, nsecs_t maxExpectedDuration,
2740 std::set<String8>& physicalCameraIds) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002741 ATRACE_CALL();
2742 Mutex::Autolock l(mInFlightLock);
2743
2744 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002745 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002746 hasAppCallback, maxExpectedDuration, physicalCameraIds));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002747 if (res < 0) return res;
2748
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002749 if (mInFlightMap.size() == 1) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002750 // hold mLock to prevent race with disconnect
2751 Mutex::Autolock l(mLock);
2752 if (mStatusTracker != nullptr) {
2753 mStatusTracker->markComponentActive(mInFlightStatusId);
2754 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002755 }
2756
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002757 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002758 return OK;
2759}
2760
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002761void Camera3Device::returnOutputBuffers(
2762 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2763 nsecs_t timestamp) {
2764 for (size_t i = 0; i < numBuffers; i++)
2765 {
2766 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2767 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2768 // Note: stream may be deallocated at this point, if this buffer was
2769 // the last reference to it.
2770 if (res != OK) {
2771 ALOGE("Can't return buffer to its stream: %s (%d)",
2772 strerror(-res), res);
2773 }
2774 }
2775}
2776
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002777void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002778 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002779 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002780 mInFlightMap.removeItemsAt(idx, 1);
2781
2782 // Indicate idle inFlightMap to the status tracker
2783 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002784 // hold mLock to prevent race with disconnect
2785 Mutex::Autolock l(mLock);
2786 if (mStatusTracker != nullptr) {
2787 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2788 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002789 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002790 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002791}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002792
2793void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2794
2795 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2796 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2797
2798 nsecs_t sensorTimestamp = request.sensorTimestamp;
2799 nsecs_t shutterTimestamp = request.shutterTimestamp;
2800
2801 // Check if it's okay to remove the request from InFlightMap:
2802 // In the case of a successful request:
2803 // all input and output buffers, all result metadata, shutter callback
2804 // arrived.
2805 // In the case of a unsuccessful request:
2806 // all input and output buffers arrived.
2807 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002808 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002809 (request.haveResultMetadata && shutterTimestamp != 0))) {
2810 ATRACE_ASYNC_END("frame capture", frameNumber);
2811
Shuzhen Wang403044a2017-02-26 23:29:04 -08002812 // Sanity check - if sensor timestamp matches shutter timestamp in the
2813 // case of request having callback.
2814 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002815 sensorTimestamp != shutterTimestamp) {
2816 SET_ERR("sensor timestamp (%" PRId64
2817 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2818 sensorTimestamp, frameNumber, shutterTimestamp);
2819 }
2820
2821 // for an unsuccessful request, it may have pending output buffers to
2822 // return.
2823 assert(request.requestStatus != OK ||
2824 request.pendingOutputBuffers.size() == 0);
2825 returnOutputBuffers(request.pendingOutputBuffers.array(),
2826 request.pendingOutputBuffers.size(), 0);
2827
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002828 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002829 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2830 }
2831
2832 // Sanity check - if we have too many in-flight frames, something has
2833 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002834 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002835 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002836 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2837 kInFlightWarnLimitHighSpeed) {
2838 CLOGE("In-flight list too large for high speed configuration: %zu",
2839 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002840 }
2841}
2842
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002843void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002844 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002845 { // First return buffers cached in mInFlightMap
2846 Mutex::Autolock l(mInFlightLock);
2847 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2848 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2849 returnOutputBuffers(request.pendingOutputBuffers.array(),
2850 request.pendingOutputBuffers.size(), 0);
2851 }
2852 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002853 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002854 }
2855
2856 // Then return all inflight buffers not returned by HAL
2857 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2858 mInterface->getInflightBufferKeys(&inflightKeys);
2859
2860 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2861 for (auto& pair : inflightKeys) {
2862 int32_t frameNumber = pair.first;
2863 int32_t streamId = pair.second;
2864 buffer_handle_t* buffer;
2865 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2866 if (res != OK) {
2867 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2868 __FUNCTION__, frameNumber, streamId);
2869 continue;
2870 }
2871
2872 camera3_stream_buffer_t streamBuffer;
2873 streamBuffer.buffer = buffer;
2874 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2875 streamBuffer.acquire_fence = -1;
2876 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002877
2878 // First check if the buffer belongs to deleted stream
2879 bool streamDeleted = false;
2880 for (auto& stream : mDeletedStreams) {
2881 if (streamId == stream->getId()) {
2882 streamDeleted = true;
2883 // Return buffer to deleted stream
2884 camera3_stream* halStream = stream->asHalStream();
2885 streamBuffer.stream = halStream;
2886 switch (halStream->stream_type) {
2887 case CAMERA3_STREAM_OUTPUT:
2888 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2889 if (res != OK) {
2890 ALOGE("%s: Can't return output buffer for frame %d to"
2891 " stream %d: %s (%d)", __FUNCTION__,
2892 frameNumber, streamId, strerror(-res), res);
2893 }
2894 break;
2895 case CAMERA3_STREAM_INPUT:
2896 res = stream->returnInputBuffer(streamBuffer);
2897 if (res != OK) {
2898 ALOGE("%s: Can't return input buffer for frame %d to"
2899 " stream %d: %s (%d)", __FUNCTION__,
2900 frameNumber, streamId, strerror(-res), res);
2901 }
2902 break;
2903 default: // Bi-direcitonal stream is deprecated
2904 ALOGE("%s: stream %d has unknown stream type %d",
2905 __FUNCTION__, streamId, halStream->stream_type);
2906 break;
2907 }
2908 break;
2909 }
2910 }
2911 if (streamDeleted) {
2912 continue;
2913 }
2914
2915 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002916 if (streamId == inputStreamId) {
2917 streamBuffer.stream = mInputStream->asHalStream();
2918 res = mInputStream->returnInputBuffer(streamBuffer);
2919 if (res != OK) {
2920 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002921 " stream %d: %s (%d)", __FUNCTION__,
2922 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002923 }
2924 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002925 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2926 if (idx == NAME_NOT_FOUND) {
2927 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2928 continue;
2929 }
2930 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002931 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2932 }
2933 }
2934}
2935
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002936void Camera3Device::insertResultLocked(CaptureResult *result,
2937 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002938 if (result == nullptr) return;
2939
Emilian Peev71c73a22017-03-21 16:35:51 +00002940 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2941 result->mMetadata.getAndLock());
2942 set_camera_metadata_vendor_id(meta, mVendorTagId);
2943 result->mMetadata.unlock(meta);
2944
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002945 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2946 (int32_t*)&frameNumber, 1) != OK) {
2947 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2948 return;
2949 }
2950
2951 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2952 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2953 return;
2954 }
2955
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002956 // Valid result, insert into queue
2957 List<CaptureResult>::iterator queuedResult =
2958 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2959 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2960 ", burstId = %" PRId32, __FUNCTION__,
2961 queuedResult->mResultExtras.requestId,
2962 queuedResult->mResultExtras.frameNumber,
2963 queuedResult->mResultExtras.burstId);
2964
2965 mResultSignal.signal();
2966}
2967
2968
2969void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002970 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002971 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002972 Mutex::Autolock l(mOutputLock);
2973
2974 CaptureResult captureResult;
2975 captureResult.mResultExtras = resultExtras;
2976 captureResult.mMetadata = partialResult;
2977
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002978 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002979}
2980
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002981
2982void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2983 CaptureResultExtras &resultExtras,
2984 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002985 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002986 bool reprocess,
2987 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002988 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002989 if (pendingMetadata.isEmpty())
2990 return;
2991
2992 Mutex::Autolock l(mOutputLock);
2993
2994 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002995 if (reprocess) {
2996 if (frameNumber < mNextReprocessResultFrameNumber) {
2997 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002998 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002999 frameNumber, mNextReprocessResultFrameNumber);
3000 return;
3001 }
3002 mNextReprocessResultFrameNumber = frameNumber + 1;
3003 } else {
3004 if (frameNumber < mNextResultFrameNumber) {
3005 SET_ERR("Out-of-order capture result metadata submitted! "
3006 "(got frame number %d, expecting %d)",
3007 frameNumber, mNextResultFrameNumber);
3008 return;
3009 }
3010 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003011 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003012
3013 CaptureResult captureResult;
3014 captureResult.mResultExtras = resultExtras;
3015 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003016 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003017
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003018 // Append any previous partials to form a complete result
3019 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3020 captureResult.mMetadata.append(collectedPartialResult);
3021 }
3022
3023 captureResult.mMetadata.sort();
3024
3025 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003026 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3027 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003028 SET_ERR("No timestamp provided by HAL for frame %d!",
3029 frameNumber);
3030 return;
3031 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003032 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3033 camera_metadata_entry timestamp =
3034 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3035 if (timestamp.count == 0) {
3036 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3037 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3038 return;
3039 }
3040 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003041
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003042 // Fix up some result metadata to account for HAL-level distortion correction
3043 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3044 if (res != OK) {
3045 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3046 frameNumber, strerror(res), res);
3047 return;
3048 }
3049
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003050 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3051 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3052
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003053 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003054}
3055
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003056/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003057 * Camera HAL device callback methods
3058 */
3059
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003060void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003061 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003062
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003063 status_t res;
3064
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003065 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003066 if (result->result == NULL && result->num_output_buffers == 0 &&
3067 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003068 SET_ERR("No result data provided by HAL for frame %d",
3069 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003070 return;
3071 }
Zhijun He204e3292014-07-14 17:09:23 -07003072
Zhijun He204e3292014-07-14 17:09:23 -07003073 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003074 result->result != NULL &&
3075 result->partial_result != 1) {
3076 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3077 " if partial result is not supported",
3078 frameNumber, result->partial_result);
3079 return;
3080 }
3081
3082 bool isPartialResult = false;
3083 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003084 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003085
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003086 // Get shutter timestamp and resultExtras from list of in-flight requests,
3087 // where it was added by the shutter notification for this frame. If the
3088 // shutter timestamp isn't received yet, append the output buffers to the
3089 // in-flight request and they will be returned when the shutter timestamp
3090 // arrives. Update the in-flight status and remove the in-flight entry if
3091 // all result data and shutter timestamp have been received.
3092 nsecs_t shutterTimestamp = 0;
3093
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003094 {
3095 Mutex::Autolock l(mInFlightLock);
3096 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3097 if (idx == NAME_NOT_FOUND) {
3098 SET_ERR("Unknown frame number for capture result: %d",
3099 frameNumber);
3100 return;
3101 }
3102 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003103 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3104 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003105 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003106 __FUNCTION__, request.resultExtras.requestId,
3107 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003108 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003109 // Always update the partial count to the latest one if it's not 0
3110 // (buffers only). When framework aggregates adjacent partial results
3111 // into one, the latest partial count will be used.
3112 if (result->partial_result != 0)
3113 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003114
3115 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003116 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003117 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3118 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3119 " the range of [1, %d] when metadata is included in the result",
3120 frameNumber, result->partial_result, mNumPartialResults);
3121 return;
3122 }
3123 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003124 if (isPartialResult && result->num_physcam_metadata) {
3125 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3126 " physical camera result", frameNumber);
3127 return;
3128 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003129 if (isPartialResult) {
3130 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003131 }
3132
Shuzhen Wang4a472662017-02-26 23:29:04 -08003133 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003134 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003135 sendPartialCaptureResult(result->result, request.resultExtras,
3136 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003137 }
3138 }
3139
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003140 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003141 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003142
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003143 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003144 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003145 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3146 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3147 request.physicalCameraIds.size(), result->num_physcam_metadata);
3148 return;
3149 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003150 if (request.haveResultMetadata) {
3151 SET_ERR("Called multiple times with metadata for frame %d",
3152 frameNumber);
3153 return;
3154 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003155 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3156 String8 physicalId(result->physcam_ids[i]);
3157 std::set<String8>::iterator cameraIdIter =
3158 request.physicalCameraIds.find(physicalId);
3159 if (cameraIdIter != request.physicalCameraIds.end()) {
3160 request.physicalCameraIds.erase(cameraIdIter);
3161 } else {
3162 SET_ERR("Total result for frame %d has already returned for camera %s",
3163 frameNumber, physicalId.c_str());
3164 return;
3165 }
3166 }
Zhijun He204e3292014-07-14 17:09:23 -07003167 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003168 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003169 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003170 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003171 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003172 request.haveResultMetadata = true;
3173 }
3174
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003175 uint32_t numBuffersReturned = result->num_output_buffers;
3176 if (result->input_buffer != NULL) {
3177 if (hasInputBufferInRequest) {
3178 numBuffersReturned += 1;
3179 } else {
3180 ALOGW("%s: Input buffer should be NULL if there is no input"
3181 " buffer sent in the request",
3182 __FUNCTION__);
3183 }
3184 }
3185 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003186 if (request.numBuffersLeft < 0) {
3187 SET_ERR("Too many buffers returned for frame %d",
3188 frameNumber);
3189 return;
3190 }
3191
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003192 camera_metadata_ro_entry_t entry;
3193 res = find_camera_metadata_ro_entry(result->result,
3194 ANDROID_SENSOR_TIMESTAMP, &entry);
3195 if (res == OK && entry.count == 1) {
3196 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003197 }
3198
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003199 // If shutter event isn't received yet, append the output buffers to
3200 // the in-flight request. Otherwise, return the output buffers to
3201 // streams.
3202 if (shutterTimestamp == 0) {
3203 request.pendingOutputBuffers.appendArray(result->output_buffers,
3204 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003205 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003206 returnOutputBuffers(result->output_buffers,
3207 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07003208 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003209
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003210 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003211 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3212 CameraMetadata physicalMetadata;
3213 physicalMetadata.append(result->physcam_metadata[i]);
3214 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3215 physicalMetadata});
3216 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003217 if (shutterTimestamp == 0) {
3218 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003219 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003220 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003221 CameraMetadata metadata;
3222 metadata = result->result;
3223 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003224 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003225 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003226 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003227 }
3228
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003229 removeInFlightRequestIfReadyLocked(idx);
3230 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003231
Zhijun Hef0d962a2014-06-30 10:24:11 -07003232 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003233 if (hasInputBufferInRequest) {
3234 Camera3Stream *stream =
3235 Camera3Stream::cast(result->input_buffer->stream);
3236 res = stream->returnInputBuffer(*(result->input_buffer));
3237 // Note: stream may be deallocated at this point, if this buffer was the
3238 // last reference to it.
3239 if (res != OK) {
3240 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3241 " its stream:%s (%d)", __FUNCTION__,
3242 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003243 }
3244 } else {
3245 ALOGW("%s: Input buffer should be NULL if there is no input"
3246 " buffer sent in the request, skipping input buffer return.",
3247 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003248 }
3249 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003250}
3251
3252void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003253 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003254 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003255 {
3256 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003257 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003258 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003259
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003260 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003261 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003262 return;
3263 }
3264
3265 switch (msg->type) {
3266 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003267 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003268 break;
3269 }
3270 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003271 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003272 break;
3273 }
3274 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003275 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003276 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003277 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003278}
3279
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003280void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003281 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003282 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003283 // Map camera HAL error codes to ICameraDeviceCallback error codes
3284 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003285 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003286 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003287 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003288 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003289 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003290 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003291 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003292 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003293 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003294 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003295 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003296 };
3297
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003298 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003299 ((msg.error_code >= 0) &&
3300 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3301 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003302 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003303
3304 int streamId = 0;
3305 if (msg.error_stream != NULL) {
3306 Camera3Stream *stream =
3307 Camera3Stream::cast(msg.error_stream);
3308 streamId = stream->getId();
3309 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003310 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3311 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003312 streamId, msg.error_code);
3313
3314 CaptureResultExtras resultExtras;
3315 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003316 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003317 // SET_ERR calls notifyError
3318 SET_ERR("Camera HAL reported serious device error");
3319 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003320 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3321 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3322 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003323 {
3324 Mutex::Autolock l(mInFlightLock);
3325 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3326 if (idx >= 0) {
3327 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3328 r.requestStatus = msg.error_code;
3329 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003330 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3331 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3332 errorCode) {
3333 r.skipResultMetadata = true;
3334 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003335 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3336 errorCode) {
3337 // In case of missing result check whether the buffers
3338 // returned. If they returned, then remove inflight
3339 // request.
3340 removeInFlightRequestIfReadyLocked(idx);
3341 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003342 } else {
3343 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003344 ALOGE("Camera %s: %s: cannot find in-flight request on "
3345 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003346 resultExtras.frameNumber);
3347 }
3348 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003349 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003350 if (listener != NULL) {
3351 listener->notifyError(errorCode, resultExtras);
3352 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003353 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003354 }
3355 break;
3356 default:
3357 // SET_ERR calls notifyError
3358 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3359 break;
3360 }
3361}
3362
3363void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003364 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003365 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003366 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003367
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003368 // Set timestamp for the request in the in-flight tracking
3369 // and get the request ID to send upstream
3370 {
3371 Mutex::Autolock l(mInFlightLock);
3372 idx = mInFlightMap.indexOfKey(msg.frame_number);
3373 if (idx >= 0) {
3374 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003375
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003376 // Verify ordering of shutter notifications
3377 {
3378 Mutex::Autolock l(mOutputLock);
3379 // TODO: need to track errors for tighter bounds on expected frame number.
3380 if (r.hasInputBuffer) {
3381 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3382 SET_ERR("Shutter notification out-of-order. Expected "
3383 "notification for frame %d, got frame %d",
3384 mNextReprocessShutterFrameNumber, msg.frame_number);
3385 return;
3386 }
3387 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3388 } else {
3389 if (msg.frame_number < mNextShutterFrameNumber) {
3390 SET_ERR("Shutter notification out-of-order. Expected "
3391 "notification for frame %d, got frame %d",
3392 mNextShutterFrameNumber, msg.frame_number);
3393 return;
3394 }
3395 mNextShutterFrameNumber = msg.frame_number + 1;
3396 }
3397 }
3398
Shuzhen Wang4a472662017-02-26 23:29:04 -08003399 r.shutterTimestamp = msg.timestamp;
3400 if (r.hasCallback) {
3401 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003402 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003403 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003404 // Call listener, if any
3405 if (listener != NULL) {
3406 listener->notifyShutter(r.resultExtras, msg.timestamp);
3407 }
3408 // send pending result and buffers
3409 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3410 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003411 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003412 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003413 returnOutputBuffers(r.pendingOutputBuffers.array(),
3414 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3415 r.pendingOutputBuffers.clear();
3416
3417 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003418 }
3419 }
3420 if (idx < 0) {
3421 SET_ERR("Shutter notification for non-existent frame number %d",
3422 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003423 }
3424}
3425
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003426CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003427 ALOGV("%s", __FUNCTION__);
3428
Igor Murashkin1e479c02013-09-06 16:55:14 -07003429 CameraMetadata retVal;
3430
3431 if (mRequestThread != NULL) {
3432 retVal = mRequestThread->getLatestRequest();
3433 }
3434
Igor Murashkin1e479c02013-09-06 16:55:14 -07003435 return retVal;
3436}
3437
Jianing Weicb0652e2014-03-12 18:29:36 -07003438
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003439void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3440 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3441 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3442}
3443
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003444/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003445 * HalInterface inner class methods
3446 */
3447
Yifan Hongf79b5542017-04-11 14:44:25 -07003448Camera3Device::HalInterface::HalInterface(
3449 sp<ICameraDeviceSession> &session,
3450 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003451 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003452 mRequestMetadataQueue(queue) {
3453 // Check with hardware service manager if we can downcast these interfaces
3454 // Somewhat expensive, so cache the results at startup
3455 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3456 if (castResult_3_4.isOk()) {
3457 mHidlSession_3_4 = castResult_3_4;
3458 }
3459 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3460 if (castResult_3_3.isOk()) {
3461 mHidlSession_3_3 = castResult_3_3;
3462 }
3463}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003464
Emilian Peev31abd0a2017-05-11 18:37:46 +01003465Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003466
3467Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003468 mHidlSession(other.mHidlSession),
3469 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003470
3471bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003472 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003473}
3474
3475void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003476 mHidlSession_3_4.clear();
3477 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003478 mHidlSession.clear();
3479}
3480
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003481bool Camera3Device::HalInterface::supportBatchRequest() {
3482 return mHidlSession != nullptr;
3483}
3484
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003485status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3486 camera3_request_template_t templateId,
3487 /*out*/ camera_metadata_t **requestTemplate) {
3488 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3489 if (!valid()) return INVALID_OPERATION;
3490 status_t res = OK;
3491
Emilian Peev31abd0a2017-05-11 18:37:46 +01003492 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003493
3494 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003495 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003496 status = s;
3497 if (status == common::V1_0::Status::OK) {
3498 const camera_metadata *r =
3499 reinterpret_cast<const camera_metadata_t*>(request.data());
3500 size_t expectedSize = request.size();
3501 int ret = validate_camera_metadata_structure(r, &expectedSize);
3502 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3503 *requestTemplate = clone_camera_metadata(r);
3504 if (*requestTemplate == nullptr) {
3505 ALOGE("%s: Unable to clone camera metadata received from HAL",
3506 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003507 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003508 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003509 } else {
3510 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3511 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003512 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003513 }
3514 };
3515 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003516 RequestTemplate id;
3517 switch (templateId) {
3518 case CAMERA3_TEMPLATE_PREVIEW:
3519 id = RequestTemplate::PREVIEW;
3520 break;
3521 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3522 id = RequestTemplate::STILL_CAPTURE;
3523 break;
3524 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3525 id = RequestTemplate::VIDEO_RECORD;
3526 break;
3527 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3528 id = RequestTemplate::VIDEO_SNAPSHOT;
3529 break;
3530 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3531 id = RequestTemplate::ZERO_SHUTTER_LAG;
3532 break;
3533 case CAMERA3_TEMPLATE_MANUAL:
3534 id = RequestTemplate::MANUAL;
3535 break;
3536 default:
3537 // Unknown template ID, or this HAL is too old to support it
3538 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003539 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003540 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003541
Emilian Peev31abd0a2017-05-11 18:37:46 +01003542 if (!err.isOk()) {
3543 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3544 res = DEAD_OBJECT;
3545 } else {
3546 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003547 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003548
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003549 return res;
3550}
3551
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003552status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003553 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003554 ATRACE_NAME("CameraHal::configureStreams");
3555 if (!valid()) return INVALID_OPERATION;
3556 status_t res = OK;
3557
Emilian Peev31abd0a2017-05-11 18:37:46 +01003558 // Convert stream config to HIDL
3559 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003560 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3561 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3562 requestedConfiguration3_2.streams.resize(config->num_streams);
3563 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003564 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003565 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3566 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003567 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003568
Emilian Peev31abd0a2017-05-11 18:37:46 +01003569 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3570 cam3stream->setBufferFreedListener(this);
3571 int streamId = cam3stream->getId();
3572 StreamType streamType;
3573 switch (src->stream_type) {
3574 case CAMERA3_STREAM_OUTPUT:
3575 streamType = StreamType::OUTPUT;
3576 break;
3577 case CAMERA3_STREAM_INPUT:
3578 streamType = StreamType::INPUT;
3579 break;
3580 default:
3581 ALOGE("%s: Stream %d: Unsupported stream type %d",
3582 __FUNCTION__, streamId, config->streams[i]->stream_type);
3583 return BAD_VALUE;
3584 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003585 dst3_2.id = streamId;
3586 dst3_2.streamType = streamType;
3587 dst3_2.width = src->width;
3588 dst3_2.height = src->height;
3589 dst3_2.format = mapToPixelFormat(src->format);
3590 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3591 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3592 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3593 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003594 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003595 if (src->physical_camera_id != nullptr) {
3596 dst3_4.physicalCameraId = src->physical_camera_id;
3597 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003598
3599 activeStreams.insert(streamId);
3600 // Create Buffer ID map if necessary
3601 if (mBufferIdMaps.count(streamId) == 0) {
3602 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3603 }
3604 }
3605 // remove BufferIdMap for deleted streams
3606 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3607 int streamId = it->first;
3608 bool active = activeStreams.count(streamId) > 0;
3609 if (!active) {
3610 it = mBufferIdMaps.erase(it);
3611 } else {
3612 ++it;
3613 }
3614 }
3615
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003616 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003617 res = mapToStreamConfigurationMode(
3618 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003619 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003620 if (res != OK) {
3621 return res;
3622 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003623 requestedConfiguration3_2.operationMode = operationMode;
3624 requestedConfiguration3_4.operationMode = operationMode;
3625 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003626 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3627 get_camera_metadata_size(sessionParams));
3628
Emilian Peev31abd0a2017-05-11 18:37:46 +01003629 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003630 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003631 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003632
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003633 // See if we have v3.4 or v3.3 HAL
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003634 if (mHidlSession_3_4 != nullptr) {
3635 // We do; use v3.4 for the call
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003636 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003637 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003638 auto err = mHidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003639 [&status, &finalConfiguration3_4]
3640 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3641 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003642 status = s;
3643 });
3644 if (!err.isOk()) {
3645 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3646 return DEAD_OBJECT;
3647 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003648 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3649 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3650 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3651 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003652 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003653 // We do; use v3.3 for the call
3654 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003655 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003656 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003657 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003658 finalConfiguration = halConfiguration;
3659 status = s;
3660 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003661 if (!err.isOk()) {
3662 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3663 return DEAD_OBJECT;
3664 }
3665 } else {
3666 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3667 ALOGV("%s: v3.2 device found", __FUNCTION__);
3668 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003669 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003670 [&status, &finalConfiguration_3_2]
3671 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3672 finalConfiguration_3_2 = halConfiguration;
3673 status = s;
3674 });
3675 if (!err.isOk()) {
3676 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3677 return DEAD_OBJECT;
3678 }
3679 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3680 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3681 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3682 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003683 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003684 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003685 }
3686
3687 if (status != common::V1_0::Status::OK ) {
3688 return CameraProviderManager::mapToStatusT(status);
3689 }
3690
3691 // And convert output stream configuration from HIDL
3692
3693 for (size_t i = 0; i < config->num_streams; i++) {
3694 camera3_stream_t *dst = config->streams[i];
3695 int streamId = Camera3Stream::cast(dst)->getId();
3696
3697 // Start scan at i, with the assumption that the stream order matches
3698 size_t realIdx = i;
3699 bool found = false;
3700 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003701 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003702 found = true;
3703 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003704 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003705 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3706 }
3707 if (!found) {
3708 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3709 __FUNCTION__, streamId);
3710 return INVALID_OPERATION;
3711 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003712 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003713
Emilian Peev710c1422017-08-30 11:19:38 +01003714 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3715 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003716 dstStream->setDataSpaceOverride(false);
3717 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3718 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3719
Emilian Peev31abd0a2017-05-11 18:37:46 +01003720 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3721 if (dst->format != overrideFormat) {
3722 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3723 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003724 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003725 if (dst->data_space != overrideDataSpace) {
3726 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3727 streamId, dst->format);
3728 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003729 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003730 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003731 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3732
Emilian Peev31abd0a2017-05-11 18:37:46 +01003733 // Override allowed with IMPLEMENTATION_DEFINED
3734 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003735 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003736 }
3737
Emilian Peev31abd0a2017-05-11 18:37:46 +01003738 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003739 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003740 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003741 __FUNCTION__, streamId);
3742 return INVALID_OPERATION;
3743 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003744 dstStream->setUsage(
3745 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003746 } else {
3747 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003748 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003749 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3750 __FUNCTION__, streamId);
3751 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003752 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003753 dstStream->setUsage(
3754 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003755 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003756 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003757 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003758
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003759 return res;
3760}
3761
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003762void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3763 /*out*/device::V3_2::CaptureRequest* captureRequest,
3764 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003765 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003766 if (captureRequest == nullptr || handlesCreated == nullptr) {
3767 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3768 __FUNCTION__, captureRequest, handlesCreated);
3769 return;
3770 }
3771
3772 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003773
3774 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003775
3776 {
3777 std::lock_guard<std::mutex> lock(mInflightLock);
3778 if (request->input_buffer != nullptr) {
3779 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3780 buffer_handle_t buf = *(request->input_buffer->buffer);
3781 auto pair = getBufferId(buf, streamId);
3782 bool isNewBuffer = pair.first;
3783 uint64_t bufferId = pair.second;
3784 captureRequest->inputBuffer.streamId = streamId;
3785 captureRequest->inputBuffer.bufferId = bufferId;
3786 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3787 captureRequest->inputBuffer.status = BufferStatus::OK;
3788 native_handle_t *acquireFence = nullptr;
3789 if (request->input_buffer->acquire_fence != -1) {
3790 acquireFence = native_handle_create(1,0);
3791 acquireFence->data[0] = request->input_buffer->acquire_fence;
3792 handlesCreated->push_back(acquireFence);
3793 }
3794 captureRequest->inputBuffer.acquireFence = acquireFence;
3795 captureRequest->inputBuffer.releaseFence = nullptr;
3796
3797 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3798 request->input_buffer->buffer,
3799 request->input_buffer->acquire_fence);
3800 } else {
3801 captureRequest->inputBuffer.streamId = -1;
3802 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3803 }
3804
3805 captureRequest->outputBuffers.resize(request->num_output_buffers);
3806 for (size_t i = 0; i < request->num_output_buffers; i++) {
3807 const camera3_stream_buffer_t *src = request->output_buffers + i;
3808 StreamBuffer &dst = captureRequest->outputBuffers[i];
3809 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3810 buffer_handle_t buf = *(src->buffer);
3811 auto pair = getBufferId(buf, streamId);
3812 bool isNewBuffer = pair.first;
3813 dst.streamId = streamId;
3814 dst.bufferId = pair.second;
3815 dst.buffer = isNewBuffer ? buf : nullptr;
3816 dst.status = BufferStatus::OK;
3817 native_handle_t *acquireFence = nullptr;
3818 if (src->acquire_fence != -1) {
3819 acquireFence = native_handle_create(1,0);
3820 acquireFence->data[0] = src->acquire_fence;
3821 handlesCreated->push_back(acquireFence);
3822 }
3823 dst.acquireFence = acquireFence;
3824 dst.releaseFence = nullptr;
3825
3826 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3827 src->buffer, src->acquire_fence);
3828 }
3829 }
3830}
3831
3832status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3833 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3834 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3835 if (!valid()) return INVALID_OPERATION;
3836
Emilian Peevaebbe412018-01-15 13:53:24 +00003837 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3838 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3839 if (castResult_3_4.isOk()) {
3840 hidlSession_3_4 = castResult_3_4;
3841 }
3842
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003843 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003844 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003845 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003846 if (hidlSession_3_4 != nullptr) {
3847 captureRequests_3_4.resize(batchSize);
3848 } else {
3849 captureRequests.resize(batchSize);
3850 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003851 std::vector<native_handle_t*> handlesCreated;
3852
3853 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003854 if (hidlSession_3_4 != nullptr) {
3855 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
3856 /*out*/&handlesCreated);
3857 } else {
3858 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3859 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003860 }
3861
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003862 std::vector<device::V3_2::BufferCache> cachesToRemove;
3863 {
3864 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3865 for (auto& pair : mFreedBuffers) {
3866 // The stream might have been removed since onBufferFreed
3867 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3868 cachesToRemove.push_back({pair.first, pair.second});
3869 }
3870 }
3871 mFreedBuffers.clear();
3872 }
3873
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003874 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3875 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003876
3877 // Write metadata to FMQ.
3878 for (size_t i = 0; i < batchSize; i++) {
3879 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003880 device::V3_2::CaptureRequest* captureRequest;
3881 if (hidlSession_3_4 != nullptr) {
3882 captureRequest = &captureRequests_3_4[i].v3_2;
3883 } else {
3884 captureRequest = &captureRequests[i];
3885 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003886
3887 if (request->settings != nullptr) {
3888 size_t settingsSize = get_camera_metadata_size(request->settings);
3889 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3890 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3891 captureRequest->settings.resize(0);
3892 captureRequest->fmqSettingsSize = settingsSize;
3893 } else {
3894 if (mRequestMetadataQueue != nullptr) {
3895 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3896 }
3897 captureRequest->settings.setToExternal(
3898 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3899 get_camera_metadata_size(request->settings));
3900 captureRequest->fmqSettingsSize = 0u;
3901 }
3902 } else {
3903 // A null request settings maps to a size-0 CameraMetadata
3904 captureRequest->settings.resize(0);
3905 captureRequest->fmqSettingsSize = 0u;
3906 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003907
3908 if (hidlSession_3_4 != nullptr) {
3909 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3910 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003911 if (request->physcam_settings != nullptr) {
3912 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3913 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3914 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3915 settingsSize)) {
3916 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3917 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3918 settingsSize;
3919 } else {
3920 if (mRequestMetadataQueue != nullptr) {
3921 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3922 }
3923 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3924 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3925 request->physcam_settings[j])),
3926 get_camera_metadata_size(request->physcam_settings[j]));
3927 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003928 }
Emilian Peev00420d22018-02-05 21:33:13 +00003929 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003930 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003931 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003932 }
3933 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3934 request->physcam_id[j];
3935 }
3936 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003937 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003938
3939 hardware::details::return_status err;
3940 if (hidlSession_3_4 != nullptr) {
3941 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003942 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3943 status = s;
3944 *numRequestProcessed = n;
3945 });
Emilian Peevaebbe412018-01-15 13:53:24 +00003946 } else {
3947 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
3948 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3949 status = s;
3950 *numRequestProcessed = n;
3951 });
3952 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003953 if (!err.isOk()) {
3954 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3955 return DEAD_OBJECT;
3956 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003957 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3958 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3959 __FUNCTION__, *numRequestProcessed, batchSize);
3960 status = common::V1_0::Status::INTERNAL_ERROR;
3961 }
3962
3963 for (auto& handle : handlesCreated) {
3964 native_handle_delete(handle);
3965 }
3966 return CameraProviderManager::mapToStatusT(status);
3967}
3968
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003969status_t Camera3Device::HalInterface::processCaptureRequest(
3970 camera3_capture_request_t *request) {
3971 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003972 if (!valid()) return INVALID_OPERATION;
3973 status_t res = OK;
3974
Emilian Peev31abd0a2017-05-11 18:37:46 +01003975 uint32_t numRequestProcessed = 0;
3976 std::vector<camera3_capture_request_t*> requests(1);
3977 requests[0] = request;
3978 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3979
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003980 return res;
3981}
3982
3983status_t Camera3Device::HalInterface::flush() {
3984 ATRACE_NAME("CameraHal::flush");
3985 if (!valid()) return INVALID_OPERATION;
3986 status_t res = OK;
3987
Emilian Peev31abd0a2017-05-11 18:37:46 +01003988 auto err = mHidlSession->flush();
3989 if (!err.isOk()) {
3990 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3991 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003992 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003993 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003994 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003995
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003996 return res;
3997}
3998
Emilian Peev31abd0a2017-05-11 18:37:46 +01003999status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004000 ATRACE_NAME("CameraHal::dump");
4001 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004002
Emilian Peev31abd0a2017-05-11 18:37:46 +01004003 // Handled by CameraProviderManager::dump
4004
4005 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004006}
4007
4008status_t Camera3Device::HalInterface::close() {
4009 ATRACE_NAME("CameraHal::close()");
4010 if (!valid()) return INVALID_OPERATION;
4011 status_t res = OK;
4012
Emilian Peev31abd0a2017-05-11 18:37:46 +01004013 auto err = mHidlSession->close();
4014 // Interface will be dead shortly anyway, so don't log errors
4015 if (!err.isOk()) {
4016 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004017 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004018
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004019 return res;
4020}
4021
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004022void Camera3Device::HalInterface::getInflightBufferKeys(
4023 std::vector<std::pair<int32_t, int32_t>>* out) {
4024 std::lock_guard<std::mutex> lock(mInflightLock);
4025 out->clear();
4026 out->reserve(mInflightBufferMap.size());
4027 for (auto& pair : mInflightBufferMap) {
4028 uint64_t key = pair.first;
4029 int32_t streamId = key & 0xFFFFFFFF;
4030 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4031 out->push_back(std::make_pair(frameNumber, streamId));
4032 }
4033 return;
4034}
4035
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004036status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004037 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004038 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004039 auto pair = std::make_pair(buffer, acquireFence);
4040 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004041 return OK;
4042}
4043
4044status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004045 int32_t frameNumber, int32_t streamId,
4046 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004047 std::lock_guard<std::mutex> lock(mInflightLock);
4048
4049 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4050 auto it = mInflightBufferMap.find(key);
4051 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004052 auto pair = it->second;
4053 *buffer = pair.first;
4054 int acquireFence = pair.second;
4055 if (acquireFence > 0) {
4056 ::close(acquireFence);
4057 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004058 mInflightBufferMap.erase(it);
4059 return OK;
4060}
4061
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004062std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4063 const buffer_handle_t& buf, int streamId) {
4064 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4065
4066 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4067 auto it = bIdMap.find(buf);
4068 if (it == bIdMap.end()) {
4069 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004070 ALOGV("stream %d now have %zu buffer caches, buf %p",
4071 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004072 return std::make_pair(true, mNextBufferId - 1);
4073 } else {
4074 return std::make_pair(false, it->second);
4075 }
4076}
4077
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004078void Camera3Device::HalInterface::onBufferFreed(
4079 int streamId, const native_handle_t* handle) {
4080 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4081 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4082 auto mapIt = mBufferIdMaps.find(streamId);
4083 if (mapIt == mBufferIdMaps.end()) {
4084 // streamId might be from a deleted stream here
4085 ALOGI("%s: stream %d has been removed",
4086 __FUNCTION__, streamId);
4087 return;
4088 }
4089 BufferIdMap& bIdMap = mapIt->second;
4090 auto it = bIdMap.find(handle);
4091 if (it == bIdMap.end()) {
4092 ALOGW("%s: cannot find buffer %p in stream %d",
4093 __FUNCTION__, handle, streamId);
4094 return;
4095 } else {
4096 bufferId = it->second;
4097 bIdMap.erase(it);
4098 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4099 __FUNCTION__, streamId, bIdMap.size(), handle);
4100 }
4101 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4102}
4103
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004104/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004105 * RequestThread inner class methods
4106 */
4107
4108Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004109 sp<StatusTracker> statusTracker,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004110 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004111 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004112 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004113 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004114 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004115 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004116 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004117 mReconfigured(false),
4118 mDoPause(false),
4119 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004120 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004121 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004122 mCurrentAfTriggerId(0),
4123 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004124 mRepeatingLastFrameNumber(
4125 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004126 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004127 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004128 mRequestLatency(kRequestLatencyBinSize),
4129 mSessionParamKeys(sessionParamKeys),
4130 mLatestSessionParams(sessionParamKeys.size()) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004131 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004132}
4133
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004134Camera3Device::RequestThread::~RequestThread() {}
4135
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004136void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004137 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004138 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004139 Mutex::Autolock l(mRequestLock);
4140 mListener = listener;
4141}
4142
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004143void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4144 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004145 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004146 Mutex::Autolock l(mRequestLock);
4147 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004148 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004149 // Prepare video stream for high speed recording.
4150 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004151 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004152}
4153
Jianing Wei90e59c92014-03-12 18:29:36 -07004154status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004155 List<sp<CaptureRequest> > &requests,
4156 /*out*/
4157 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004158 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004159 Mutex::Autolock l(mRequestLock);
4160 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4161 ++it) {
4162 mRequestQueue.push_back(*it);
4163 }
4164
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004165 if (lastFrameNumber != NULL) {
4166 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4167 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4168 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4169 *lastFrameNumber);
4170 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004171
Jianing Wei90e59c92014-03-12 18:29:36 -07004172 unpauseForNewRequests();
4173
4174 return OK;
4175}
4176
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004177
4178status_t Camera3Device::RequestThread::queueTrigger(
4179 RequestTrigger trigger[],
4180 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004181 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004182 Mutex::Autolock l(mTriggerMutex);
4183 status_t ret;
4184
4185 for (size_t i = 0; i < count; ++i) {
4186 ret = queueTriggerLocked(trigger[i]);
4187
4188 if (ret != OK) {
4189 return ret;
4190 }
4191 }
4192
4193 return OK;
4194}
4195
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004196const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4197 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004198 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004199 if (d != nullptr) return d->mId;
4200 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004201}
4202
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004203status_t Camera3Device::RequestThread::queueTriggerLocked(
4204 RequestTrigger trigger) {
4205
4206 uint32_t tag = trigger.metadataTag;
4207 ssize_t index = mTriggerMap.indexOfKey(tag);
4208
4209 switch (trigger.getTagType()) {
4210 case TYPE_BYTE:
4211 // fall-through
4212 case TYPE_INT32:
4213 break;
4214 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004215 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4216 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004217 return INVALID_OPERATION;
4218 }
4219
4220 /**
4221 * Collect only the latest trigger, since we only have 1 field
4222 * in the request settings per trigger tag, and can't send more than 1
4223 * trigger per request.
4224 */
4225 if (index != NAME_NOT_FOUND) {
4226 mTriggerMap.editValueAt(index) = trigger;
4227 } else {
4228 mTriggerMap.add(tag, trigger);
4229 }
4230
4231 return OK;
4232}
4233
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004234status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004235 const RequestList &requests,
4236 /*out*/
4237 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004238 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004239 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004240 if (lastFrameNumber != NULL) {
4241 *lastFrameNumber = mRepeatingLastFrameNumber;
4242 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004243 mRepeatingRequests.clear();
4244 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4245 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004246
4247 unpauseForNewRequests();
4248
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004249 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004250 return OK;
4251}
4252
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004253bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004254 if (mRepeatingRequests.empty()) {
4255 return false;
4256 }
4257 int32_t requestId = requestIn->mResultExtras.requestId;
4258 const RequestList &repeatRequests = mRepeatingRequests;
4259 // All repeating requests are guaranteed to have same id so only check first quest
4260 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4261 return (firstRequest->mResultExtras.requestId == requestId);
4262}
4263
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004264status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004265 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004266 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004267 return clearRepeatingRequestsLocked(lastFrameNumber);
4268
4269}
4270
4271status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004272 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004273 if (lastFrameNumber != NULL) {
4274 *lastFrameNumber = mRepeatingLastFrameNumber;
4275 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004276 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004277 return OK;
4278}
4279
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004280status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004281 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004282 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004283 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004284 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004285
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004286 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004287
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004288 // Send errors for all requests pending in the request queue, including
4289 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004290 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004291 if (listener != NULL) {
4292 for (RequestList::iterator it = mRequestQueue.begin();
4293 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004294 // Abort the input buffers for reprocess requests.
4295 if ((*it)->mInputStream != NULL) {
4296 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004297 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4298 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004299 if (res != OK) {
4300 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4301 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4302 } else {
4303 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4304 if (res != OK) {
4305 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4306 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4307 }
4308 }
4309 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004310 // Set the frame number this request would have had, if it
4311 // had been submitted; this frame number will not be reused.
4312 // The requestId and burstId fields were set when the request was
4313 // submitted originally (in convertMetadataListToRequestListLocked)
4314 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004315 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004316 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004317 }
4318 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004319 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004320
4321 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004322 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004323 if (lastFrameNumber != NULL) {
4324 *lastFrameNumber = mRepeatingLastFrameNumber;
4325 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004326 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004327 return OK;
4328}
4329
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004330status_t Camera3Device::RequestThread::flush() {
4331 ATRACE_CALL();
4332 Mutex::Autolock l(mFlushLock);
4333
Emilian Peev08dd2452017-04-06 16:55:14 +01004334 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004335}
4336
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004337void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004338 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004339 Mutex::Autolock l(mPauseLock);
4340 mDoPause = paused;
4341 mDoPauseSignal.signal();
4342}
4343
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004344status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4345 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004346 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004347 Mutex::Autolock l(mLatestRequestMutex);
4348 status_t res;
4349 while (mLatestRequestId != requestId) {
4350 nsecs_t startTime = systemTime();
4351
4352 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4353 if (res != OK) return res;
4354
4355 timeout -= (systemTime() - startTime);
4356 }
4357
4358 return OK;
4359}
4360
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004361void Camera3Device::RequestThread::requestExit() {
4362 // Call parent to set up shutdown
4363 Thread::requestExit();
4364 // The exit from any possible waits
4365 mDoPauseSignal.signal();
4366 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004367
4368 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4369 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004370}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004371
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004372void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004373 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004374 bool surfaceAbandoned = false;
4375 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004376 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004377 {
4378 Mutex::Autolock l(mRequestLock);
4379 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4380 // repeating requests.
4381 for (const auto& request : mRepeatingRequests) {
4382 for (const auto& s : request->mOutputStreams) {
4383 if (s->isAbandoned()) {
4384 surfaceAbandoned = true;
4385 clearRepeatingRequestsLocked(&lastFrameNumber);
4386 break;
4387 }
4388 }
4389 if (surfaceAbandoned) {
4390 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004391 }
4392 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004393 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004394 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004395
4396 if (listener != NULL && surfaceAbandoned) {
4397 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004398 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004399}
4400
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004401bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004402 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004403 status_t res;
4404 size_t batchSize = mNextRequests.size();
4405 std::vector<camera3_capture_request_t*> requests(batchSize);
4406 uint32_t numRequestProcessed = 0;
4407 for (size_t i = 0; i < batchSize; i++) {
4408 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004409 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004410 }
4411
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004412 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4413
4414 bool triggerRemoveFailed = false;
4415 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4416 for (size_t i = 0; i < numRequestProcessed; i++) {
4417 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4418 nextRequest.submitted = true;
4419
4420
4421 // Update the latest request sent to HAL
4422 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4423 Mutex::Autolock al(mLatestRequestMutex);
4424
4425 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4426 mLatestRequest.acquire(cloned);
4427
4428 sp<Camera3Device> parent = mParent.promote();
4429 if (parent != NULL) {
4430 parent->monitorMetadata(TagMonitor::REQUEST,
4431 nextRequest.halRequest.frame_number,
4432 0, mLatestRequest);
4433 }
4434 }
4435
4436 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004437 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4438 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004439 }
4440
Emilian Peevaebbe412018-01-15 13:53:24 +00004441 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4442
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004443 if (!triggerRemoveFailed) {
4444 // Remove any previously queued triggers (after unlock)
4445 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4446 if (removeTriggerRes != OK) {
4447 triggerRemoveFailed = true;
4448 triggerFailedRequest = nextRequest;
4449 }
4450 }
4451 }
4452
4453 if (triggerRemoveFailed) {
4454 SET_ERR("RequestThread: Unable to remove triggers "
4455 "(capture request %d, HAL device: %s (%d)",
4456 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4457 cleanUpFailedRequests(/*sendRequestError*/ false);
4458 return false;
4459 }
4460
4461 if (res != OK) {
4462 // Should only get a failure here for malformed requests or device-level
4463 // errors, so consider all errors fatal. Bad metadata failures should
4464 // come through notify.
4465 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4466 mNextRequests[numRequestProcessed].halRequest.frame_number,
4467 strerror(-res), res);
4468 cleanUpFailedRequests(/*sendRequestError*/ false);
4469 return false;
4470 }
4471 return true;
4472}
4473
4474bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4475 status_t res;
4476
4477 for (auto& nextRequest : mNextRequests) {
4478 // Submit request and block until ready for next one
4479 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4480 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4481
4482 if (res != OK) {
4483 // Should only get a failure here for malformed requests or device-level
4484 // errors, so consider all errors fatal. Bad metadata failures should
4485 // come through notify.
4486 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4487 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4488 res);
4489 cleanUpFailedRequests(/*sendRequestError*/ false);
4490 return false;
4491 }
4492
4493 // Mark that the request has be submitted successfully.
4494 nextRequest.submitted = true;
4495
4496 // Update the latest request sent to HAL
4497 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4498 Mutex::Autolock al(mLatestRequestMutex);
4499
4500 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4501 mLatestRequest.acquire(cloned);
4502
4503 sp<Camera3Device> parent = mParent.promote();
4504 if (parent != NULL) {
4505 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4506 0, mLatestRequest);
4507 }
4508 }
4509
4510 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004511 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4512 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004513 }
4514
Emilian Peevaebbe412018-01-15 13:53:24 +00004515 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4516
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004517 // Remove any previously queued triggers (after unlock)
4518 res = removeTriggers(mPrevRequest);
4519 if (res != OK) {
4520 SET_ERR("RequestThread: Unable to remove triggers "
4521 "(capture request %d, HAL device: %s (%d)",
4522 nextRequest.halRequest.frame_number, strerror(-res), res);
4523 cleanUpFailedRequests(/*sendRequestError*/ false);
4524 return false;
4525 }
4526 }
4527 return true;
4528}
4529
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004530nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4531 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4532 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4533 find_camera_metadata_ro_entry(request,
4534 ANDROID_CONTROL_AE_MODE,
4535 &e);
4536 if (e.count == 0) return maxExpectedDuration;
4537
4538 switch (e.data.u8[0]) {
4539 case ANDROID_CONTROL_AE_MODE_OFF:
4540 find_camera_metadata_ro_entry(request,
4541 ANDROID_SENSOR_EXPOSURE_TIME,
4542 &e);
4543 if (e.count > 0) {
4544 maxExpectedDuration = e.data.i64[0];
4545 }
4546 find_camera_metadata_ro_entry(request,
4547 ANDROID_SENSOR_FRAME_DURATION,
4548 &e);
4549 if (e.count > 0) {
4550 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4551 }
4552 break;
4553 default:
4554 find_camera_metadata_ro_entry(request,
4555 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4556 &e);
4557 if (e.count > 1) {
4558 maxExpectedDuration = 1e9 / e.data.u8[0];
4559 }
4560 break;
4561 }
4562
4563 return maxExpectedDuration;
4564}
4565
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004566bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4567 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4568 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4569 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4570 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4571 return true;
4572 }
4573
4574 return false;
4575}
4576
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004577bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4578 ATRACE_CALL();
4579 bool updatesDetected = false;
4580
4581 for (auto tag : mSessionParamKeys) {
4582 camera_metadata_ro_entry entry = settings.find(tag);
4583 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4584
4585 if (entry.count > 0) {
4586 bool isDifferent = false;
4587 if (lastEntry.count > 0) {
4588 // Have a last value, compare to see if changed
4589 if (lastEntry.type == entry.type &&
4590 lastEntry.count == entry.count) {
4591 // Same type and count, compare values
4592 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4593 size_t entryBytes = bytesPerValue * lastEntry.count;
4594 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4595 if (cmp != 0) {
4596 isDifferent = true;
4597 }
4598 } else {
4599 // Count or type has changed
4600 isDifferent = true;
4601 }
4602 } else {
4603 // No last entry, so always consider to be different
4604 isDifferent = true;
4605 }
4606
4607 if (isDifferent) {
4608 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004609 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4610 updatesDetected = true;
4611 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004612 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004613 }
4614 } else if (lastEntry.count > 0) {
4615 // Value has been removed
4616 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4617 mLatestSessionParams.erase(tag);
4618 updatesDetected = true;
4619 }
4620 }
4621
4622 return updatesDetected;
4623}
4624
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004625bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004626 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004627 status_t res;
4628
4629 // Handle paused state.
4630 if (waitIfPaused()) {
4631 return true;
4632 }
4633
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004634 // Wait for the next batch of requests.
4635 waitForNextRequestBatch();
4636 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004637 return true;
4638 }
4639
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004640 // Get the latest request ID, if any
4641 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004642 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004643 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004644 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004645 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004646 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004647 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4648 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004649 }
4650
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004651 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4652 // or a single request from streaming or burst. In either case the first element
4653 // should contain the latest camera settings that we need to check for any session
4654 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004655 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004656 res = OK;
4657
4658 //Input stream buffers are already acquired at this point so an input stream
4659 //will not be able to move to idle state unless we force it.
4660 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4661 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4662 if (res != OK) {
4663 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4664 cleanUpFailedRequests(/*sendRequestError*/ false);
4665 return false;
4666 }
4667 }
4668
4669 if (res == OK) {
4670 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4671 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004672 sp<Camera3Device> parent = mParent.promote();
4673 if (parent != nullptr) {
4674 parent->pauseStateNotify(true);
4675 }
4676
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004677 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4678
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004679 if (parent != nullptr) {
4680 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4681 }
4682
4683 statusTracker->markComponentActive(mStatusId);
4684 setPaused(false);
4685 }
4686
4687 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4688 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4689 if (res != OK) {
4690 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4691 cleanUpFailedRequests(/*sendRequestError*/ false);
4692 return false;
4693 }
4694 }
4695 }
4696 }
4697
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004698 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004699 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004700 if (res == TIMED_OUT) {
4701 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004702 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004703 // Check if any stream is abandoned.
4704 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004705 return true;
4706 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004707 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004708 return false;
4709 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004710
Zhijun Hecc27e112013-10-03 16:12:43 -07004711 // Inform waitUntilRequestProcessed thread of a new request ID
4712 {
4713 Mutex::Autolock al(mLatestRequestMutex);
4714
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004715 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004716 mLatestRequestSignal.signal();
4717 }
4718
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004719 // Submit a batch of requests to HAL.
4720 // Use flush lock only when submitting multilple requests in a batch.
4721 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4722 // which may take a long time to finish so synchronizing flush() and
4723 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4724 // For now, only synchronize for high speed recording and we should figure something out for
4725 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004726 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004727
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004728 if (useFlushLock) {
4729 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004730 }
4731
Zhijun Hef0645c12016-08-02 00:58:11 -07004732 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004733 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004734
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004735 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004736 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004737 if (mInterface->supportBatchRequest()) {
4738 submitRequestSuccess = sendRequestsBatch();
4739 } else {
4740 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004741 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004742 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4743 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004744
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004745 if (useFlushLock) {
4746 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004747 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004748
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004749 // Unset as current request
4750 {
4751 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004752 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004753 }
4754
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004755 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004756}
4757
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004758status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004759 ATRACE_CALL();
4760
Shuzhen Wang4a472662017-02-26 23:29:04 -08004761 for (size_t i = 0; i < mNextRequests.size(); i++) {
4762 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004763 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4764 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4765 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4766
4767 // Prepare a request to HAL
4768 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4769
4770 // Insert any queued triggers (before metadata is locked)
4771 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004772 if (res < 0) {
4773 SET_ERR("RequestThread: Unable to insert triggers "
4774 "(capture request %d, HAL device: %s (%d)",
4775 halRequest->frame_number, strerror(-res), res);
4776 return INVALID_OPERATION;
4777 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004778
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004779 int triggerCount = res;
4780 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4781 mPrevTriggers = triggerCount;
4782
4783 // If the request is the same as last, or we had triggers last time
Emilian Peev00420d22018-02-05 21:33:13 +00004784 bool newRequest = mPrevRequest != captureRequest || triggersMixedIn;
4785 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004786 /**
4787 * HAL workaround:
4788 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4789 */
4790 res = addDummyTriggerIds(captureRequest);
4791 if (res != OK) {
4792 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4793 "(capture request %d, HAL device: %s (%d)",
4794 halRequest->frame_number, strerror(-res), res);
4795 return INVALID_OPERATION;
4796 }
4797
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004798 {
4799 // Correct metadata regions for distortion correction if enabled
4800 sp<Camera3Device> parent = mParent.promote();
4801 if (parent != nullptr) {
4802 res = parent->mDistortionMapper.correctCaptureRequest(
4803 &(captureRequest->mSettingsList.begin()->metadata));
4804 if (res != OK) {
4805 SET_ERR("RequestThread: Unable to correct capture requests "
4806 "for lens distortion for request %d: %s (%d)",
4807 halRequest->frame_number, strerror(-res), res);
4808 return INVALID_OPERATION;
4809 }
4810 }
4811 }
4812
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004813 /**
4814 * The request should be presorted so accesses in HAL
4815 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4816 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004817 captureRequest->mSettingsList.begin()->metadata.sort();
4818 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004819 mPrevRequest = captureRequest;
4820 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4821
4822 IF_ALOGV() {
4823 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4824 find_camera_metadata_ro_entry(
4825 halRequest->settings,
4826 ANDROID_CONTROL_AF_TRIGGER,
4827 &e
4828 );
4829 if (e.count > 0) {
4830 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4831 __FUNCTION__,
4832 halRequest->frame_number,
4833 e.data.u8[0]);
4834 }
4835 }
4836 } else {
4837 // leave request.settings NULL to indicate 'reuse latest given'
4838 ALOGVV("%s: Request settings are REUSED",
4839 __FUNCTION__);
4840 }
4841
Emilian Peevaebbe412018-01-15 13:53:24 +00004842 if (captureRequest->mSettingsList.size() > 1) {
4843 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4844 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004845 if (newRequest) {
4846 halRequest->physcam_settings =
4847 new const camera_metadata* [halRequest->num_physcam_settings];
4848 } else {
4849 halRequest->physcam_settings = nullptr;
4850 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004851 auto it = ++captureRequest->mSettingsList.begin();
4852 size_t i = 0;
4853 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4854 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004855 if (newRequest) {
4856 it->metadata.sort();
4857 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4858 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004859 }
4860 }
4861
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004862 uint32_t totalNumBuffers = 0;
4863
4864 // Fill in buffers
4865 if (captureRequest->mInputStream != NULL) {
4866 halRequest->input_buffer = &captureRequest->mInputBuffer;
4867 totalNumBuffers += 1;
4868 } else {
4869 halRequest->input_buffer = NULL;
4870 }
4871
4872 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4873 captureRequest->mOutputStreams.size());
4874 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004875 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004876
4877 sp<Camera3Device> parent = mParent.promote();
4878 if (parent == NULL) {
4879 // Should not happen, and nowhere to send errors to, so just log it
4880 CLOGE("RequestThread: Parent is gone");
4881 return INVALID_OPERATION;
4882 }
4883 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4884
Shuzhen Wang4a472662017-02-26 23:29:04 -08004885 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4886 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004887
4888 // Prepare video buffers for high speed recording on the first video request.
4889 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4890 // Only try to prepare video stream on the first video request.
4891 mPrepareVideoStream = false;
4892
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004893 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4894 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004895 while (res == NOT_ENOUGH_DATA) {
4896 res = outputStream->prepareNextBuffer();
4897 }
4898 if (res != OK) {
4899 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4900 __FUNCTION__, strerror(-res), res);
4901 outputStream->cancelPrepare();
4902 }
4903 }
4904
Shuzhen Wang4a472662017-02-26 23:29:04 -08004905 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004906 waitDuration,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004907 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004908 if (res != OK) {
4909 // Can't get output buffer from gralloc queue - this could be due to
4910 // abandoned queue or other consumer misbehavior, so not a fatal
4911 // error
4912 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4913 " %s (%d)", strerror(-res), res);
4914
4915 return TIMED_OUT;
4916 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004917
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004918 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4919
4920 if (!physicalCameraId.isEmpty()) {
4921 // Physical stream isn't supported for input request.
4922 if (halRequest->input_buffer) {
4923 CLOGE("Physical stream is not supported for input request");
4924 return INVALID_OPERATION;
4925 }
4926 requestedPhysicalCameras.insert(physicalCameraId);
4927 }
4928 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004929 }
4930 totalNumBuffers += halRequest->num_output_buffers;
4931
4932 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004933 // If this request list is for constrained high speed recording (not
4934 // preview), and the current request is not the last one in the batch,
4935 // do not send callback to the app.
4936 bool hasCallback = true;
4937 if (mNextRequests[0].captureRequest->mBatchSize > 1 && i != mNextRequests.size()-1) {
4938 hasCallback = false;
4939 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004940 res = parent->registerInFlight(halRequest->frame_number,
4941 totalNumBuffers, captureRequest->mResultExtras,
4942 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004943 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004944 calculateMaxExpectedDuration(halRequest->settings),
4945 requestedPhysicalCameras);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004946 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4947 ", burstId = %" PRId32 ".",
4948 __FUNCTION__,
4949 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4950 captureRequest->mResultExtras.burstId);
4951 if (res != OK) {
4952 SET_ERR("RequestThread: Unable to register new in-flight request:"
4953 " %s (%d)", strerror(-res), res);
4954 return INVALID_OPERATION;
4955 }
4956 }
4957
4958 return OK;
4959}
4960
Igor Murashkin1e479c02013-09-06 16:55:14 -07004961CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004962 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004963 Mutex::Autolock al(mLatestRequestMutex);
4964
4965 ALOGV("RequestThread::%s", __FUNCTION__);
4966
4967 return mLatestRequest;
4968}
4969
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004970bool Camera3Device::RequestThread::isStreamPending(
4971 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004972 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004973 Mutex::Autolock l(mRequestLock);
4974
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004975 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004976 if (!nextRequest.submitted) {
4977 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4978 if (stream == s) return true;
4979 }
4980 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004981 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004982 }
4983
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004984 for (const auto& request : mRequestQueue) {
4985 for (const auto& s : request->mOutputStreams) {
4986 if (stream == s) return true;
4987 }
4988 if (stream == request->mInputStream) return true;
4989 }
4990
4991 for (const auto& request : mRepeatingRequests) {
4992 for (const auto& s : request->mOutputStreams) {
4993 if (stream == s) return true;
4994 }
4995 if (stream == request->mInputStream) return true;
4996 }
4997
4998 return false;
4999}
Jianing Weicb0652e2014-03-12 18:29:36 -07005000
Emilian Peev40ead602017-09-26 15:46:36 +01005001bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5002 ATRACE_CALL();
5003 Mutex::Autolock l(mRequestLock);
5004
5005 for (const auto& nextRequest : mNextRequests) {
5006 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5007 if (s.first == streamId) {
5008 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5009 if (it != s.second.end()) {
5010 return true;
5011 }
5012 }
5013 }
5014 }
5015
5016 for (const auto& request : mRequestQueue) {
5017 for (const auto& s : request->mOutputSurfaces) {
5018 if (s.first == streamId) {
5019 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5020 if (it != s.second.end()) {
5021 return true;
5022 }
5023 }
5024 }
5025 }
5026
5027 for (const auto& request : mRepeatingRequests) {
5028 for (const auto& s : request->mOutputSurfaces) {
5029 if (s.first == streamId) {
5030 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5031 if (it != s.second.end()) {
5032 return true;
5033 }
5034 }
5035 }
5036 }
5037
5038 return false;
5039}
5040
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005041nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005042 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005043 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005044 return mExpectedInflightDuration > kMinInflightDuration ?
5045 mExpectedInflightDuration : kMinInflightDuration;
5046}
5047
Emilian Peevaebbe412018-01-15 13:53:24 +00005048void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5049 camera3_capture_request_t *halRequest) {
5050 if ((request == nullptr) || (halRequest == nullptr)) {
5051 ALOGE("%s: Invalid request!", __FUNCTION__);
5052 return;
5053 }
5054
5055 if (halRequest->num_physcam_settings > 0) {
5056 if (halRequest->physcam_id != nullptr) {
5057 delete [] halRequest->physcam_id;
5058 halRequest->physcam_id = nullptr;
5059 }
5060 if (halRequest->physcam_settings != nullptr) {
5061 auto it = ++(request->mSettingsList.begin());
5062 size_t i = 0;
5063 for (; it != request->mSettingsList.end(); it++, i++) {
5064 it->metadata.unlock(halRequest->physcam_settings[i]);
5065 }
5066 delete [] halRequest->physcam_settings;
5067 halRequest->physcam_settings = nullptr;
5068 }
5069 }
5070}
5071
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005072void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5073 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005074 return;
5075 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005076
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005077 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005078 // Skip the ones that have been submitted successfully.
5079 if (nextRequest.submitted) {
5080 continue;
5081 }
5082
5083 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5084 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5085 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5086
5087 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005088 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005089 }
5090
Emilian Peevaebbe412018-01-15 13:53:24 +00005091 cleanupPhysicalSettings(captureRequest, halRequest);
5092
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005093 if (captureRequest->mInputStream != NULL) {
5094 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5095 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5096 }
5097
5098 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005099 //Buffers that failed processing could still have
5100 //valid acquire fence.
5101 int acquireFence = (*outputBuffers)[i].acquire_fence;
5102 if (0 <= acquireFence) {
5103 close(acquireFence);
5104 outputBuffers->editItemAt(i).acquire_fence = -1;
5105 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005106 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5107 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5108 }
5109
5110 if (sendRequestError) {
5111 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005112 sp<NotificationListener> listener = mListener.promote();
5113 if (listener != NULL) {
5114 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005115 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005116 captureRequest->mResultExtras);
5117 }
5118 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005119
5120 // Remove yet-to-be submitted inflight request from inflightMap
5121 {
5122 sp<Camera3Device> parent = mParent.promote();
5123 if (parent != NULL) {
5124 Mutex::Autolock l(parent->mInFlightLock);
5125 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5126 if (idx >= 0) {
5127 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5128 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5129 parent->removeInFlightMapEntryLocked(idx);
5130 }
5131 }
5132 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005133 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005134
5135 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005136 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005137}
5138
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005139void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005140 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005141 // Optimized a bit for the simple steady-state case (single repeating
5142 // request), to avoid putting that request in the queue temporarily.
5143 Mutex::Autolock l(mRequestLock);
5144
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005145 assert(mNextRequests.empty());
5146
5147 NextRequest nextRequest;
5148 nextRequest.captureRequest = waitForNextRequestLocked();
5149 if (nextRequest.captureRequest == nullptr) {
5150 return;
5151 }
5152
5153 nextRequest.halRequest = camera3_capture_request_t();
5154 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005155 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005156
5157 // Wait for additional requests
5158 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5159
5160 for (size_t i = 1; i < batchSize; i++) {
5161 NextRequest additionalRequest;
5162 additionalRequest.captureRequest = waitForNextRequestLocked();
5163 if (additionalRequest.captureRequest == nullptr) {
5164 break;
5165 }
5166
5167 additionalRequest.halRequest = camera3_capture_request_t();
5168 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005169 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005170 }
5171
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005172 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005173 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005174 mNextRequests.size(), batchSize);
5175 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005176 }
5177
5178 return;
5179}
5180
5181sp<Camera3Device::CaptureRequest>
5182 Camera3Device::RequestThread::waitForNextRequestLocked() {
5183 status_t res;
5184 sp<CaptureRequest> nextRequest;
5185
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005186 while (mRequestQueue.empty()) {
5187 if (!mRepeatingRequests.empty()) {
5188 // Always atomically enqueue all requests in a repeating request
5189 // list. Guarantees a complete in-sequence set of captures to
5190 // application.
5191 const RequestList &requests = mRepeatingRequests;
5192 RequestList::const_iterator firstRequest =
5193 requests.begin();
5194 nextRequest = *firstRequest;
5195 mRequestQueue.insert(mRequestQueue.end(),
5196 ++firstRequest,
5197 requests.end());
5198 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005199
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005200 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005201
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005202 break;
5203 }
5204
5205 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5206
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005207 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5208 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005209 Mutex::Autolock pl(mPauseLock);
5210 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005211 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005212 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005213 // Let the tracker know
5214 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5215 if (statusTracker != 0) {
5216 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5217 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005218 }
5219 // Stop waiting for now and let thread management happen
5220 return NULL;
5221 }
5222 }
5223
5224 if (nextRequest == NULL) {
5225 // Don't have a repeating request already in hand, so queue
5226 // must have an entry now.
5227 RequestList::iterator firstRequest =
5228 mRequestQueue.begin();
5229 nextRequest = *firstRequest;
5230 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005231 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5232 sp<NotificationListener> listener = mListener.promote();
5233 if (listener != NULL) {
5234 listener->notifyRequestQueueEmpty();
5235 }
5236 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005237 }
5238
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005239 // In case we've been unpaused by setPaused clearing mDoPause, need to
5240 // update internal pause state (capture/setRepeatingRequest unpause
5241 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005242 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005243 if (mPaused) {
5244 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5245 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5246 if (statusTracker != 0) {
5247 statusTracker->markComponentActive(mStatusId);
5248 }
5249 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005250 mPaused = false;
5251
5252 // Check if we've reconfigured since last time, and reset the preview
5253 // request if so. Can't use 'NULL request == repeat' across configure calls.
5254 if (mReconfigured) {
5255 mPrevRequest.clear();
5256 mReconfigured = false;
5257 }
5258
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005259 if (nextRequest != NULL) {
5260 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005261 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5262 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005263
5264 // Since RequestThread::clear() removes buffers from the input stream,
5265 // get the right buffer here before unlocking mRequestLock
5266 if (nextRequest->mInputStream != NULL) {
5267 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5268 if (res != OK) {
5269 // Can't get input buffer from gralloc queue - this could be due to
5270 // disconnected queue or other producer misbehavior, so not a fatal
5271 // error
5272 ALOGE("%s: Can't get input buffer, skipping request:"
5273 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005274
5275 sp<NotificationListener> listener = mListener.promote();
5276 if (listener != NULL) {
5277 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005278 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005279 nextRequest->mResultExtras);
5280 }
5281 return NULL;
5282 }
5283 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005284 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005285
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005286 return nextRequest;
5287}
5288
5289bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005290 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005291 status_t res;
5292 Mutex::Autolock l(mPauseLock);
5293 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005294 if (mPaused == false) {
5295 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005296 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5297 // Let the tracker know
5298 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5299 if (statusTracker != 0) {
5300 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5301 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005302 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005303
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005304 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005305 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005306 return true;
5307 }
5308 }
5309 // We don't set mPaused to false here, because waitForNextRequest needs
5310 // to further manage the paused state in case of starvation.
5311 return false;
5312}
5313
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005314void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005315 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005316 // With work to do, mark thread as unpaused.
5317 // If paused by request (setPaused), don't resume, to avoid
5318 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005319 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005320 Mutex::Autolock p(mPauseLock);
5321 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005322 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5323 if (mPaused) {
5324 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5325 if (statusTracker != 0) {
5326 statusTracker->markComponentActive(mStatusId);
5327 }
5328 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005329 mPaused = false;
5330 }
5331}
5332
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005333void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5334 sp<Camera3Device> parent = mParent.promote();
5335 if (parent != NULL) {
5336 va_list args;
5337 va_start(args, fmt);
5338
5339 parent->setErrorStateV(fmt, args);
5340
5341 va_end(args);
5342 }
5343}
5344
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005345status_t Camera3Device::RequestThread::insertTriggers(
5346 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005347 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005348 Mutex::Autolock al(mTriggerMutex);
5349
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005350 sp<Camera3Device> parent = mParent.promote();
5351 if (parent == NULL) {
5352 CLOGE("RequestThread: Parent is gone");
5353 return DEAD_OBJECT;
5354 }
5355
Emilian Peevaebbe412018-01-15 13:53:24 +00005356 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005357 size_t count = mTriggerMap.size();
5358
5359 for (size_t i = 0; i < count; ++i) {
5360 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005361 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005362
5363 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5364 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5365 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005366 if (isAeTrigger) {
5367 request->mResultExtras.precaptureTriggerId = triggerId;
5368 mCurrentPreCaptureTriggerId = triggerId;
5369 } else {
5370 request->mResultExtras.afTriggerId = triggerId;
5371 mCurrentAfTriggerId = triggerId;
5372 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005373 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005374 }
5375
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005376 camera_metadata_entry entry = metadata.find(tag);
5377
5378 if (entry.count > 0) {
5379 /**
5380 * Already has an entry for this trigger in the request.
5381 * Rewrite it with our requested trigger value.
5382 */
5383 RequestTrigger oldTrigger = trigger;
5384
5385 oldTrigger.entryValue = entry.data.u8[0];
5386
5387 mTriggerReplacedMap.add(tag, oldTrigger);
5388 } else {
5389 /**
5390 * More typical, no trigger entry, so we just add it
5391 */
5392 mTriggerRemovedMap.add(tag, trigger);
5393 }
5394
5395 status_t res;
5396
5397 switch (trigger.getTagType()) {
5398 case TYPE_BYTE: {
5399 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5400 res = metadata.update(tag,
5401 &entryValue,
5402 /*count*/1);
5403 break;
5404 }
5405 case TYPE_INT32:
5406 res = metadata.update(tag,
5407 &trigger.entryValue,
5408 /*count*/1);
5409 break;
5410 default:
5411 ALOGE("%s: Type not supported: 0x%x",
5412 __FUNCTION__,
5413 trigger.getTagType());
5414 return INVALID_OPERATION;
5415 }
5416
5417 if (res != OK) {
5418 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5419 ", value %d", __FUNCTION__, trigger.getTagName(),
5420 trigger.entryValue);
5421 return res;
5422 }
5423
5424 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5425 trigger.getTagName(),
5426 trigger.entryValue);
5427 }
5428
5429 mTriggerMap.clear();
5430
5431 return count;
5432}
5433
5434status_t Camera3Device::RequestThread::removeTriggers(
5435 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005436 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005437 Mutex::Autolock al(mTriggerMutex);
5438
Emilian Peevaebbe412018-01-15 13:53:24 +00005439 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005440
5441 /**
5442 * Replace all old entries with their old values.
5443 */
5444 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5445 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5446
5447 status_t res;
5448
5449 uint32_t tag = trigger.metadataTag;
5450 switch (trigger.getTagType()) {
5451 case TYPE_BYTE: {
5452 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5453 res = metadata.update(tag,
5454 &entryValue,
5455 /*count*/1);
5456 break;
5457 }
5458 case TYPE_INT32:
5459 res = metadata.update(tag,
5460 &trigger.entryValue,
5461 /*count*/1);
5462 break;
5463 default:
5464 ALOGE("%s: Type not supported: 0x%x",
5465 __FUNCTION__,
5466 trigger.getTagType());
5467 return INVALID_OPERATION;
5468 }
5469
5470 if (res != OK) {
5471 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5472 ", trigger value %d", __FUNCTION__,
5473 trigger.getTagName(), trigger.entryValue);
5474 return res;
5475 }
5476 }
5477 mTriggerReplacedMap.clear();
5478
5479 /**
5480 * Remove all new entries.
5481 */
5482 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5483 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5484 status_t res = metadata.erase(trigger.metadataTag);
5485
5486 if (res != OK) {
5487 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5488 ", trigger value %d", __FUNCTION__,
5489 trigger.getTagName(), trigger.entryValue);
5490 return res;
5491 }
5492 }
5493 mTriggerRemovedMap.clear();
5494
5495 return OK;
5496}
5497
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005498status_t Camera3Device::RequestThread::addDummyTriggerIds(
5499 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005500 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005501 static const int32_t dummyTriggerId = 1;
5502 status_t res;
5503
Emilian Peevaebbe412018-01-15 13:53:24 +00005504 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005505
5506 // If AF trigger is active, insert a dummy AF trigger ID if none already
5507 // exists
5508 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5509 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5510 if (afTrigger.count > 0 &&
5511 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5512 afId.count == 0) {
5513 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5514 if (res != OK) return res;
5515 }
5516
5517 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5518 // if none already exists
5519 camera_metadata_entry pcTrigger =
5520 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5521 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5522 if (pcTrigger.count > 0 &&
5523 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5524 pcId.count == 0) {
5525 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5526 &dummyTriggerId, 1);
5527 if (res != OK) return res;
5528 }
5529
5530 return OK;
5531}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005532
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005533/**
5534 * PreparerThread inner class methods
5535 */
5536
5537Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005538 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005539 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005540}
5541
5542Camera3Device::PreparerThread::~PreparerThread() {
5543 Thread::requestExitAndWait();
5544 if (mCurrentStream != nullptr) {
5545 mCurrentStream->cancelPrepare();
5546 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5547 mCurrentStream.clear();
5548 }
5549 clear();
5550}
5551
Ruben Brunkc78ac262015-08-13 17:58:46 -07005552status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005553 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005554 status_t res;
5555
5556 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005557 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005558
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005559 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005560 if (res == OK) {
5561 // No preparation needed, fire listener right off
5562 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005563 if (listener != NULL) {
5564 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005565 }
5566 return OK;
5567 } else if (res != NOT_ENOUGH_DATA) {
5568 return res;
5569 }
5570
5571 // Need to prepare, start up thread if necessary
5572 if (!mActive) {
5573 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5574 // isn't running
5575 Thread::requestExitAndWait();
5576 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5577 if (res != OK) {
5578 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005579 if (listener != NULL) {
5580 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005581 }
5582 return res;
5583 }
5584 mCancelNow = false;
5585 mActive = true;
5586 ALOGV("%s: Preparer stream started", __FUNCTION__);
5587 }
5588
5589 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005590 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005591 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5592
5593 return OK;
5594}
5595
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005596void Camera3Device::PreparerThread::pause() {
5597 ATRACE_CALL();
5598
5599 Mutex::Autolock l(mLock);
5600
5601 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5602 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5603 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5604 int currentMaxCount = mCurrentMaxCount;
5605 mPendingStreams.clear();
5606 mCancelNow = true;
5607 while (mActive) {
5608 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5609 if (res == TIMED_OUT) {
5610 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5611 return;
5612 } else if (res != OK) {
5613 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5614 return;
5615 }
5616 }
5617
5618 //Check whether the prepare thread was able to complete the current
5619 //stream. In case work is still pending emplace it along with the rest
5620 //of the streams in the pending list.
5621 if (currentStream != nullptr) {
5622 if (!mCurrentPrepareComplete) {
5623 pendingStreams.emplace(currentMaxCount, currentStream);
5624 }
5625 }
5626
5627 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5628 for (const auto& it : mPendingStreams) {
5629 it.second->cancelPrepare();
5630 }
5631}
5632
5633status_t Camera3Device::PreparerThread::resume() {
5634 ATRACE_CALL();
5635 status_t res;
5636
5637 Mutex::Autolock l(mLock);
5638 sp<NotificationListener> listener = mListener.promote();
5639
5640 if (mActive) {
5641 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5642 return NO_INIT;
5643 }
5644
5645 auto it = mPendingStreams.begin();
5646 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005647 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005648 if (res == OK) {
5649 if (listener != NULL) {
5650 listener->notifyPrepared(it->second->getId());
5651 }
5652 it = mPendingStreams.erase(it);
5653 } else if (res != NOT_ENOUGH_DATA) {
5654 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5655 res, strerror(-res));
5656 it = mPendingStreams.erase(it);
5657 } else {
5658 it++;
5659 }
5660 }
5661
5662 if (mPendingStreams.empty()) {
5663 return OK;
5664 }
5665
5666 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5667 if (res != OK) {
5668 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5669 __FUNCTION__, res, strerror(-res));
5670 return res;
5671 }
5672 mCancelNow = false;
5673 mActive = true;
5674 ALOGV("%s: Preparer stream started", __FUNCTION__);
5675
5676 return OK;
5677}
5678
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005679status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005680 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005681 Mutex::Autolock l(mLock);
5682
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005683 for (const auto& it : mPendingStreams) {
5684 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005685 }
5686 mPendingStreams.clear();
5687 mCancelNow = true;
5688
5689 return OK;
5690}
5691
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005692void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005693 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005694 Mutex::Autolock l(mLock);
5695 mListener = listener;
5696}
5697
5698bool Camera3Device::PreparerThread::threadLoop() {
5699 status_t res;
5700 {
5701 Mutex::Autolock l(mLock);
5702 if (mCurrentStream == nullptr) {
5703 // End thread if done with work
5704 if (mPendingStreams.empty()) {
5705 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5706 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5707 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5708 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005709 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005710 return false;
5711 }
5712
5713 // Get next stream to prepare
5714 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005715 mCurrentStream = it->second;
5716 mCurrentMaxCount = it->first;
5717 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005718 mPendingStreams.erase(it);
5719 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5720 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5721 } else if (mCancelNow) {
5722 mCurrentStream->cancelPrepare();
5723 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5724 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5725 mCurrentStream.clear();
5726 mCancelNow = false;
5727 return true;
5728 }
5729 }
5730
5731 res = mCurrentStream->prepareNextBuffer();
5732 if (res == NOT_ENOUGH_DATA) return true;
5733 if (res != OK) {
5734 // Something bad happened; try to recover by cancelling prepare and
5735 // signalling listener anyway
5736 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5737 mCurrentStream->getId(), res, strerror(-res));
5738 mCurrentStream->cancelPrepare();
5739 }
5740
5741 // This stream has finished, notify listener
5742 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005743 sp<NotificationListener> listener = mListener.promote();
5744 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005745 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5746 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005747 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005748 }
5749
5750 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5751 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005752 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005753
5754 return true;
5755}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005756
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005757/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005758 * Static callback forwarding methods from HAL to instance
5759 */
5760
5761void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5762 const camera3_capture_result *result) {
5763 Camera3Device *d =
5764 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005765
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005766 d->processCaptureResult(result);
5767}
5768
5769void Camera3Device::sNotify(const camera3_callback_ops *cb,
5770 const camera3_notify_msg *msg) {
5771 Camera3Device *d =
5772 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5773 d->notify(msg);
5774}
5775
5776}; // namespace android