blob: 786fd7f3b944ef5e933c82aae59e6ec7f8f9addc [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());
Yin-Chia Yehc5248132018-08-15 12:19:20 -070093 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080094}
95
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080096const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080097 return mId;
98}
99
Emilian Peevbd8c5032018-02-14 23:05:40 +0000100status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ATRACE_CALL();
102 Mutex::Autolock il(mInterfaceLock);
103 Mutex::Autolock l(mLock);
104
105 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
106 if (mStatus != STATUS_UNINITIALIZED) {
107 CLOGE("Already initialized!");
108 return INVALID_OPERATION;
109 }
110 if (manager == nullptr) return INVALID_OPERATION;
111
112 sp<ICameraDeviceSession> session;
113 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800114 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115 /*out*/ &session);
116 ATRACE_END();
117 if (res != OK) {
118 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
119 return res;
120 }
121
Steven Moreland5ff9c912017-03-09 23:13:00 -0800122 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700124 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125 session->close();
126 return res;
127 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800128
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700129 std::vector<std::string> physicalCameraIds;
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() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700278 return disconnectImpl();
279}
280
281status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800282 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700283 Mutex::Autolock il(mInterfaceLock);
Emilian Peev26d975d2018-07-05 14:52:57 +0100284 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800285
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700286 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800287
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700288 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700289 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700290 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700291 {
292 Mutex::Autolock l(mLock);
293 if (mStatus == STATUS_UNINITIALIZED) return res;
294
295 if (mStatus == STATUS_ACTIVE ||
296 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
297 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700298 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700299 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700300 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700301 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700302 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700303 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700304 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
305 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700306 // Continue to close device even in case of error
307 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700308 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800309 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800310
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700311 if (mStatus == STATUS_ERROR) {
312 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700313 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700314
315 if (mStatusTracker != NULL) {
316 mStatusTracker->requestExit();
317 }
318
319 if (mRequestThread != NULL) {
320 mRequestThread->requestExit();
321 }
322
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700323 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
324 for (size_t i = 0; i < mOutputStreams.size(); i++) {
325 streams.push_back(mOutputStreams[i]);
326 }
327 if (mInputStream != nullptr) {
328 streams.push_back(mInputStream);
329 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700330 }
331
332 // Joining done without holding mLock, otherwise deadlocks may ensue
333 // as the threads try to access parent state
334 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
335 // HAL may be in a bad state, so waiting for request thread
336 // (which may be stuck in the HAL processCaptureRequest call)
337 // could be dangerous.
338 mRequestThread->join();
339 }
340
341 if (mStatusTracker != NULL) {
342 mStatusTracker->join();
343 }
344
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800345 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700346 {
347 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800348 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700349 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800350 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700351 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800352
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700353 // Call close without internal mutex held, as the HAL close may need to
354 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800355 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700356
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700357 flushInflightRequests();
358
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700359 {
360 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800361 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700362 mOutputStreams.clear();
363 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700364 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700365 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700366 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700367 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800368
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700369 for (auto& weakStream : streams) {
370 sp<Camera3StreamInterface> stream = weakStream.promote();
371 if (stream != nullptr) {
372 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
373 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
374 }
375 }
376
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700377 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700378 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800379}
380
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700381// For dumping/debugging only -
382// try to acquire a lock a few times, eventually give up to proceed with
383// debug/dump operations
384bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
385 bool gotLock = false;
386 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
387 if (lock.tryLock() == NO_ERROR) {
388 gotLock = true;
389 break;
390 } else {
391 usleep(kDumpSleepDuration);
392 }
393 }
394 return gotLock;
395}
396
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700397Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
398 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100399 const int STREAM_CONFIGURATION_SIZE = 4;
400 const int STREAM_FORMAT_OFFSET = 0;
401 const int STREAM_WIDTH_OFFSET = 1;
402 const int STREAM_HEIGHT_OFFSET = 2;
403 const int STREAM_IS_INPUT_OFFSET = 3;
404 camera_metadata_ro_entry_t availableStreamConfigs =
405 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
406 if (availableStreamConfigs.count == 0 ||
407 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
408 return Size(0, 0);
409 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700410
Emilian Peev08dd2452017-04-06 16:55:14 +0100411 // Get max jpeg size (area-wise).
412 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
413 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
414 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
415 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
416 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
417 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
418 && format == HAL_PIXEL_FORMAT_BLOB &&
419 (width * height > maxJpegWidth * maxJpegHeight)) {
420 maxJpegWidth = width;
421 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700422 }
423 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100424
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700425 return Size(maxJpegWidth, maxJpegHeight);
426}
427
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800428nsecs_t Camera3Device::getMonoToBoottimeOffset() {
429 // try three times to get the clock offset, choose the one
430 // with the minimum gap in measurements.
431 const int tries = 3;
432 nsecs_t bestGap, measured;
433 for (int i = 0; i < tries; ++i) {
434 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
435 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
436 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
437 const nsecs_t gap = tmono2 - tmono;
438 if (i == 0 || gap < bestGap) {
439 bestGap = gap;
440 measured = tbase - ((tmono + tmono2) >> 1);
441 }
442 }
443 return measured;
444}
445
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800446hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
447 int frameworkFormat) {
448 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
449}
450
451DataspaceFlags Camera3Device::mapToHidlDataspace(
452 android_dataspace dataSpace) {
453 return dataSpace;
454}
455
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700456BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100457 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700458 return usage;
459}
460
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800461StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
462 switch (rotation) {
463 case CAMERA3_STREAM_ROTATION_0:
464 return StreamRotation::ROTATION_0;
465 case CAMERA3_STREAM_ROTATION_90:
466 return StreamRotation::ROTATION_90;
467 case CAMERA3_STREAM_ROTATION_180:
468 return StreamRotation::ROTATION_180;
469 case CAMERA3_STREAM_ROTATION_270:
470 return StreamRotation::ROTATION_270;
471 }
472 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
473 return StreamRotation::ROTATION_0;
474}
475
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800476status_t Camera3Device::mapToStreamConfigurationMode(
477 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
478 if (mode == nullptr) return BAD_VALUE;
479 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
480 switch(operationMode) {
481 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
482 *mode = StreamConfigurationMode::NORMAL_MODE;
483 break;
484 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
485 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
486 break;
487 default:
488 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
489 return BAD_VALUE;
490 }
491 } else {
492 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800493 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800494 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800495}
496
497camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
498 switch (status) {
499 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
500 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
501 }
502 return CAMERA3_BUFFER_STATUS_ERROR;
503}
504
505int Camera3Device::mapToFrameworkFormat(
506 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
507 return static_cast<uint32_t>(pixelFormat);
508}
509
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700510android_dataspace Camera3Device::mapToFrameworkDataspace(
511 DataspaceFlags dataSpace) {
512 return static_cast<android_dataspace>(dataSpace);
513}
514
Emilian Peev050f5dc2017-05-18 14:43:56 +0100515uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700516 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700517 return usage;
518}
519
Emilian Peev050f5dc2017-05-18 14:43:56 +0100520uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700521 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700522 return usage;
523}
524
Zhijun Hef7da0962014-04-24 13:27:56 -0700525ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700526 // Get max jpeg size (area-wise).
527 Size maxJpegResolution = getMaxJpegResolution();
528 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800529 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
530 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700531 return BAD_VALUE;
532 }
533
Zhijun Hef7da0962014-04-24 13:27:56 -0700534 // Get max jpeg buffer size
535 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700536 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
537 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800538 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
539 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700540 return BAD_VALUE;
541 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700542 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800543 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700544
545 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700546 float scaleFactor = ((float) (width * height)) /
547 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800548 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
549 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700550 if (jpegBufferSize > maxJpegBufferSize) {
551 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700552 }
553
554 return jpegBufferSize;
555}
556
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700557ssize_t Camera3Device::getPointCloudBufferSize() const {
558 const int FLOATS_PER_POINT=4;
559 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
560 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800561 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
562 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700563 return BAD_VALUE;
564 }
565 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
566 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
567 return maxBytesForPointCloud;
568}
569
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800570ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800571 const int PER_CONFIGURATION_SIZE = 3;
572 const int WIDTH_OFFSET = 0;
573 const int HEIGHT_OFFSET = 1;
574 const int SIZE_OFFSET = 2;
575 camera_metadata_ro_entry rawOpaqueSizes =
576 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800577 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800578 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800579 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
580 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800581 return BAD_VALUE;
582 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700583
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800584 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
585 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
586 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
587 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
588 }
589 }
590
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800591 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
592 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800593 return BAD_VALUE;
594}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700595
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800596status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
597 ATRACE_CALL();
598 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700599
600 // Try to lock, but continue in case of failure (to avoid blocking in
601 // deadlocks)
602 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
603 bool gotLock = tryLockSpinRightRound(mLock);
604
605 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800606 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
607 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700608 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800609 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
610 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700611
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800612 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700613
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800614 String16 templatesOption("-t");
615 int n = args.size();
616 for (int i = 0; i < n; i++) {
617 if (args[i] == templatesOption) {
618 dumpTemplates = true;
619 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000620 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700621 if (i + 1 < n) {
622 String8 monitorTags = String8(args[i + 1]);
623 if (monitorTags == "off") {
624 mTagMonitor.disableMonitoring();
625 } else {
626 mTagMonitor.parseTagsToMonitor(monitorTags);
627 }
628 } else {
629 mTagMonitor.disableMonitoring();
630 }
631 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800632 }
633
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800634 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800635
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800636 const char *status =
637 mStatus == STATUS_ERROR ? "ERROR" :
638 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700639 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
640 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800641 mStatus == STATUS_ACTIVE ? "ACTIVE" :
642 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700643
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800644 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700645 if (mStatus == STATUS_ERROR) {
646 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
647 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800648 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800649 const char *mode =
650 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
651 mOperatingMode == static_cast<int>(
652 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
653 "CUSTOM";
654 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800655
656 if (mInputStream != NULL) {
657 write(fd, lines.string(), lines.size());
658 mInputStream->dump(fd, args);
659 } else {
660 lines.appendFormat(" No input stream.\n");
661 write(fd, lines.string(), lines.size());
662 }
663 for (size_t i = 0; i < mOutputStreams.size(); i++) {
664 mOutputStreams[i]->dump(fd,args);
665 }
666
Zhijun He431503c2016-03-07 17:30:16 -0800667 if (mBufferManager != NULL) {
668 lines = String8(" Camera3 Buffer Manager:\n");
669 write(fd, lines.string(), lines.size());
670 mBufferManager->dump(fd, args);
671 }
Zhijun He125684a2015-12-26 15:07:30 -0800672
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700673 lines = String8(" In-flight requests:\n");
674 if (mInFlightMap.size() == 0) {
675 lines.append(" None\n");
676 } else {
677 for (size_t i = 0; i < mInFlightMap.size(); i++) {
678 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700679 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700680 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800681 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700682 r.numBuffersLeft);
683 }
684 }
685 write(fd, lines.string(), lines.size());
686
Shuzhen Wang686f6442017-06-20 16:16:04 -0700687 if (mRequestThread != NULL) {
688 mRequestThread->dumpCaptureRequestLatency(fd,
689 " ProcessCaptureRequest latency histogram:");
690 }
691
Igor Murashkin1e479c02013-09-06 16:55:14 -0700692 {
693 lines = String8(" Last request sent:\n");
694 write(fd, lines.string(), lines.size());
695
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700696 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700697 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
698 }
699
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800700 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800701 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800702 "TEMPLATE_PREVIEW",
703 "TEMPLATE_STILL_CAPTURE",
704 "TEMPLATE_VIDEO_RECORD",
705 "TEMPLATE_VIDEO_SNAPSHOT",
706 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800707 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800708 };
709
710 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800711 camera_metadata_t *templateRequest = nullptr;
712 mInterface->constructDefaultRequestSettings(
713 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800714 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800715 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800716 lines.append(" Not supported\n");
717 write(fd, lines.string(), lines.size());
718 } else {
719 write(fd, lines.string(), lines.size());
720 dump_indented_camera_metadata(templateRequest,
721 fd, /*verbosity*/2, /*indentation*/8);
722 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800723 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800724 }
725 }
726
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700727 mTagMonitor.dumpMonitoredMetadata(fd);
728
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800729 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800730 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800731 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800732 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800733 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800734
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700735 if (gotLock) mLock.unlock();
736 if (gotInterfaceLock) mInterfaceLock.unlock();
737
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800738 return OK;
739}
740
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700741const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800742 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800743 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
744 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700745 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800746 mStatus == STATUS_ERROR ?
747 "when in error state" : "before init");
748 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700749 if (physicalId.isEmpty()) {
750 return mDeviceInfo;
751 } else {
752 std::string id(physicalId.c_str());
753 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
754 return mPhysicalDeviceInfoMap.at(id);
755 } else {
756 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
757 return mDeviceInfo;
758 }
759 }
760}
761
762const CameraMetadata& Camera3Device::info() const {
763 String8 emptyId;
764 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800765}
766
Jianing Wei90e59c92014-03-12 18:29:36 -0700767status_t Camera3Device::checkStatusOkToCaptureLocked() {
768 switch (mStatus) {
769 case STATUS_ERROR:
770 CLOGE("Device has encountered a serious error");
771 return INVALID_OPERATION;
772 case STATUS_UNINITIALIZED:
773 CLOGE("Device not initialized");
774 return INVALID_OPERATION;
775 case STATUS_UNCONFIGURED:
776 case STATUS_CONFIGURED:
777 case STATUS_ACTIVE:
778 // OK
779 break;
780 default:
781 SET_ERR_L("Unexpected status: %d", mStatus);
782 return INVALID_OPERATION;
783 }
784 return OK;
785}
786
787status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000788 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700789 const std::list<const SurfaceMap> &surfaceMaps,
790 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700791 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700792 if (requestList == NULL) {
793 CLOGE("requestList cannot be NULL.");
794 return BAD_VALUE;
795 }
796
Jianing Weicb0652e2014-03-12 18:29:36 -0700797 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000798 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700799 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
800 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
801 ++metadataIt, ++surfaceMapIt) {
802 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700803 if (newRequest == 0) {
804 CLOGE("Can't create capture request");
805 return BAD_VALUE;
806 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700807
Shuzhen Wang9d066012016-09-30 11:30:20 -0700808 newRequest->mRepeating = repeating;
809
Jianing Weicb0652e2014-03-12 18:29:36 -0700810 // Setup burst Id and request Id
811 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000812 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
813 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700814 CLOGE("RequestID entry exists; but must not be empty in metadata");
815 return BAD_VALUE;
816 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000817 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
818 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700819 } else {
820 CLOGE("RequestID does not exist in metadata");
821 return BAD_VALUE;
822 }
823
Jianing Wei90e59c92014-03-12 18:29:36 -0700824 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700825
826 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700827 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700828 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
829 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
830 return BAD_VALUE;
831 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700832
833 // Setup batch size if this is a high speed video recording request.
834 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
835 auto firstRequest = requestList->begin();
836 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
837 if (outputStream->isVideoStream()) {
838 (*firstRequest)->mBatchSize = requestList->size();
839 break;
840 }
841 }
842 }
843
Jianing Wei90e59c92014-03-12 18:29:36 -0700844 return OK;
845}
846
Jianing Weicb0652e2014-03-12 18:29:36 -0700847status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800848 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800849
Emilian Peevaebbe412018-01-15 13:53:24 +0000850 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700851 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000852 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700853
Emilian Peevaebbe412018-01-15 13:53:24 +0000854 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700855}
856
Emilian Peevaebbe412018-01-15 13:53:24 +0000857void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700858 std::list<const SurfaceMap>& surfaceMaps,
859 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000860 PhysicalCameraSettingsList requestList;
861 requestList.push_back({std::string(getId().string()), request});
862 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700863
864 SurfaceMap surfaceMap;
865 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
866 // With no surface list passed in, stream and surface will have 1-to-1
867 // mapping. So the surface index is 0 for each stream in the surfaceMap.
868 for (size_t i = 0; i < streams.count; i++) {
869 surfaceMap[streams.data.i32[i]].push_back(0);
870 }
871 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800872}
873
Jianing Wei90e59c92014-03-12 18:29:36 -0700874status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000875 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700876 const std::list<const SurfaceMap> &surfaceMaps,
877 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700878 /*out*/
879 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700880 ATRACE_CALL();
881 Mutex::Autolock il(mInterfaceLock);
882 Mutex::Autolock l(mLock);
883
884 status_t res = checkStatusOkToCaptureLocked();
885 if (res != OK) {
886 // error logged by previous call
887 return res;
888 }
889
890 RequestList requestList;
891
Shuzhen Wang0129d522016-10-30 22:43:41 -0700892 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
893 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700894 if (res != OK) {
895 // error logged by previous call
896 return res;
897 }
898
899 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700900 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700901 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700902 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700903 }
904
905 if (res == OK) {
906 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
907 if (res != OK) {
908 SET_ERR_L("Can't transition to active in %f seconds!",
909 kActiveTimeout/1e9);
910 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800911 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700912 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700913 } else {
914 CLOGE("Cannot queue request. Impossible.");
915 return BAD_VALUE;
916 }
917
918 return res;
919}
920
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800921hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800922 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800923 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700924 // Ideally we should grab mLock, but that can lead to deadlock, and
925 // it's not super important to get up to date value of mStatus for this
926 // warning print, hence skipping the lock here
927 if (mStatus == STATUS_ERROR) {
928 // Per API contract, HAL should act as closed after device error
929 // But mStatus can be set to error by framework as well, so just log
930 // a warning here.
931 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700932 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700933
934 if (mProcessCaptureResultLock.tryLock() != OK) {
935 // This should never happen; it indicates a wrong client implementation
936 // that doesn't follow the contract. But, we can be tolerant here.
937 ALOGE("%s: callback overlapped! waiting 1s...",
938 __FUNCTION__);
939 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
940 ALOGE("%s: cannot acquire lock in 1s, dropping results",
941 __FUNCTION__);
942 // really don't know what to do, so bail out.
943 return hardware::Void();
944 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800945 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700946 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800947 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -0700948 }
949 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800950 return hardware::Void();
951}
952
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800953// Only one processCaptureResult should be called at a time, so
954// the locks won't block. The locks are present here simply to enforce this.
955hardware::Return<void> Camera3Device::processCaptureResult(
956 const hardware::hidl_vec<
957 hardware::camera::device::V3_2::CaptureResult>& results) {
958 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
959
960 // Ideally we should grab mLock, but that can lead to deadlock, and
961 // it's not super important to get up to date value of mStatus for this
962 // warning print, hence skipping the lock here
963 if (mStatus == STATUS_ERROR) {
964 // Per API contract, HAL should act as closed after device error
965 // But mStatus can be set to error by framework as well, so just log
966 // a warning here.
967 ALOGW("%s: received capture result in error state.", __FUNCTION__);
968 }
969
970 if (mProcessCaptureResultLock.tryLock() != OK) {
971 // This should never happen; it indicates a wrong client implementation
972 // that doesn't follow the contract. But, we can be tolerant here.
973 ALOGE("%s: callback overlapped! waiting 1s...",
974 __FUNCTION__);
975 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
976 ALOGE("%s: cannot acquire lock in 1s, dropping results",
977 __FUNCTION__);
978 // really don't know what to do, so bail out.
979 return hardware::Void();
980 }
981 }
982 for (const auto& result : results) {
983 processOneCaptureResultLocked(result, noPhysMetadata);
984 }
985 mProcessCaptureResultLock.unlock();
986 return hardware::Void();
987}
988
989status_t Camera3Device::readOneCameraMetadataLocked(
990 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
991 const hardware::camera::device::V3_2::CameraMetadata& result) {
992 if (fmqResultSize > 0) {
993 resultMetadata.resize(fmqResultSize);
994 if (mResultMetadataQueue == nullptr) {
995 return NO_MEMORY; // logged in initialize()
996 }
997 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
998 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
999 __FUNCTION__, fmqResultSize);
1000 return INVALID_OPERATION;
1001 }
1002 } else {
1003 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1004 result.size());
1005 }
1006
1007 if (resultMetadata.size() != 0) {
1008 status_t res;
1009 const camera_metadata_t* metadata =
1010 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1011 size_t expected_metadata_size = resultMetadata.size();
1012 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1013 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1014 __FUNCTION__, strerror(-res), res);
1015 return INVALID_OPERATION;
1016 }
1017 }
1018
1019 return OK;
1020}
1021
Yifan Honga640c5a2017-04-12 16:30:31 -07001022void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001023 const hardware::camera::device::V3_2::CaptureResult& result,
1024 const hardware::hidl_vec<
1025 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001026 camera3_capture_result r;
1027 status_t res;
1028 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001029
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001030 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001031 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001032 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1033 if (res != OK) {
1034 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1035 __FUNCTION__, result.frameNumber);
1036 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001037 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001038 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001039
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001040 // Read and validate physical camera metadata
1041 size_t physResultCount = physicalCameraMetadatas.size();
1042 std::vector<const char*> physCamIds(physResultCount);
1043 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1044 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1045 physResultMetadata.resize(physResultCount);
1046 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1047 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1048 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1049 if (res != OK) {
1050 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1051 __FUNCTION__, result.frameNumber,
1052 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001053 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001054 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001055 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1056 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1057 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001058 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001059 r.num_physcam_metadata = physResultCount;
1060 r.physcam_ids = physCamIds.data();
1061 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001062
1063 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1064 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1065 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1066 auto& bDst = outputBuffers[i];
1067 const StreamBuffer &bSrc = result.outputBuffers[i];
1068
1069 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001070 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001071 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1072 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001073 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001074 }
1075 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
1076
1077 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08001078 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001079 if (res != OK) {
1080 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1081 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001082 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001083 }
1084 bDst.buffer = buffer;
1085 bDst.status = mapHidlBufferStatus(bSrc.status);
1086 bDst.acquire_fence = -1;
1087 if (bSrc.releaseFence == nullptr) {
1088 bDst.release_fence = -1;
1089 } else if (bSrc.releaseFence->numFds == 1) {
1090 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1091 } else {
1092 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1093 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001094 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001095 }
1096 }
1097 r.num_output_buffers = outputBuffers.size();
1098 r.output_buffers = outputBuffers.data();
1099
1100 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001101 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001102 r.input_buffer = nullptr;
1103 } else {
1104 if (mInputStream->getId() != result.inputBuffer.streamId) {
1105 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1106 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001107 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001108 }
1109 inputBuffer.stream = mInputStream->asHalStream();
1110 buffer_handle_t *buffer;
1111 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1112 &buffer);
1113 if (res != OK) {
1114 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1115 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001116 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001117 }
1118 inputBuffer.buffer = buffer;
1119 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1120 inputBuffer.acquire_fence = -1;
1121 if (result.inputBuffer.releaseFence == nullptr) {
1122 inputBuffer.release_fence = -1;
1123 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1124 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1125 } else {
1126 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1127 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001128 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001129 }
1130 r.input_buffer = &inputBuffer;
1131 }
1132
1133 r.partial_result = result.partialResult;
1134
1135 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001136}
1137
1138hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001139 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001140 // Ideally we should grab mLock, but that can lead to deadlock, and
1141 // it's not super important to get up to date value of mStatus for this
1142 // warning print, hence skipping the lock here
1143 if (mStatus == STATUS_ERROR) {
1144 // Per API contract, HAL should act as closed after device error
1145 // But mStatus can be set to error by framework as well, so just log
1146 // a warning here.
1147 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001148 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001149
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001150 for (const auto& msg : msgs) {
1151 notify(msg);
1152 }
1153 return hardware::Void();
1154}
1155
1156void Camera3Device::notify(
1157 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1158
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001159 camera3_notify_msg m;
1160 switch (msg.type) {
1161 case MsgType::ERROR:
1162 m.type = CAMERA3_MSG_ERROR;
1163 m.message.error.frame_number = msg.msg.error.frameNumber;
1164 if (msg.msg.error.errorStreamId >= 0) {
1165 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001166 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001167 ALOGE("%s: Frame %d: Invalid error stream id %d",
1168 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001169 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001170 }
1171 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1172 } else {
1173 m.message.error.error_stream = nullptr;
1174 }
1175 switch (msg.msg.error.errorCode) {
1176 case ErrorCode::ERROR_DEVICE:
1177 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1178 break;
1179 case ErrorCode::ERROR_REQUEST:
1180 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1181 break;
1182 case ErrorCode::ERROR_RESULT:
1183 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1184 break;
1185 case ErrorCode::ERROR_BUFFER:
1186 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1187 break;
1188 }
1189 break;
1190 case MsgType::SHUTTER:
1191 m.type = CAMERA3_MSG_SHUTTER;
1192 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1193 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1194 break;
1195 }
1196 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001197}
1198
Emilian Peevaebbe412018-01-15 13:53:24 +00001199status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001200 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001201 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001202 ATRACE_CALL();
1203
Emilian Peevaebbe412018-01-15 13:53:24 +00001204 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001205}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001206
Jianing Weicb0652e2014-03-12 18:29:36 -07001207status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1208 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001209 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001210
Emilian Peevaebbe412018-01-15 13:53:24 +00001211 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001212 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001213 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001214
Emilian Peevaebbe412018-01-15 13:53:24 +00001215 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001216 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001217}
1218
Emilian Peevaebbe412018-01-15 13:53:24 +00001219status_t Camera3Device::setStreamingRequestList(
1220 const List<const PhysicalCameraSettingsList> &requestsList,
1221 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001222 ATRACE_CALL();
1223
Emilian Peevaebbe412018-01-15 13:53:24 +00001224 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001225}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001226
1227sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001228 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001229 status_t res;
1230
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001231 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001232 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1233 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001234 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1235 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001236 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001237 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001238 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001239 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001240 } else if (mStatus == STATUS_UNCONFIGURED) {
1241 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001242 CLOGE("No streams configured");
1243 return NULL;
1244 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001245 }
1246
Shuzhen Wang0129d522016-10-30 22:43:41 -07001247 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001248 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001249}
1250
Jianing Weicb0652e2014-03-12 18:29:36 -07001251status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001252 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001253 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001254 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001255
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001256 switch (mStatus) {
1257 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001258 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001259 return INVALID_OPERATION;
1260 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001261 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001262 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001263 case STATUS_UNCONFIGURED:
1264 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001265 case STATUS_ACTIVE:
1266 // OK
1267 break;
1268 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001269 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001270 return INVALID_OPERATION;
1271 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001272 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001273
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001274 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001275}
1276
1277status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1278 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001279 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001280
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001281 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001282}
1283
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001284status_t Camera3Device::createInputStream(
1285 uint32_t width, uint32_t height, int format, int *id) {
1286 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001287 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001288 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001289 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001290 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1291 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001292
1293 status_t res;
1294 bool wasActive = false;
1295
1296 switch (mStatus) {
1297 case STATUS_ERROR:
1298 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1299 return INVALID_OPERATION;
1300 case STATUS_UNINITIALIZED:
1301 ALOGE("%s: Device not initialized", __FUNCTION__);
1302 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001303 case STATUS_UNCONFIGURED:
1304 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001305 // OK
1306 break;
1307 case STATUS_ACTIVE:
1308 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001309 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001310 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001311 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001312 return res;
1313 }
1314 wasActive = true;
1315 break;
1316 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001317 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001318 return INVALID_OPERATION;
1319 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001320 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001321
1322 if (mInputStream != 0) {
1323 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1324 return INVALID_OPERATION;
1325 }
1326
1327 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1328 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001329 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001330
1331 mInputStream = newStream;
1332
1333 *id = mNextStreamId++;
1334
1335 // Continue captures if active at start
1336 if (wasActive) {
1337 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001338 // Reuse current operating mode and session parameters for new stream config
1339 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001340 if (res != OK) {
1341 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1342 __FUNCTION__, mNextStreamId, strerror(-res), res);
1343 return res;
1344 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001345 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001346 }
1347
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001348 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001349 return OK;
1350}
1351
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001352status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001353 uint32_t width, uint32_t height, int format,
1354 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001355 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001356 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001357 ATRACE_CALL();
1358
1359 if (consumer == nullptr) {
1360 ALOGE("%s: consumer must not be null", __FUNCTION__);
1361 return BAD_VALUE;
1362 }
1363
1364 std::vector<sp<Surface>> consumers;
1365 consumers.push_back(consumer);
1366
1367 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001368 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1369 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001370}
1371
1372status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1373 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1374 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001375 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001376 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001377 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001378
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001379 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001380 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001381 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001382 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001383 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1384 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1385 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001386
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001387 status_t res;
1388 bool wasActive = false;
1389
1390 switch (mStatus) {
1391 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001392 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001393 return INVALID_OPERATION;
1394 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001395 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001396 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001397 case STATUS_UNCONFIGURED:
1398 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001399 // OK
1400 break;
1401 case STATUS_ACTIVE:
1402 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001403 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001404 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001405 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001406 return res;
1407 }
1408 wasActive = true;
1409 break;
1410 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001411 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001412 return INVALID_OPERATION;
1413 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001414 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001415
1416 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001417
Shuzhen Wang0129d522016-10-30 22:43:41 -07001418 if (consumers.size() == 0 && !hasDeferredConsumer) {
1419 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1420 return BAD_VALUE;
1421 }
Zhijun He5d677d12016-05-29 16:52:39 -07001422
Shuzhen Wang0129d522016-10-30 22:43:41 -07001423 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001424 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1425 return BAD_VALUE;
1426 }
1427
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001428 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001429 ssize_t blobBufferSize;
1430 if (dataSpace != HAL_DATASPACE_DEPTH) {
1431 blobBufferSize = getJpegBufferSize(width, height);
1432 if (blobBufferSize <= 0) {
1433 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1434 return BAD_VALUE;
1435 }
1436 } else {
1437 blobBufferSize = getPointCloudBufferSize();
1438 if (blobBufferSize <= 0) {
1439 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1440 return BAD_VALUE;
1441 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001442 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001443 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001444 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001445 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001446 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1447 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1448 if (rawOpaqueBufferSize <= 0) {
1449 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1450 return BAD_VALUE;
1451 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001452 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001453 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001454 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001455 } else if (isShared) {
1456 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1457 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001458 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001459 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001460 newStream = new Camera3OutputStream(mNextStreamId,
1461 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001462 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001463 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001464 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001465 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001466 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001467 }
Emilian Peev40ead602017-09-26 15:46:36 +01001468
1469 size_t consumerCount = consumers.size();
1470 for (size_t i = 0; i < consumerCount; i++) {
1471 int id = newStream->getSurfaceId(consumers[i]);
1472 if (id < 0) {
1473 SET_ERR_L("Invalid surface id");
1474 return BAD_VALUE;
1475 }
1476 if (surfaceIds != nullptr) {
1477 surfaceIds->push_back(id);
1478 }
1479 }
1480
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001481 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001482
Emilian Peev08dd2452017-04-06 16:55:14 +01001483 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001484
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001485 res = mOutputStreams.add(mNextStreamId, newStream);
1486 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001487 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001488 return res;
1489 }
1490
1491 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001492 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001493
1494 // Continue captures if active at start
1495 if (wasActive) {
1496 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001497 // Reuse current operating mode and session parameters for new stream config
1498 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001499 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001500 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1501 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001502 return res;
1503 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001504 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001505 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001506 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001507 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001508}
1509
Emilian Peev710c1422017-08-30 11:19:38 +01001510status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001511 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001512 if (nullptr == streamInfo) {
1513 return BAD_VALUE;
1514 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001515 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001516 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001517
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001518 switch (mStatus) {
1519 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001520 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001521 return INVALID_OPERATION;
1522 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001523 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001524 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001525 case STATUS_UNCONFIGURED:
1526 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001527 case STATUS_ACTIVE:
1528 // OK
1529 break;
1530 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001531 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001532 return INVALID_OPERATION;
1533 }
1534
1535 ssize_t idx = mOutputStreams.indexOfKey(id);
1536 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001537 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 return idx;
1539 }
1540
Emilian Peev710c1422017-08-30 11:19:38 +01001541 streamInfo->width = mOutputStreams[idx]->getWidth();
1542 streamInfo->height = mOutputStreams[idx]->getHeight();
1543 streamInfo->format = mOutputStreams[idx]->getFormat();
1544 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1545 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1546 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001547 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1548 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001549 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001550}
1551
1552status_t Camera3Device::setStreamTransform(int id,
1553 int transform) {
1554 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001555 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001557
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 switch (mStatus) {
1559 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001560 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001561 return INVALID_OPERATION;
1562 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001563 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001564 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001565 case STATUS_UNCONFIGURED:
1566 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001567 case STATUS_ACTIVE:
1568 // OK
1569 break;
1570 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001571 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001572 return INVALID_OPERATION;
1573 }
1574
1575 ssize_t idx = mOutputStreams.indexOfKey(id);
1576 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001577 CLOGE("Stream %d does not exist",
1578 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001579 return BAD_VALUE;
1580 }
1581
1582 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001583}
1584
1585status_t Camera3Device::deleteStream(int id) {
1586 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001587 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001588 Mutex::Autolock l(mLock);
1589 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001590
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001591 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001592
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001593 // CameraDevice semantics require device to already be idle before
1594 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001595 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001596 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001597 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001598 }
1599
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001600 if (mStatus == STATUS_ERROR) {
1601 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1602 __FUNCTION__, mId.string());
1603 return -EBUSY;
1604 }
1605
Igor Murashkin2fba5842013-04-22 14:03:54 -07001606 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001607 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001608 if (mInputStream != NULL && id == mInputStream->getId()) {
1609 deletedStream = mInputStream;
1610 mInputStream.clear();
1611 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001612 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001613 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001614 return BAD_VALUE;
1615 }
Zhijun He5f446352014-01-22 09:49:33 -08001616 }
1617
1618 // Delete output stream or the output part of a bi-directional stream.
1619 if (outputStreamIdx != NAME_NOT_FOUND) {
1620 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001621 mOutputStreams.removeItem(id);
1622 }
1623
1624 // Free up the stream endpoint so that it can be used by some other stream
1625 res = deletedStream->disconnect();
1626 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001627 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001628 // fall through since we want to still list the stream as deleted.
1629 }
1630 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001631 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001632
1633 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001634}
1635
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001636status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001637 ATRACE_CALL();
1638 ALOGV("%s: E", __FUNCTION__);
1639
1640 Mutex::Autolock il(mInterfaceLock);
1641 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001642
Emilian Peev811d2952018-05-25 11:08:40 +01001643 // In case the client doesn't include any session parameter, try a
1644 // speculative configuration using the values from the last cached
1645 // default request.
1646 if (sessionParams.isEmpty() &&
1647 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1648 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1649 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1650 mLastTemplateId);
1651 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1652 operatingMode);
1653 }
1654
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001655 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1656}
1657
1658status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1659 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001660 //Filter out any incoming session parameters
1661 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001662 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1663 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001664 CameraMetadata filteredParams(availableSessionKeys.count);
1665 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1666 filteredParams.getAndLock());
1667 set_camera_metadata_vendor_id(meta, mVendorTagId);
1668 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001669 if (availableSessionKeys.count > 0) {
1670 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1671 camera_metadata_ro_entry entry = params.find(
1672 availableSessionKeys.data.i32[i]);
1673 if (entry.count > 0) {
1674 filteredParams.update(entry);
1675 }
1676 }
1677 }
1678
1679 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001680}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001681
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001682status_t Camera3Device::getInputBufferProducer(
1683 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001684 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001685 Mutex::Autolock il(mInterfaceLock);
1686 Mutex::Autolock l(mLock);
1687
1688 if (producer == NULL) {
1689 return BAD_VALUE;
1690 } else if (mInputStream == NULL) {
1691 return INVALID_OPERATION;
1692 }
1693
1694 return mInputStream->getInputBufferProducer(producer);
1695}
1696
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001697status_t Camera3Device::createDefaultRequest(int templateId,
1698 CameraMetadata *request) {
1699 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001700 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001701
1702 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1703 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1704 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1705 return BAD_VALUE;
1706 }
1707
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001708 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001709
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001710 {
1711 Mutex::Autolock l(mLock);
1712 switch (mStatus) {
1713 case STATUS_ERROR:
1714 CLOGE("Device has encountered a serious error");
1715 return INVALID_OPERATION;
1716 case STATUS_UNINITIALIZED:
1717 CLOGE("Device is not initialized!");
1718 return INVALID_OPERATION;
1719 case STATUS_UNCONFIGURED:
1720 case STATUS_CONFIGURED:
1721 case STATUS_ACTIVE:
1722 // OK
1723 break;
1724 default:
1725 SET_ERR_L("Unexpected status: %d", mStatus);
1726 return INVALID_OPERATION;
1727 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001728
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001729 if (!mRequestTemplateCache[templateId].isEmpty()) {
1730 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001731 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001732 return OK;
1733 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001734 }
1735
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001736 camera_metadata_t *rawRequest;
1737 status_t res = mInterface->constructDefaultRequestSettings(
1738 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001739
1740 {
1741 Mutex::Autolock l(mLock);
1742 if (res == BAD_VALUE) {
1743 ALOGI("%s: template %d is not supported on this camera device",
1744 __FUNCTION__, templateId);
1745 return res;
1746 } else if (res != OK) {
1747 CLOGE("Unable to construct request template %d: %s (%d)",
1748 templateId, strerror(-res), res);
1749 return res;
1750 }
1751
1752 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1753 mRequestTemplateCache[templateId].acquire(rawRequest);
1754
1755 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001756 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001757 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001758 return OK;
1759}
1760
1761status_t Camera3Device::waitUntilDrained() {
1762 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001763 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001764 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001765 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001766
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001767 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001768}
1769
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001770status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001771 switch (mStatus) {
1772 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001773 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001774 ALOGV("%s: Already idle", __FUNCTION__);
1775 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001776 case STATUS_CONFIGURED:
1777 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001778 case STATUS_ERROR:
1779 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001780 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001781 break;
1782 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001783 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001784 return INVALID_OPERATION;
1785 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001786 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1787 maxExpectedDuration);
1788 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001789 if (res != OK) {
1790 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1791 res);
1792 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001793 return res;
1794}
1795
Ruben Brunk183f0562015-08-12 12:55:02 -07001796
1797void Camera3Device::internalUpdateStatusLocked(Status status) {
1798 mStatus = status;
1799 mRecentStatusUpdates.add(mStatus);
1800 mStatusChanged.broadcast();
1801}
1802
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001803void Camera3Device::pauseStateNotify(bool enable) {
1804 Mutex::Autolock il(mInterfaceLock);
1805 Mutex::Autolock l(mLock);
1806
1807 mPauseStateNotify = enable;
1808}
1809
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001810// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001811status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001812 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001813
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001814 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1815 maxExpectedDuration);
1816 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001817 if (res != OK) {
1818 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001819 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001820 }
1821
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001822 return res;
1823}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001824
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001825// Resume after internalPauseAndWaitLocked
1826status_t Camera3Device::internalResumeLocked() {
1827 status_t res;
1828
1829 mRequestThread->setPaused(false);
1830
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001831 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1832 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001833 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1834 if (res != OK) {
1835 SET_ERR_L("Can't transition to active in %f seconds!",
1836 kActiveTimeout/1e9);
1837 }
1838 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001839 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001840}
1841
Ruben Brunk183f0562015-08-12 12:55:02 -07001842status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001843 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001844
1845 size_t startIndex = 0;
1846 if (mStatusWaiters == 0) {
1847 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1848 // this status list
1849 mRecentStatusUpdates.clear();
1850 } else {
1851 // If other threads are waiting on updates to this status list, set the position of the
1852 // first element that this list will check rather than clearing the list.
1853 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001854 }
1855
Ruben Brunk183f0562015-08-12 12:55:02 -07001856 mStatusWaiters++;
1857
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001858 bool stateSeen = false;
1859 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001860 if (active == (mStatus == STATUS_ACTIVE)) {
1861 // Desired state is current
1862 break;
1863 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001864
1865 res = mStatusChanged.waitRelative(mLock, timeout);
1866 if (res != OK) break;
1867
Ruben Brunk183f0562015-08-12 12:55:02 -07001868 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1869 // transitions.
1870 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1871 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1872 __FUNCTION__);
1873
1874 // Encountered desired state since we began waiting
1875 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001876 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1877 stateSeen = true;
1878 break;
1879 }
1880 }
1881 } while (!stateSeen);
1882
Ruben Brunk183f0562015-08-12 12:55:02 -07001883 mStatusWaiters--;
1884
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001885 return res;
1886}
1887
1888
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001889status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001890 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001891 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001892
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001893 if (listener != NULL && mListener != NULL) {
1894 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1895 }
1896 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001897 mRequestThread->setNotificationListener(listener);
1898 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001899
1900 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001901}
1902
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001903bool Camera3Device::willNotify3A() {
1904 return false;
1905}
1906
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001907status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001908 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001909 status_t res;
1910 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001911
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001912 while (mResultQueue.empty()) {
1913 res = mResultSignal.waitRelative(mOutputLock, timeout);
1914 if (res == TIMED_OUT) {
1915 return res;
1916 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001917 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1918 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001919 return res;
1920 }
1921 }
1922 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001923}
1924
Jianing Weicb0652e2014-03-12 18:29:36 -07001925status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001926 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001927 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001928
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001929 if (mResultQueue.empty()) {
1930 return NOT_ENOUGH_DATA;
1931 }
1932
Jianing Weicb0652e2014-03-12 18:29:36 -07001933 if (frame == NULL) {
1934 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1935 return BAD_VALUE;
1936 }
1937
1938 CaptureResult &result = *(mResultQueue.begin());
1939 frame->mResultExtras = result.mResultExtras;
1940 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001941 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001942 mResultQueue.erase(mResultQueue.begin());
1943
1944 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001945}
1946
1947status_t Camera3Device::triggerAutofocus(uint32_t id) {
1948 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001949 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001950
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001951 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1952 // Mix-in this trigger into the next request and only the next request.
1953 RequestTrigger trigger[] = {
1954 {
1955 ANDROID_CONTROL_AF_TRIGGER,
1956 ANDROID_CONTROL_AF_TRIGGER_START
1957 },
1958 {
1959 ANDROID_CONTROL_AF_TRIGGER_ID,
1960 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001961 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001962 };
1963
1964 return mRequestThread->queueTrigger(trigger,
1965 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001966}
1967
1968status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1969 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001970 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001971
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001972 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1973 // Mix-in this trigger into the next request and only the next request.
1974 RequestTrigger trigger[] = {
1975 {
1976 ANDROID_CONTROL_AF_TRIGGER,
1977 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1978 },
1979 {
1980 ANDROID_CONTROL_AF_TRIGGER_ID,
1981 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001982 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001983 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001984
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001985 return mRequestThread->queueTrigger(trigger,
1986 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001987}
1988
1989status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1990 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001991 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001992
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001993 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1994 // Mix-in this trigger into the next request and only the next request.
1995 RequestTrigger trigger[] = {
1996 {
1997 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1998 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1999 },
2000 {
2001 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2002 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002003 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002004 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002005
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002006 return mRequestThread->queueTrigger(trigger,
2007 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002008}
2009
Jianing Weicb0652e2014-03-12 18:29:36 -07002010status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002011 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002012 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002013 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002014
Zhijun He7ef20392014-04-21 16:04:17 -07002015 {
2016 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002017
2018 // b/116514106 "disconnect()" can get called twice for the same device. The
2019 // camera device will not be initialized during the second run.
2020 if (mStatus == STATUS_UNINITIALIZED) {
2021 return OK;
2022 }
2023
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002024 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002025 }
2026
Emilian Peev08dd2452017-04-06 16:55:14 +01002027 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002028}
2029
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002030status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002031 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2032}
2033
2034status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002035 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002036 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002037 Mutex::Autolock il(mInterfaceLock);
2038 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002039
2040 sp<Camera3StreamInterface> stream;
2041 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2042 if (outputStreamIdx == NAME_NOT_FOUND) {
2043 CLOGE("Stream %d does not exist", streamId);
2044 return BAD_VALUE;
2045 }
2046
2047 stream = mOutputStreams.editValueAt(outputStreamIdx);
2048
2049 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002050 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002051 return BAD_VALUE;
2052 }
2053
2054 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002055 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002056 return BAD_VALUE;
2057 }
2058
Ruben Brunkc78ac262015-08-13 17:58:46 -07002059 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002060}
2061
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002062status_t Camera3Device::tearDown(int streamId) {
2063 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002064 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002065 Mutex::Autolock il(mInterfaceLock);
2066 Mutex::Autolock l(mLock);
2067
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002068 sp<Camera3StreamInterface> stream;
2069 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2070 if (outputStreamIdx == NAME_NOT_FOUND) {
2071 CLOGE("Stream %d does not exist", streamId);
2072 return BAD_VALUE;
2073 }
2074
2075 stream = mOutputStreams.editValueAt(outputStreamIdx);
2076
2077 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2078 CLOGE("Stream %d is a target of a in-progress request", streamId);
2079 return BAD_VALUE;
2080 }
2081
2082 return stream->tearDown();
2083}
2084
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002085status_t Camera3Device::addBufferListenerForStream(int streamId,
2086 wp<Camera3StreamBufferListener> listener) {
2087 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002088 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002089 Mutex::Autolock il(mInterfaceLock);
2090 Mutex::Autolock l(mLock);
2091
2092 sp<Camera3StreamInterface> stream;
2093 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2094 if (outputStreamIdx == NAME_NOT_FOUND) {
2095 CLOGE("Stream %d does not exist", streamId);
2096 return BAD_VALUE;
2097 }
2098
2099 stream = mOutputStreams.editValueAt(outputStreamIdx);
2100 stream->addBufferListener(listener);
2101
2102 return OK;
2103}
2104
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002105/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002106 * Methods called by subclasses
2107 */
2108
2109void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002110 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002111 {
2112 // Need mLock to safely update state and synchronize to current
2113 // state of methods in flight.
2114 Mutex::Autolock l(mLock);
2115 // We can get various system-idle notices from the status tracker
2116 // while starting up. Only care about them if we've actually sent
2117 // in some requests recently.
2118 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2119 return;
2120 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002121 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2122 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002123 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002124
2125 // Skip notifying listener if we're doing some user-transparent
2126 // state changes
2127 if (mPauseStateNotify) return;
2128 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002129
2130 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002131 {
2132 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002133 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002134 }
2135 if (idle && listener != NULL) {
2136 listener->notifyIdle();
2137 }
2138}
2139
Shuzhen Wang758c2152017-01-10 18:26:18 -08002140status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002141 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002142 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002143 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2144 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002145
2146 if (surfaceIds == nullptr) {
2147 return BAD_VALUE;
2148 }
2149
Zhijun He5d677d12016-05-29 16:52:39 -07002150 Mutex::Autolock il(mInterfaceLock);
2151 Mutex::Autolock l(mLock);
2152
Shuzhen Wang758c2152017-01-10 18:26:18 -08002153 if (consumers.size() == 0) {
2154 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002155 return BAD_VALUE;
2156 }
2157
2158 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2159 if (idx == NAME_NOT_FOUND) {
2160 CLOGE("Stream %d is unknown", streamId);
2161 return idx;
2162 }
2163 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002164 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002165 if (res != OK) {
2166 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2167 return res;
2168 }
2169
Emilian Peev40ead602017-09-26 15:46:36 +01002170 for (auto &consumer : consumers) {
2171 int id = stream->getSurfaceId(consumer);
2172 if (id < 0) {
2173 CLOGE("Invalid surface id!");
2174 return BAD_VALUE;
2175 }
2176 surfaceIds->push_back(id);
2177 }
2178
Shuzhen Wang0129d522016-10-30 22:43:41 -07002179 if (stream->isConsumerConfigurationDeferred()) {
2180 if (!stream->isConfiguring()) {
2181 CLOGE("Stream %d was already fully configured.", streamId);
2182 return INVALID_OPERATION;
2183 }
Zhijun He5d677d12016-05-29 16:52:39 -07002184
Shuzhen Wang0129d522016-10-30 22:43:41 -07002185 res = stream->finishConfiguration();
2186 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002187 // If finishConfiguration fails due to abandoned surface, do not set
2188 // device to error state.
2189 bool isSurfaceAbandoned =
2190 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2191 if (!isSurfaceAbandoned) {
2192 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2193 stream->getId(), strerror(-res), res);
2194 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002195 return res;
2196 }
Zhijun He5d677d12016-05-29 16:52:39 -07002197 }
2198
2199 return OK;
2200}
2201
Emilian Peev40ead602017-09-26 15:46:36 +01002202status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2203 const std::vector<OutputStreamInfo> &outputInfo,
2204 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2205 Mutex::Autolock il(mInterfaceLock);
2206 Mutex::Autolock l(mLock);
2207
2208 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2209 if (idx == NAME_NOT_FOUND) {
2210 CLOGE("Stream %d is unknown", streamId);
2211 return idx;
2212 }
2213
2214 for (const auto &it : removedSurfaceIds) {
2215 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2216 CLOGE("Shared surface still part of a pending request!");
2217 return -EBUSY;
2218 }
2219 }
2220
2221 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2222 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2223 if (res != OK) {
2224 CLOGE("Stream %d failed to update stream (error %d %s) ",
2225 streamId, res, strerror(-res));
2226 if (res == UNKNOWN_ERROR) {
2227 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2228 __FUNCTION__);
2229 }
2230 return res;
2231 }
2232
2233 return res;
2234}
2235
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002236status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2237 Mutex::Autolock il(mInterfaceLock);
2238 Mutex::Autolock l(mLock);
2239
2240 int idx = mOutputStreams.indexOfKey(streamId);
2241 if (idx == NAME_NOT_FOUND) {
2242 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2243 return BAD_VALUE;
2244 }
2245
2246 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2247 return stream->dropBuffers(dropping);
2248}
2249
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002250/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002251 * Camera3Device private methods
2252 */
2253
2254sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002255 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002256 ATRACE_CALL();
2257 status_t res;
2258
2259 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002260 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002261
2262 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002263 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002264 if (inputStreams.count > 0) {
2265 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002266 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002267 CLOGE("Request references unknown input stream %d",
2268 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002269 return NULL;
2270 }
2271 // Lazy completion of stream configuration (allocation/registration)
2272 // on first use
2273 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002274 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002275 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002276 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002277 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002278 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002279 return NULL;
2280 }
2281 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002282 // Check if stream prepare is blocking requests.
2283 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002284 CLOGE("Request references an input stream that's being prepared!");
2285 return NULL;
2286 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002287
2288 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002289 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002290 }
2291
2292 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002293 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002294 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002295 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002296 return NULL;
2297 }
2298
2299 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002300 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002301 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002302 CLOGE("Request references unknown stream %d",
2303 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002304 return NULL;
2305 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002306 sp<Camera3OutputStreamInterface> stream =
2307 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002308
Zhijun He5d677d12016-05-29 16:52:39 -07002309 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002310 auto iter = surfaceMap.find(streams.data.i32[i]);
2311 if (iter != surfaceMap.end()) {
2312 const std::vector<size_t>& surfaces = iter->second;
2313 for (const auto& surface : surfaces) {
2314 if (stream->isConsumerConfigurationDeferred(surface)) {
2315 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2316 "due to deferred consumer", stream->getId(), surface);
2317 return NULL;
2318 }
2319 }
2320 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002321 }
2322
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002323 // Lazy completion of stream configuration (allocation/registration)
2324 // on first use
2325 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002326 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002327 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002328 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2329 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002330 return NULL;
2331 }
2332 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002333 // Check if stream prepare is blocking requests.
2334 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002335 CLOGE("Request references an output stream that's being prepared!");
2336 return NULL;
2337 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002338
2339 newRequest->mOutputStreams.push(stream);
2340 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002341 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002342 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002343
2344 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002345}
2346
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002347bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2348 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2349 Size size = mSupportedOpaqueInputSizes[i];
2350 if (size.width == width && size.height == height) {
2351 return true;
2352 }
2353 }
2354
2355 return false;
2356}
2357
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002358void Camera3Device::cancelStreamsConfigurationLocked() {
2359 int res = OK;
2360 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2361 res = mInputStream->cancelConfiguration();
2362 if (res != OK) {
2363 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2364 mInputStream->getId(), strerror(-res), res);
2365 }
2366 }
2367
2368 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2369 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2370 if (outputStream->isConfiguring()) {
2371 res = outputStream->cancelConfiguration();
2372 if (res != OK) {
2373 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2374 outputStream->getId(), strerror(-res), res);
2375 }
2376 }
2377 }
2378
2379 // Return state to that at start of call, so that future configures
2380 // properly clean things up
2381 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2382 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002383
2384 res = mPreparerThread->resume();
2385 if (res != OK) {
2386 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2387 }
2388}
2389
2390bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2391 ATRACE_CALL();
2392 bool ret = false;
2393
2394 Mutex::Autolock il(mInterfaceLock);
2395 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2396
2397 Mutex::Autolock l(mLock);
2398 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2399 if (rc == NO_ERROR) {
2400 mNeedConfig = true;
2401 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2402 if (rc == NO_ERROR) {
2403 ret = true;
2404 mPauseStateNotify = false;
2405 //Moving to active state while holding 'mLock' is important.
2406 //There could be pending calls to 'create-/deleteStream' which
2407 //will trigger another stream configuration while the already
2408 //present streams end up with outstanding buffers that will
2409 //not get drained.
2410 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002411 } else if (rc == DEAD_OBJECT) {
2412 // DEAD_OBJECT can be returned if either the consumer surface is
2413 // abandoned, or the HAL has died.
2414 // - If the HAL has died, configureStreamsLocked call will set
2415 // device to error state,
2416 // - If surface is abandoned, we should not set device to error
2417 // state.
2418 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002419 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002420 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002421 }
2422 } else {
2423 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2424 }
2425
2426 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002427}
2428
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002429status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002430 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002431 ATRACE_CALL();
2432 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002433
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002434 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002435 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002436 return INVALID_OPERATION;
2437 }
2438
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002439 if (operatingMode < 0) {
2440 CLOGE("Invalid operating mode: %d", operatingMode);
2441 return BAD_VALUE;
2442 }
2443
2444 bool isConstrainedHighSpeed =
2445 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2446 operatingMode;
2447
2448 if (mOperatingMode != operatingMode) {
2449 mNeedConfig = true;
2450 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2451 mOperatingMode = operatingMode;
2452 }
2453
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002454 if (!mNeedConfig) {
2455 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2456 return OK;
2457 }
2458
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002459 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2460 // adding a dummy stream instead.
2461 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2462 if (mOutputStreams.size() == 0) {
2463 addDummyStreamLocked();
2464 } else {
2465 tryRemoveDummyStreamLocked();
2466 }
2467
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002468 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002469 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002470
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002471 mPreparerThread->pause();
2472
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002473 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002474 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002475 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2476
2477 Vector<camera3_stream_t*> streams;
2478 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002479 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002480
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002481
2482 if (mInputStream != NULL) {
2483 camera3_stream_t *inputStream;
2484 inputStream = mInputStream->startConfiguration();
2485 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002486 CLOGE("Can't start input stream configuration");
2487 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002488 return INVALID_OPERATION;
2489 }
2490 streams.add(inputStream);
2491 }
2492
2493 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002494
2495 // Don't configure bidi streams twice, nor add them twice to the list
2496 if (mOutputStreams[i].get() ==
2497 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2498
2499 config.num_streams--;
2500 continue;
2501 }
2502
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002503 camera3_stream_t *outputStream;
2504 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2505 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002506 CLOGE("Can't start output stream configuration");
2507 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002508 return INVALID_OPERATION;
2509 }
2510 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002511
2512 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2513 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002514 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2515 // always occupy the initial entry.
2516 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002517 getJpegBufferSize(outputStream->width, outputStream->height));
2518 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002519 }
2520
2521 config.streams = streams.editArray();
2522
2523 // Do the HAL configuration; will potentially touch stream
2524 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002525
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002526 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002527 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002528 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002529
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002530 if (res == BAD_VALUE) {
2531 // HAL rejected this set of streams as unsupported, clean up config
2532 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002533 CLOGE("Set of requested inputs/outputs not supported by HAL");
2534 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002535 return BAD_VALUE;
2536 } else if (res != OK) {
2537 // Some other kind of error from configure_streams - this is not
2538 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002539 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2540 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002541 return res;
2542 }
2543
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002544 // Finish all stream configuration immediately.
2545 // TODO: Try to relax this later back to lazy completion, which should be
2546 // faster
2547
Igor Murashkin073f8572013-05-02 14:59:28 -07002548 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002549 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002550 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002551 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002552 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002553 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002554 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2555 return DEAD_OBJECT;
2556 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002557 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002558 }
2559 }
2560
2561 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002562 sp<Camera3OutputStreamInterface> outputStream =
2563 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002564 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002565 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002566 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002567 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002568 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002569 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002570 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2571 return DEAD_OBJECT;
2572 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002573 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002574 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002575 }
2576 }
2577
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002578 // Request thread needs to know to avoid using repeat-last-settings protocol
2579 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002580 if (notifyRequestThread) {
2581 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2582 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002583
Zhijun He90f7c372016-08-16 16:19:43 -07002584 char value[PROPERTY_VALUE_MAX];
2585 property_get("camera.fifo.disable", value, "0");
2586 int32_t disableFifo = atoi(value);
2587 if (disableFifo != 1) {
2588 // Boost priority of request thread to SCHED_FIFO.
2589 pid_t requestThreadTid = mRequestThread->getTid();
2590 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002591 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002592 if (res != OK) {
2593 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2594 strerror(-res), res);
2595 } else {
2596 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2597 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002598 }
2599
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002600 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002601 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2602 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2603 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2604 sessionParams.unlock(newSessionParams);
2605 mSessionParams.unlock(currentSessionParams);
2606 if (updateSessionParams) {
2607 mSessionParams = sessionParams;
2608 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002609
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002610 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002611
Ruben Brunk183f0562015-08-12 12:55:02 -07002612 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2613 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002614
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002615 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002616
Zhijun He0a210512014-07-24 13:45:15 -07002617 // tear down the deleted streams after configure streams.
2618 mDeletedStreams.clear();
2619
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002620 auto rc = mPreparerThread->resume();
2621 if (rc != OK) {
2622 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2623 return rc;
2624 }
2625
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002626 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002627}
2628
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002629status_t Camera3Device::addDummyStreamLocked() {
2630 ATRACE_CALL();
2631 status_t res;
2632
2633 if (mDummyStreamId != NO_STREAM) {
2634 // Should never be adding a second dummy stream when one is already
2635 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002636 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2637 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002638 return INVALID_OPERATION;
2639 }
2640
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002641 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002642
2643 sp<Camera3OutputStreamInterface> dummyStream =
2644 new Camera3DummyStream(mNextStreamId);
2645
2646 res = mOutputStreams.add(mNextStreamId, dummyStream);
2647 if (res < 0) {
2648 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2649 return res;
2650 }
2651
2652 mDummyStreamId = mNextStreamId;
2653 mNextStreamId++;
2654
2655 return OK;
2656}
2657
2658status_t Camera3Device::tryRemoveDummyStreamLocked() {
2659 ATRACE_CALL();
2660 status_t res;
2661
2662 if (mDummyStreamId == NO_STREAM) return OK;
2663 if (mOutputStreams.size() == 1) return OK;
2664
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002665 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002666
2667 // Ok, have a dummy stream and there's at least one other output stream,
2668 // so remove the dummy
2669
2670 sp<Camera3StreamInterface> deletedStream;
2671 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2672 if (outputStreamIdx == NAME_NOT_FOUND) {
2673 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2674 return INVALID_OPERATION;
2675 }
2676
2677 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2678 mOutputStreams.removeItemsAt(outputStreamIdx);
2679
2680 // Free up the stream endpoint so that it can be used by some other stream
2681 res = deletedStream->disconnect();
2682 if (res != OK) {
2683 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2684 // fall through since we want to still list the stream as deleted.
2685 }
2686 mDeletedStreams.add(deletedStream);
2687 mDummyStreamId = NO_STREAM;
2688
2689 return res;
2690}
2691
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002692void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002693 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002694 Mutex::Autolock l(mLock);
2695 va_list args;
2696 va_start(args, fmt);
2697
2698 setErrorStateLockedV(fmt, args);
2699
2700 va_end(args);
2701}
2702
2703void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002704 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002705 Mutex::Autolock l(mLock);
2706 setErrorStateLockedV(fmt, args);
2707}
2708
2709void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2710 va_list args;
2711 va_start(args, fmt);
2712
2713 setErrorStateLockedV(fmt, args);
2714
2715 va_end(args);
2716}
2717
2718void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002719 // Print out all error messages to log
2720 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002721 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002722
2723 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002724 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002725
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002726 mErrorCause = errorCause;
2727
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002728 if (mRequestThread != nullptr) {
2729 mRequestThread->setPaused(true);
2730 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002731 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002732
2733 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002734 sp<NotificationListener> listener = mListener.promote();
2735 if (listener != NULL) {
2736 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002737 CaptureResultExtras());
2738 }
2739
2740 // Save stack trace. View by dumping it later.
2741 CameraTraces::saveTrace();
2742 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002743}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002744
2745/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002746 * In-flight request management
2747 */
2748
Jianing Weicb0652e2014-03-12 18:29:36 -07002749status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002750 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002751 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002752 std::set<String8>& physicalCameraIds, bool isStillCapture,
2753 bool isZslCapture) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002754 ATRACE_CALL();
2755 Mutex::Autolock l(mInFlightLock);
2756
2757 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002758 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002759 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002760 if (res < 0) return res;
2761
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002762 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002763 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2764 // avoid a deadlock during reprocess requests.
2765 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002766 if (mStatusTracker != nullptr) {
2767 mStatusTracker->markComponentActive(mInFlightStatusId);
2768 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002769 }
2770
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002771 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002772 return OK;
2773}
2774
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002775void Camera3Device::returnOutputBuffers(
2776 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002777 nsecs_t timestamp, bool timestampIncreasing) {
2778
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002779 for (size_t i = 0; i < numBuffers; i++)
2780 {
2781 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
Shuzhen Wang26abaf42018-08-28 15:41:20 -07002782 status_t res = stream->returnBuffer(outputBuffers[i], timestamp, timestampIncreasing);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002783 // Note: stream may be deallocated at this point, if this buffer was
2784 // the last reference to it.
2785 if (res != OK) {
2786 ALOGE("Can't return buffer to its stream: %s (%d)",
2787 strerror(-res), res);
2788 }
2789 }
2790}
2791
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002792void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002793 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002794 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002795 mInFlightMap.removeItemsAt(idx, 1);
2796
2797 // Indicate idle inFlightMap to the status tracker
2798 if (mInFlightMap.size() == 0) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002799 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2800 // avoid a deadlock during reprocess requests.
2801 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002802 if (mStatusTracker != nullptr) {
2803 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2804 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002805 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002806 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002807}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002808
2809void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2810
2811 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2812 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2813
2814 nsecs_t sensorTimestamp = request.sensorTimestamp;
2815 nsecs_t shutterTimestamp = request.shutterTimestamp;
2816
2817 // Check if it's okay to remove the request from InFlightMap:
2818 // In the case of a successful request:
2819 // all input and output buffers, all result metadata, shutter callback
2820 // arrived.
2821 // In the case of a unsuccessful request:
2822 // all input and output buffers arrived.
2823 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002824 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002825 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01002826 if (request.stillCapture) {
2827 ATRACE_ASYNC_END("still capture", frameNumber);
2828 }
2829
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002830 ATRACE_ASYNC_END("frame capture", frameNumber);
2831
Shuzhen Wang403044a2017-02-26 23:29:04 -08002832 // Sanity check - if sensor timestamp matches shutter timestamp in the
2833 // case of request having callback.
2834 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002835 sensorTimestamp != shutterTimestamp) {
2836 SET_ERR("sensor timestamp (%" PRId64
2837 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2838 sensorTimestamp, frameNumber, shutterTimestamp);
2839 }
2840
2841 // for an unsuccessful request, it may have pending output buffers to
2842 // return.
2843 assert(request.requestStatus != OK ||
2844 request.pendingOutputBuffers.size() == 0);
2845 returnOutputBuffers(request.pendingOutputBuffers.array(),
2846 request.pendingOutputBuffers.size(), 0);
2847
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002848 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002849 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2850 }
2851
2852 // Sanity check - if we have too many in-flight frames, something has
2853 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002854 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002855 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002856 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2857 kInFlightWarnLimitHighSpeed) {
2858 CLOGE("In-flight list too large for high speed configuration: %zu",
2859 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002860 }
2861}
2862
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002863void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002864 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002865 { // First return buffers cached in mInFlightMap
2866 Mutex::Autolock l(mInFlightLock);
2867 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2868 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2869 returnOutputBuffers(request.pendingOutputBuffers.array(),
2870 request.pendingOutputBuffers.size(), 0);
2871 }
2872 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002873 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002874 }
2875
2876 // Then return all inflight buffers not returned by HAL
2877 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2878 mInterface->getInflightBufferKeys(&inflightKeys);
2879
2880 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2881 for (auto& pair : inflightKeys) {
2882 int32_t frameNumber = pair.first;
2883 int32_t streamId = pair.second;
2884 buffer_handle_t* buffer;
2885 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2886 if (res != OK) {
2887 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2888 __FUNCTION__, frameNumber, streamId);
2889 continue;
2890 }
2891
2892 camera3_stream_buffer_t streamBuffer;
2893 streamBuffer.buffer = buffer;
2894 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2895 streamBuffer.acquire_fence = -1;
2896 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002897
2898 // First check if the buffer belongs to deleted stream
2899 bool streamDeleted = false;
2900 for (auto& stream : mDeletedStreams) {
2901 if (streamId == stream->getId()) {
2902 streamDeleted = true;
2903 // Return buffer to deleted stream
2904 camera3_stream* halStream = stream->asHalStream();
2905 streamBuffer.stream = halStream;
2906 switch (halStream->stream_type) {
2907 case CAMERA3_STREAM_OUTPUT:
2908 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2909 if (res != OK) {
2910 ALOGE("%s: Can't return output buffer for frame %d to"
2911 " stream %d: %s (%d)", __FUNCTION__,
2912 frameNumber, streamId, strerror(-res), res);
2913 }
2914 break;
2915 case CAMERA3_STREAM_INPUT:
2916 res = stream->returnInputBuffer(streamBuffer);
2917 if (res != OK) {
2918 ALOGE("%s: Can't return input buffer for frame %d to"
2919 " stream %d: %s (%d)", __FUNCTION__,
2920 frameNumber, streamId, strerror(-res), res);
2921 }
2922 break;
2923 default: // Bi-direcitonal stream is deprecated
2924 ALOGE("%s: stream %d has unknown stream type %d",
2925 __FUNCTION__, streamId, halStream->stream_type);
2926 break;
2927 }
2928 break;
2929 }
2930 }
2931 if (streamDeleted) {
2932 continue;
2933 }
2934
2935 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002936 if (streamId == inputStreamId) {
2937 streamBuffer.stream = mInputStream->asHalStream();
2938 res = mInputStream->returnInputBuffer(streamBuffer);
2939 if (res != OK) {
2940 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002941 " stream %d: %s (%d)", __FUNCTION__,
2942 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002943 }
2944 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002945 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2946 if (idx == NAME_NOT_FOUND) {
2947 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2948 continue;
2949 }
2950 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002951 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2952 }
2953 }
2954}
2955
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002956void Camera3Device::insertResultLocked(CaptureResult *result,
2957 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002958 if (result == nullptr) return;
2959
Emilian Peev71c73a22017-03-21 16:35:51 +00002960 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2961 result->mMetadata.getAndLock());
2962 set_camera_metadata_vendor_id(meta, mVendorTagId);
2963 result->mMetadata.unlock(meta);
2964
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002965 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2966 (int32_t*)&frameNumber, 1) != OK) {
2967 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2968 return;
2969 }
2970
2971 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2972 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2973 return;
2974 }
2975
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002976 // Valid result, insert into queue
2977 List<CaptureResult>::iterator queuedResult =
2978 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2979 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2980 ", burstId = %" PRId32, __FUNCTION__,
2981 queuedResult->mResultExtras.requestId,
2982 queuedResult->mResultExtras.frameNumber,
2983 queuedResult->mResultExtras.burstId);
2984
2985 mResultSignal.signal();
2986}
2987
2988
2989void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002990 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002991 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002992 Mutex::Autolock l(mOutputLock);
2993
2994 CaptureResult captureResult;
2995 captureResult.mResultExtras = resultExtras;
2996 captureResult.mMetadata = partialResult;
2997
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002998 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002999}
3000
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003001
3002void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3003 CaptureResultExtras &resultExtras,
3004 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003005 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003006 bool reprocess,
3007 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003008 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003009 if (pendingMetadata.isEmpty())
3010 return;
3011
3012 Mutex::Autolock l(mOutputLock);
3013
3014 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003015 if (reprocess) {
3016 if (frameNumber < mNextReprocessResultFrameNumber) {
3017 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003018 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003019 frameNumber, mNextReprocessResultFrameNumber);
3020 return;
3021 }
3022 mNextReprocessResultFrameNumber = frameNumber + 1;
3023 } else {
3024 if (frameNumber < mNextResultFrameNumber) {
3025 SET_ERR("Out-of-order capture result metadata submitted! "
3026 "(got frame number %d, expecting %d)",
3027 frameNumber, mNextResultFrameNumber);
3028 return;
3029 }
3030 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003031 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003032
3033 CaptureResult captureResult;
3034 captureResult.mResultExtras = resultExtras;
3035 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003036 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003037
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003038 // Append any previous partials to form a complete result
3039 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3040 captureResult.mMetadata.append(collectedPartialResult);
3041 }
3042
3043 captureResult.mMetadata.sort();
3044
3045 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003046 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3047 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003048 SET_ERR("No timestamp provided by HAL for frame %d!",
3049 frameNumber);
3050 return;
3051 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003052 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3053 camera_metadata_entry timestamp =
3054 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3055 if (timestamp.count == 0) {
3056 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3057 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3058 return;
3059 }
3060 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003061
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003062 // Fix up some result metadata to account for HAL-level distortion correction
3063 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3064 if (res != OK) {
3065 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3066 frameNumber, strerror(res), res);
3067 return;
3068 }
3069
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003070 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3071 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3072
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003073 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003074}
3075
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003076/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003077 * Camera HAL device callback methods
3078 */
3079
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003080void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003081 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003082
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003083 status_t res;
3084
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003085 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003086 if (result->result == NULL && result->num_output_buffers == 0 &&
3087 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003088 SET_ERR("No result data provided by HAL for frame %d",
3089 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003090 return;
3091 }
Zhijun He204e3292014-07-14 17:09:23 -07003092
Zhijun He204e3292014-07-14 17:09:23 -07003093 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003094 result->result != NULL &&
3095 result->partial_result != 1) {
3096 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3097 " if partial result is not supported",
3098 frameNumber, result->partial_result);
3099 return;
3100 }
3101
3102 bool isPartialResult = false;
3103 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003104 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003105
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003106 // Get shutter timestamp and resultExtras from list of in-flight requests,
3107 // where it was added by the shutter notification for this frame. If the
3108 // shutter timestamp isn't received yet, append the output buffers to the
3109 // in-flight request and they will be returned when the shutter timestamp
3110 // arrives. Update the in-flight status and remove the in-flight entry if
3111 // all result data and shutter timestamp have been received.
3112 nsecs_t shutterTimestamp = 0;
3113
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003114 {
3115 Mutex::Autolock l(mInFlightLock);
3116 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3117 if (idx == NAME_NOT_FOUND) {
3118 SET_ERR("Unknown frame number for capture result: %d",
3119 frameNumber);
3120 return;
3121 }
3122 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003123 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3124 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003125 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003126 __FUNCTION__, request.resultExtras.requestId,
3127 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003128 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003129 // Always update the partial count to the latest one if it's not 0
3130 // (buffers only). When framework aggregates adjacent partial results
3131 // into one, the latest partial count will be used.
3132 if (result->partial_result != 0)
3133 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003134
3135 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003136 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003137 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3138 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3139 " the range of [1, %d] when metadata is included in the result",
3140 frameNumber, result->partial_result, mNumPartialResults);
3141 return;
3142 }
3143 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003144 if (isPartialResult && result->num_physcam_metadata) {
3145 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3146 " physical camera result", frameNumber);
3147 return;
3148 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003149 if (isPartialResult) {
3150 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003151 }
3152
Shuzhen Wang4a472662017-02-26 23:29:04 -08003153 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003154 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003155 sendPartialCaptureResult(result->result, request.resultExtras,
3156 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003157 }
3158 }
3159
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003160 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003161 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003162
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003163 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003164 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003165 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3166 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3167 request.physicalCameraIds.size(), result->num_physcam_metadata);
3168 return;
3169 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003170 if (request.haveResultMetadata) {
3171 SET_ERR("Called multiple times with metadata for frame %d",
3172 frameNumber);
3173 return;
3174 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003175 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3176 String8 physicalId(result->physcam_ids[i]);
3177 std::set<String8>::iterator cameraIdIter =
3178 request.physicalCameraIds.find(physicalId);
3179 if (cameraIdIter != request.physicalCameraIds.end()) {
3180 request.physicalCameraIds.erase(cameraIdIter);
3181 } else {
3182 SET_ERR("Total result for frame %d has already returned for camera %s",
3183 frameNumber, physicalId.c_str());
3184 return;
3185 }
3186 }
Zhijun He204e3292014-07-14 17:09:23 -07003187 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003188 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003189 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003190 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003191 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003192 request.haveResultMetadata = true;
3193 }
3194
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003195 uint32_t numBuffersReturned = result->num_output_buffers;
3196 if (result->input_buffer != NULL) {
3197 if (hasInputBufferInRequest) {
3198 numBuffersReturned += 1;
3199 } else {
3200 ALOGW("%s: Input buffer should be NULL if there is no input"
3201 " buffer sent in the request",
3202 __FUNCTION__);
3203 }
3204 }
3205 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003206 if (request.numBuffersLeft < 0) {
3207 SET_ERR("Too many buffers returned for frame %d",
3208 frameNumber);
3209 return;
3210 }
3211
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003212 camera_metadata_ro_entry_t entry;
3213 res = find_camera_metadata_ro_entry(result->result,
3214 ANDROID_SENSOR_TIMESTAMP, &entry);
3215 if (res == OK && entry.count == 1) {
3216 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003217 }
3218
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003219 // If shutter event isn't received yet, append the output buffers to
3220 // the in-flight request. Otherwise, return the output buffers to
3221 // streams.
3222 if (shutterTimestamp == 0) {
3223 request.pendingOutputBuffers.appendArray(result->output_buffers,
3224 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003225 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003226 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003227 returnOutputBuffers(result->output_buffers,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003228 result->num_output_buffers, shutterTimestamp, timestampIncreasing);
Igor Murashkind2c90692013-04-02 12:32:32 -07003229 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003230
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003231 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003232 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3233 CameraMetadata physicalMetadata;
3234 physicalMetadata.append(result->physcam_metadata[i]);
3235 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3236 physicalMetadata});
3237 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003238 if (shutterTimestamp == 0) {
3239 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003240 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003241 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003242 CameraMetadata metadata;
3243 metadata = result->result;
3244 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003245 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003246 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003247 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003248 }
3249
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003250 removeInFlightRequestIfReadyLocked(idx);
3251 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003252
Zhijun Hef0d962a2014-06-30 10:24:11 -07003253 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003254 if (hasInputBufferInRequest) {
3255 Camera3Stream *stream =
3256 Camera3Stream::cast(result->input_buffer->stream);
3257 res = stream->returnInputBuffer(*(result->input_buffer));
3258 // Note: stream may be deallocated at this point, if this buffer was the
3259 // last reference to it.
3260 if (res != OK) {
3261 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3262 " its stream:%s (%d)", __FUNCTION__,
3263 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003264 }
3265 } else {
3266 ALOGW("%s: Input buffer should be NULL if there is no input"
3267 " buffer sent in the request, skipping input buffer return.",
3268 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003269 }
3270 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003271}
3272
3273void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003274 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003275 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003276 {
3277 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003278 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003279 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003280
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003281 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003282 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003283 return;
3284 }
3285
3286 switch (msg->type) {
3287 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003288 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003289 break;
3290 }
3291 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003292 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003293 break;
3294 }
3295 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003296 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003297 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003298 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003299}
3300
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003301void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003302 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003303 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003304 // Map camera HAL error codes to ICameraDeviceCallback error codes
3305 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003306 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003307 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003308 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003309 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003310 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003311 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003312 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003313 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003314 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003315 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003316 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003317 };
3318
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003319 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003320 ((msg.error_code >= 0) &&
3321 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3322 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003323 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003324
3325 int streamId = 0;
3326 if (msg.error_stream != NULL) {
3327 Camera3Stream *stream =
3328 Camera3Stream::cast(msg.error_stream);
3329 streamId = stream->getId();
3330 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003331 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3332 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003333 streamId, msg.error_code);
3334
3335 CaptureResultExtras resultExtras;
3336 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003337 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003338 // SET_ERR calls notifyError
3339 SET_ERR("Camera HAL reported serious device error");
3340 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003341 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3342 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3343 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003344 {
3345 Mutex::Autolock l(mInFlightLock);
3346 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3347 if (idx >= 0) {
3348 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3349 r.requestStatus = msg.error_code;
3350 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003351 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3352 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3353 errorCode) {
3354 r.skipResultMetadata = true;
3355 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003356 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3357 errorCode) {
3358 // In case of missing result check whether the buffers
3359 // returned. If they returned, then remove inflight
3360 // request.
3361 removeInFlightRequestIfReadyLocked(idx);
3362 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003363 } else {
3364 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003365 ALOGE("Camera %s: %s: cannot find in-flight request on "
3366 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003367 resultExtras.frameNumber);
3368 }
3369 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003370 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003371 if (listener != NULL) {
3372 listener->notifyError(errorCode, resultExtras);
3373 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003374 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003375 }
3376 break;
3377 default:
3378 // SET_ERR calls notifyError
3379 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3380 break;
3381 }
3382}
3383
3384void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003385 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003386 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003387 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003388
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003389 // Set timestamp for the request in the in-flight tracking
3390 // and get the request ID to send upstream
3391 {
3392 Mutex::Autolock l(mInFlightLock);
3393 idx = mInFlightMap.indexOfKey(msg.frame_number);
3394 if (idx >= 0) {
3395 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003396
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003397 // Verify ordering of shutter notifications
3398 {
3399 Mutex::Autolock l(mOutputLock);
3400 // TODO: need to track errors for tighter bounds on expected frame number.
3401 if (r.hasInputBuffer) {
3402 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3403 SET_ERR("Shutter notification out-of-order. Expected "
3404 "notification for frame %d, got frame %d",
3405 mNextReprocessShutterFrameNumber, msg.frame_number);
3406 return;
3407 }
3408 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3409 } else {
3410 if (msg.frame_number < mNextShutterFrameNumber) {
3411 SET_ERR("Shutter notification out-of-order. Expected "
3412 "notification for frame %d, got frame %d",
3413 mNextShutterFrameNumber, msg.frame_number);
3414 return;
3415 }
3416 mNextShutterFrameNumber = msg.frame_number + 1;
3417 }
3418 }
3419
Shuzhen Wang4a472662017-02-26 23:29:04 -08003420 r.shutterTimestamp = msg.timestamp;
3421 if (r.hasCallback) {
3422 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003423 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003424 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003425 // Call listener, if any
3426 if (listener != NULL) {
3427 listener->notifyShutter(r.resultExtras, msg.timestamp);
3428 }
3429 // send pending result and buffers
3430 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3431 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003432 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003433 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003434 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003435 returnOutputBuffers(r.pendingOutputBuffers.array(),
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003436 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003437 r.pendingOutputBuffers.clear();
3438
3439 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003440 }
3441 }
3442 if (idx < 0) {
3443 SET_ERR("Shutter notification for non-existent frame number %d",
3444 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003445 }
3446}
3447
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003448CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003449 ALOGV("%s", __FUNCTION__);
3450
Igor Murashkin1e479c02013-09-06 16:55:14 -07003451 CameraMetadata retVal;
3452
3453 if (mRequestThread != NULL) {
3454 retVal = mRequestThread->getLatestRequest();
3455 }
3456
Igor Murashkin1e479c02013-09-06 16:55:14 -07003457 return retVal;
3458}
3459
Jianing Weicb0652e2014-03-12 18:29:36 -07003460
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003461void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3462 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3463 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3464}
3465
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003466/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003467 * HalInterface inner class methods
3468 */
3469
Yifan Hongf79b5542017-04-11 14:44:25 -07003470Camera3Device::HalInterface::HalInterface(
3471 sp<ICameraDeviceSession> &session,
3472 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003473 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003474 mRequestMetadataQueue(queue) {
3475 // Check with hardware service manager if we can downcast these interfaces
3476 // Somewhat expensive, so cache the results at startup
3477 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3478 if (castResult_3_4.isOk()) {
3479 mHidlSession_3_4 = castResult_3_4;
3480 }
3481 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3482 if (castResult_3_3.isOk()) {
3483 mHidlSession_3_3 = castResult_3_3;
3484 }
3485}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003486
Emilian Peev31abd0a2017-05-11 18:37:46 +01003487Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003488
3489Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003490 mHidlSession(other.mHidlSession),
3491 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003492
3493bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003494 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003495}
3496
3497void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003498 mHidlSession_3_4.clear();
3499 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003500 mHidlSession.clear();
3501}
3502
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003503bool Camera3Device::HalInterface::supportBatchRequest() {
3504 return mHidlSession != nullptr;
3505}
3506
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003507status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3508 camera3_request_template_t templateId,
3509 /*out*/ camera_metadata_t **requestTemplate) {
3510 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3511 if (!valid()) return INVALID_OPERATION;
3512 status_t res = OK;
3513
Emilian Peev31abd0a2017-05-11 18:37:46 +01003514 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003515
3516 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003517 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003518 status = s;
3519 if (status == common::V1_0::Status::OK) {
3520 const camera_metadata *r =
3521 reinterpret_cast<const camera_metadata_t*>(request.data());
3522 size_t expectedSize = request.size();
3523 int ret = validate_camera_metadata_structure(r, &expectedSize);
3524 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3525 *requestTemplate = clone_camera_metadata(r);
3526 if (*requestTemplate == nullptr) {
3527 ALOGE("%s: Unable to clone camera metadata received from HAL",
3528 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003529 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003530 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003531 } else {
3532 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3533 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003534 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003535 }
3536 };
3537 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003538 RequestTemplate id;
3539 switch (templateId) {
3540 case CAMERA3_TEMPLATE_PREVIEW:
3541 id = RequestTemplate::PREVIEW;
3542 break;
3543 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3544 id = RequestTemplate::STILL_CAPTURE;
3545 break;
3546 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3547 id = RequestTemplate::VIDEO_RECORD;
3548 break;
3549 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3550 id = RequestTemplate::VIDEO_SNAPSHOT;
3551 break;
3552 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3553 id = RequestTemplate::ZERO_SHUTTER_LAG;
3554 break;
3555 case CAMERA3_TEMPLATE_MANUAL:
3556 id = RequestTemplate::MANUAL;
3557 break;
3558 default:
3559 // Unknown template ID, or this HAL is too old to support it
3560 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003561 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003562 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003563
Emilian Peev31abd0a2017-05-11 18:37:46 +01003564 if (!err.isOk()) {
3565 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3566 res = DEAD_OBJECT;
3567 } else {
3568 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003569 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003570
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003571 return res;
3572}
3573
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003574status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003575 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003576 ATRACE_NAME("CameraHal::configureStreams");
3577 if (!valid()) return INVALID_OPERATION;
3578 status_t res = OK;
3579
Emilian Peev31abd0a2017-05-11 18:37:46 +01003580 // Convert stream config to HIDL
3581 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003582 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3583 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3584 requestedConfiguration3_2.streams.resize(config->num_streams);
3585 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003586 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003587 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3588 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003589 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003590
Emilian Peev31abd0a2017-05-11 18:37:46 +01003591 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3592 cam3stream->setBufferFreedListener(this);
3593 int streamId = cam3stream->getId();
3594 StreamType streamType;
3595 switch (src->stream_type) {
3596 case CAMERA3_STREAM_OUTPUT:
3597 streamType = StreamType::OUTPUT;
3598 break;
3599 case CAMERA3_STREAM_INPUT:
3600 streamType = StreamType::INPUT;
3601 break;
3602 default:
3603 ALOGE("%s: Stream %d: Unsupported stream type %d",
3604 __FUNCTION__, streamId, config->streams[i]->stream_type);
3605 return BAD_VALUE;
3606 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003607 dst3_2.id = streamId;
3608 dst3_2.streamType = streamType;
3609 dst3_2.width = src->width;
3610 dst3_2.height = src->height;
3611 dst3_2.format = mapToPixelFormat(src->format);
3612 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3613 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3614 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3615 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003616 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003617 if (src->physical_camera_id != nullptr) {
3618 dst3_4.physicalCameraId = src->physical_camera_id;
3619 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003620
3621 activeStreams.insert(streamId);
3622 // Create Buffer ID map if necessary
3623 if (mBufferIdMaps.count(streamId) == 0) {
3624 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3625 }
3626 }
3627 // remove BufferIdMap for deleted streams
3628 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3629 int streamId = it->first;
3630 bool active = activeStreams.count(streamId) > 0;
3631 if (!active) {
3632 it = mBufferIdMaps.erase(it);
3633 } else {
3634 ++it;
3635 }
3636 }
3637
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003638 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003639 res = mapToStreamConfigurationMode(
3640 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003641 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003642 if (res != OK) {
3643 return res;
3644 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003645 requestedConfiguration3_2.operationMode = operationMode;
3646 requestedConfiguration3_4.operationMode = operationMode;
3647 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003648 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3649 get_camera_metadata_size(sessionParams));
3650
Emilian Peev31abd0a2017-05-11 18:37:46 +01003651 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003652 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003653 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003654
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003655 // See if we have v3.4 or v3.3 HAL
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003656 if (mHidlSession_3_4 != nullptr) {
3657 // We do; use v3.4 for the call
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003658 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003659 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003660 auto err = mHidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003661 [&status, &finalConfiguration3_4]
3662 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3663 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003664 status = s;
3665 });
3666 if (!err.isOk()) {
3667 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3668 return DEAD_OBJECT;
3669 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003670 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3671 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3672 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3673 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003674 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003675 // We do; use v3.3 for the call
3676 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003677 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003678 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003679 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003680 finalConfiguration = halConfiguration;
3681 status = s;
3682 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003683 if (!err.isOk()) {
3684 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3685 return DEAD_OBJECT;
3686 }
3687 } else {
3688 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3689 ALOGV("%s: v3.2 device found", __FUNCTION__);
3690 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003691 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003692 [&status, &finalConfiguration_3_2]
3693 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3694 finalConfiguration_3_2 = halConfiguration;
3695 status = s;
3696 });
3697 if (!err.isOk()) {
3698 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3699 return DEAD_OBJECT;
3700 }
3701 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3702 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3703 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3704 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003705 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003706 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003707 }
3708
3709 if (status != common::V1_0::Status::OK ) {
3710 return CameraProviderManager::mapToStatusT(status);
3711 }
3712
3713 // And convert output stream configuration from HIDL
3714
3715 for (size_t i = 0; i < config->num_streams; i++) {
3716 camera3_stream_t *dst = config->streams[i];
3717 int streamId = Camera3Stream::cast(dst)->getId();
3718
3719 // Start scan at i, with the assumption that the stream order matches
3720 size_t realIdx = i;
3721 bool found = false;
3722 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003723 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003724 found = true;
3725 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003726 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003727 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3728 }
3729 if (!found) {
3730 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3731 __FUNCTION__, streamId);
3732 return INVALID_OPERATION;
3733 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003734 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003735
Emilian Peev710c1422017-08-30 11:19:38 +01003736 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3737 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003738 dstStream->setDataSpaceOverride(false);
3739 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3740 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3741
Emilian Peev31abd0a2017-05-11 18:37:46 +01003742 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3743 if (dst->format != overrideFormat) {
3744 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3745 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003746 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003747 if (dst->data_space != overrideDataSpace) {
3748 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3749 streamId, dst->format);
3750 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003751 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003752 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003753 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3754
Emilian Peev31abd0a2017-05-11 18:37:46 +01003755 // Override allowed with IMPLEMENTATION_DEFINED
3756 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003757 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003758 }
3759
Emilian Peev31abd0a2017-05-11 18:37:46 +01003760 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003761 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003762 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003763 __FUNCTION__, streamId);
3764 return INVALID_OPERATION;
3765 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003766 dstStream->setUsage(
3767 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003768 } else {
3769 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003770 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003771 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3772 __FUNCTION__, streamId);
3773 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003774 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003775 dstStream->setUsage(
3776 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003777 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003778 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003779 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003780
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003781 return res;
3782}
3783
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003784void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3785 /*out*/device::V3_2::CaptureRequest* captureRequest,
3786 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003787 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003788 if (captureRequest == nullptr || handlesCreated == nullptr) {
3789 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3790 __FUNCTION__, captureRequest, handlesCreated);
3791 return;
3792 }
3793
3794 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003795
3796 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003797
3798 {
3799 std::lock_guard<std::mutex> lock(mInflightLock);
3800 if (request->input_buffer != nullptr) {
3801 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3802 buffer_handle_t buf = *(request->input_buffer->buffer);
3803 auto pair = getBufferId(buf, streamId);
3804 bool isNewBuffer = pair.first;
3805 uint64_t bufferId = pair.second;
3806 captureRequest->inputBuffer.streamId = streamId;
3807 captureRequest->inputBuffer.bufferId = bufferId;
3808 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3809 captureRequest->inputBuffer.status = BufferStatus::OK;
3810 native_handle_t *acquireFence = nullptr;
3811 if (request->input_buffer->acquire_fence != -1) {
3812 acquireFence = native_handle_create(1,0);
3813 acquireFence->data[0] = request->input_buffer->acquire_fence;
3814 handlesCreated->push_back(acquireFence);
3815 }
3816 captureRequest->inputBuffer.acquireFence = acquireFence;
3817 captureRequest->inputBuffer.releaseFence = nullptr;
3818
3819 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3820 request->input_buffer->buffer,
3821 request->input_buffer->acquire_fence);
3822 } else {
3823 captureRequest->inputBuffer.streamId = -1;
3824 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3825 }
3826
3827 captureRequest->outputBuffers.resize(request->num_output_buffers);
3828 for (size_t i = 0; i < request->num_output_buffers; i++) {
3829 const camera3_stream_buffer_t *src = request->output_buffers + i;
3830 StreamBuffer &dst = captureRequest->outputBuffers[i];
3831 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3832 buffer_handle_t buf = *(src->buffer);
3833 auto pair = getBufferId(buf, streamId);
3834 bool isNewBuffer = pair.first;
3835 dst.streamId = streamId;
3836 dst.bufferId = pair.second;
3837 dst.buffer = isNewBuffer ? buf : nullptr;
3838 dst.status = BufferStatus::OK;
3839 native_handle_t *acquireFence = nullptr;
3840 if (src->acquire_fence != -1) {
3841 acquireFence = native_handle_create(1,0);
3842 acquireFence->data[0] = src->acquire_fence;
3843 handlesCreated->push_back(acquireFence);
3844 }
3845 dst.acquireFence = acquireFence;
3846 dst.releaseFence = nullptr;
3847
3848 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3849 src->buffer, src->acquire_fence);
3850 }
3851 }
3852}
3853
3854status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3855 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3856 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3857 if (!valid()) return INVALID_OPERATION;
3858
Emilian Peevaebbe412018-01-15 13:53:24 +00003859 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3860 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3861 if (castResult_3_4.isOk()) {
3862 hidlSession_3_4 = castResult_3_4;
3863 }
3864
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003865 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003866 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003867 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003868 if (hidlSession_3_4 != nullptr) {
3869 captureRequests_3_4.resize(batchSize);
3870 } else {
3871 captureRequests.resize(batchSize);
3872 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003873 std::vector<native_handle_t*> handlesCreated;
3874
3875 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003876 if (hidlSession_3_4 != nullptr) {
3877 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
3878 /*out*/&handlesCreated);
3879 } else {
3880 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3881 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003882 }
3883
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003884 std::vector<device::V3_2::BufferCache> cachesToRemove;
3885 {
3886 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3887 for (auto& pair : mFreedBuffers) {
3888 // The stream might have been removed since onBufferFreed
3889 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3890 cachesToRemove.push_back({pair.first, pair.second});
3891 }
3892 }
3893 mFreedBuffers.clear();
3894 }
3895
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003896 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3897 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003898
3899 // Write metadata to FMQ.
3900 for (size_t i = 0; i < batchSize; i++) {
3901 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003902 device::V3_2::CaptureRequest* captureRequest;
3903 if (hidlSession_3_4 != nullptr) {
3904 captureRequest = &captureRequests_3_4[i].v3_2;
3905 } else {
3906 captureRequest = &captureRequests[i];
3907 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003908
3909 if (request->settings != nullptr) {
3910 size_t settingsSize = get_camera_metadata_size(request->settings);
3911 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3912 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3913 captureRequest->settings.resize(0);
3914 captureRequest->fmqSettingsSize = settingsSize;
3915 } else {
3916 if (mRequestMetadataQueue != nullptr) {
3917 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3918 }
3919 captureRequest->settings.setToExternal(
3920 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3921 get_camera_metadata_size(request->settings));
3922 captureRequest->fmqSettingsSize = 0u;
3923 }
3924 } else {
3925 // A null request settings maps to a size-0 CameraMetadata
3926 captureRequest->settings.resize(0);
3927 captureRequest->fmqSettingsSize = 0u;
3928 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003929
3930 if (hidlSession_3_4 != nullptr) {
3931 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3932 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003933 if (request->physcam_settings != nullptr) {
3934 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3935 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3936 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3937 settingsSize)) {
3938 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3939 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3940 settingsSize;
3941 } else {
3942 if (mRequestMetadataQueue != nullptr) {
3943 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3944 }
3945 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3946 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3947 request->physcam_settings[j])),
3948 get_camera_metadata_size(request->physcam_settings[j]));
3949 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003950 }
Emilian Peev00420d22018-02-05 21:33:13 +00003951 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003952 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003953 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003954 }
3955 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3956 request->physcam_id[j];
3957 }
3958 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003959 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003960
3961 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003962 auto resultCallback =
3963 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3964 status = s;
3965 *numRequestProcessed = n;
3966 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003967 if (hidlSession_3_4 != nullptr) {
3968 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003969 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003970 } else {
3971 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003972 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003973 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003974 if (!err.isOk()) {
3975 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3976 return DEAD_OBJECT;
3977 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003978 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3979 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3980 __FUNCTION__, *numRequestProcessed, batchSize);
3981 status = common::V1_0::Status::INTERNAL_ERROR;
3982 }
3983
3984 for (auto& handle : handlesCreated) {
3985 native_handle_delete(handle);
3986 }
3987 return CameraProviderManager::mapToStatusT(status);
3988}
3989
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003990status_t Camera3Device::HalInterface::processCaptureRequest(
3991 camera3_capture_request_t *request) {
3992 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003993 if (!valid()) return INVALID_OPERATION;
3994 status_t res = OK;
3995
Emilian Peev31abd0a2017-05-11 18:37:46 +01003996 uint32_t numRequestProcessed = 0;
3997 std::vector<camera3_capture_request_t*> requests(1);
3998 requests[0] = request;
3999 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4000
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004001 return res;
4002}
4003
4004status_t Camera3Device::HalInterface::flush() {
4005 ATRACE_NAME("CameraHal::flush");
4006 if (!valid()) return INVALID_OPERATION;
4007 status_t res = OK;
4008
Emilian Peev31abd0a2017-05-11 18:37:46 +01004009 auto err = mHidlSession->flush();
4010 if (!err.isOk()) {
4011 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4012 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004013 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004014 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004015 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004016
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004017 return res;
4018}
4019
Emilian Peev31abd0a2017-05-11 18:37:46 +01004020status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004021 ATRACE_NAME("CameraHal::dump");
4022 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004023
Emilian Peev31abd0a2017-05-11 18:37:46 +01004024 // Handled by CameraProviderManager::dump
4025
4026 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004027}
4028
4029status_t Camera3Device::HalInterface::close() {
4030 ATRACE_NAME("CameraHal::close()");
4031 if (!valid()) return INVALID_OPERATION;
4032 status_t res = OK;
4033
Emilian Peev31abd0a2017-05-11 18:37:46 +01004034 auto err = mHidlSession->close();
4035 // Interface will be dead shortly anyway, so don't log errors
4036 if (!err.isOk()) {
4037 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004038 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004039
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004040 return res;
4041}
4042
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004043void Camera3Device::HalInterface::getInflightBufferKeys(
4044 std::vector<std::pair<int32_t, int32_t>>* out) {
4045 std::lock_guard<std::mutex> lock(mInflightLock);
4046 out->clear();
4047 out->reserve(mInflightBufferMap.size());
4048 for (auto& pair : mInflightBufferMap) {
4049 uint64_t key = pair.first;
4050 int32_t streamId = key & 0xFFFFFFFF;
4051 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4052 out->push_back(std::make_pair(frameNumber, streamId));
4053 }
4054 return;
4055}
4056
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004057status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004058 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004059 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004060 auto pair = std::make_pair(buffer, acquireFence);
4061 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004062 return OK;
4063}
4064
4065status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004066 int32_t frameNumber, int32_t streamId,
4067 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004068 std::lock_guard<std::mutex> lock(mInflightLock);
4069
4070 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4071 auto it = mInflightBufferMap.find(key);
4072 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004073 auto pair = it->second;
4074 *buffer = pair.first;
4075 int acquireFence = pair.second;
4076 if (acquireFence > 0) {
4077 ::close(acquireFence);
4078 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004079 mInflightBufferMap.erase(it);
4080 return OK;
4081}
4082
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004083std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4084 const buffer_handle_t& buf, int streamId) {
4085 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4086
4087 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4088 auto it = bIdMap.find(buf);
4089 if (it == bIdMap.end()) {
4090 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004091 ALOGV("stream %d now have %zu buffer caches, buf %p",
4092 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004093 return std::make_pair(true, mNextBufferId - 1);
4094 } else {
4095 return std::make_pair(false, it->second);
4096 }
4097}
4098
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004099void Camera3Device::HalInterface::onBufferFreed(
4100 int streamId, const native_handle_t* handle) {
4101 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4102 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4103 auto mapIt = mBufferIdMaps.find(streamId);
4104 if (mapIt == mBufferIdMaps.end()) {
4105 // streamId might be from a deleted stream here
4106 ALOGI("%s: stream %d has been removed",
4107 __FUNCTION__, streamId);
4108 return;
4109 }
4110 BufferIdMap& bIdMap = mapIt->second;
4111 auto it = bIdMap.find(handle);
4112 if (it == bIdMap.end()) {
4113 ALOGW("%s: cannot find buffer %p in stream %d",
4114 __FUNCTION__, handle, streamId);
4115 return;
4116 } else {
4117 bufferId = it->second;
4118 bIdMap.erase(it);
4119 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4120 __FUNCTION__, streamId, bIdMap.size(), handle);
4121 }
4122 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4123}
4124
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004125/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004126 * RequestThread inner class methods
4127 */
4128
4129Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004130 sp<StatusTracker> statusTracker,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004131 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004132 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004133 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004134 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004135 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004136 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004137 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004138 mReconfigured(false),
4139 mDoPause(false),
4140 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004141 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004142 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004143 mCurrentAfTriggerId(0),
4144 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004145 mRepeatingLastFrameNumber(
4146 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004147 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004148 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004149 mRequestLatency(kRequestLatencyBinSize),
4150 mSessionParamKeys(sessionParamKeys),
4151 mLatestSessionParams(sessionParamKeys.size()) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004152 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004153}
4154
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004155Camera3Device::RequestThread::~RequestThread() {}
4156
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004157void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004158 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004159 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004160 Mutex::Autolock l(mRequestLock);
4161 mListener = listener;
4162}
4163
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004164void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4165 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004166 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004167 Mutex::Autolock l(mRequestLock);
4168 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004169 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004170 // Prepare video stream for high speed recording.
4171 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004172 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004173}
4174
Jianing Wei90e59c92014-03-12 18:29:36 -07004175status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004176 List<sp<CaptureRequest> > &requests,
4177 /*out*/
4178 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004179 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004180 Mutex::Autolock l(mRequestLock);
4181 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4182 ++it) {
4183 mRequestQueue.push_back(*it);
4184 }
4185
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004186 if (lastFrameNumber != NULL) {
4187 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4188 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4189 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4190 *lastFrameNumber);
4191 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004192
Jianing Wei90e59c92014-03-12 18:29:36 -07004193 unpauseForNewRequests();
4194
4195 return OK;
4196}
4197
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004198
4199status_t Camera3Device::RequestThread::queueTrigger(
4200 RequestTrigger trigger[],
4201 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004202 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004203 Mutex::Autolock l(mTriggerMutex);
4204 status_t ret;
4205
4206 for (size_t i = 0; i < count; ++i) {
4207 ret = queueTriggerLocked(trigger[i]);
4208
4209 if (ret != OK) {
4210 return ret;
4211 }
4212 }
4213
4214 return OK;
4215}
4216
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004217const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4218 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004219 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004220 if (d != nullptr) return d->mId;
4221 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004222}
4223
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004224status_t Camera3Device::RequestThread::queueTriggerLocked(
4225 RequestTrigger trigger) {
4226
4227 uint32_t tag = trigger.metadataTag;
4228 ssize_t index = mTriggerMap.indexOfKey(tag);
4229
4230 switch (trigger.getTagType()) {
4231 case TYPE_BYTE:
4232 // fall-through
4233 case TYPE_INT32:
4234 break;
4235 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004236 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4237 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004238 return INVALID_OPERATION;
4239 }
4240
4241 /**
4242 * Collect only the latest trigger, since we only have 1 field
4243 * in the request settings per trigger tag, and can't send more than 1
4244 * trigger per request.
4245 */
4246 if (index != NAME_NOT_FOUND) {
4247 mTriggerMap.editValueAt(index) = trigger;
4248 } else {
4249 mTriggerMap.add(tag, trigger);
4250 }
4251
4252 return OK;
4253}
4254
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004255status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004256 const RequestList &requests,
4257 /*out*/
4258 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004259 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004260 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004261 if (lastFrameNumber != NULL) {
4262 *lastFrameNumber = mRepeatingLastFrameNumber;
4263 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004264 mRepeatingRequests.clear();
4265 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4266 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004267
4268 unpauseForNewRequests();
4269
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004270 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004271 return OK;
4272}
4273
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004274bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004275 if (mRepeatingRequests.empty()) {
4276 return false;
4277 }
4278 int32_t requestId = requestIn->mResultExtras.requestId;
4279 const RequestList &repeatRequests = mRepeatingRequests;
4280 // All repeating requests are guaranteed to have same id so only check first quest
4281 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4282 return (firstRequest->mResultExtras.requestId == requestId);
4283}
4284
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004285status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004286 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004287 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004288 return clearRepeatingRequestsLocked(lastFrameNumber);
4289
4290}
4291
4292status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004293 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004294 if (lastFrameNumber != NULL) {
4295 *lastFrameNumber = mRepeatingLastFrameNumber;
4296 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004297 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004298 return OK;
4299}
4300
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004301status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004302 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004303 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004304 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004305 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004306
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004307 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004308
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004309 // Send errors for all requests pending in the request queue, including
4310 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004311 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004312 if (listener != NULL) {
4313 for (RequestList::iterator it = mRequestQueue.begin();
4314 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004315 // Abort the input buffers for reprocess requests.
4316 if ((*it)->mInputStream != NULL) {
4317 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004318 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4319 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004320 if (res != OK) {
4321 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4322 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4323 } else {
4324 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4325 if (res != OK) {
4326 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4327 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4328 }
4329 }
4330 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004331 // Set the frame number this request would have had, if it
4332 // had been submitted; this frame number will not be reused.
4333 // The requestId and burstId fields were set when the request was
4334 // submitted originally (in convertMetadataListToRequestListLocked)
4335 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004336 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004337 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004338 }
4339 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004340 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004341
4342 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004343 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004344 if (lastFrameNumber != NULL) {
4345 *lastFrameNumber = mRepeatingLastFrameNumber;
4346 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004347 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004348 return OK;
4349}
4350
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004351status_t Camera3Device::RequestThread::flush() {
4352 ATRACE_CALL();
4353 Mutex::Autolock l(mFlushLock);
4354
Emilian Peev08dd2452017-04-06 16:55:14 +01004355 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004356}
4357
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004358void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004359 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004360 Mutex::Autolock l(mPauseLock);
4361 mDoPause = paused;
4362 mDoPauseSignal.signal();
4363}
4364
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004365status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4366 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004367 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004368 Mutex::Autolock l(mLatestRequestMutex);
4369 status_t res;
4370 while (mLatestRequestId != requestId) {
4371 nsecs_t startTime = systemTime();
4372
4373 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4374 if (res != OK) return res;
4375
4376 timeout -= (systemTime() - startTime);
4377 }
4378
4379 return OK;
4380}
4381
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004382void Camera3Device::RequestThread::requestExit() {
4383 // Call parent to set up shutdown
4384 Thread::requestExit();
4385 // The exit from any possible waits
4386 mDoPauseSignal.signal();
4387 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004388
4389 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4390 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004391}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004392
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004393void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004394 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004395 bool surfaceAbandoned = false;
4396 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004397 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004398 {
4399 Mutex::Autolock l(mRequestLock);
4400 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4401 // repeating requests.
4402 for (const auto& request : mRepeatingRequests) {
4403 for (const auto& s : request->mOutputStreams) {
4404 if (s->isAbandoned()) {
4405 surfaceAbandoned = true;
4406 clearRepeatingRequestsLocked(&lastFrameNumber);
4407 break;
4408 }
4409 }
4410 if (surfaceAbandoned) {
4411 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004412 }
4413 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004414 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004415 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004416
4417 if (listener != NULL && surfaceAbandoned) {
4418 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004419 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004420}
4421
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004422bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004423 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004424 status_t res;
4425 size_t batchSize = mNextRequests.size();
4426 std::vector<camera3_capture_request_t*> requests(batchSize);
4427 uint32_t numRequestProcessed = 0;
4428 for (size_t i = 0; i < batchSize; i++) {
4429 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004430 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004431 }
4432
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004433 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4434
4435 bool triggerRemoveFailed = false;
4436 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4437 for (size_t i = 0; i < numRequestProcessed; i++) {
4438 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4439 nextRequest.submitted = true;
4440
4441
4442 // Update the latest request sent to HAL
4443 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4444 Mutex::Autolock al(mLatestRequestMutex);
4445
4446 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4447 mLatestRequest.acquire(cloned);
4448
4449 sp<Camera3Device> parent = mParent.promote();
4450 if (parent != NULL) {
4451 parent->monitorMetadata(TagMonitor::REQUEST,
4452 nextRequest.halRequest.frame_number,
4453 0, mLatestRequest);
4454 }
4455 }
4456
4457 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004458 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4459 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004460 }
4461
Emilian Peevaebbe412018-01-15 13:53:24 +00004462 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4463
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004464 if (!triggerRemoveFailed) {
4465 // Remove any previously queued triggers (after unlock)
4466 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4467 if (removeTriggerRes != OK) {
4468 triggerRemoveFailed = true;
4469 triggerFailedRequest = nextRequest;
4470 }
4471 }
4472 }
4473
4474 if (triggerRemoveFailed) {
4475 SET_ERR("RequestThread: Unable to remove triggers "
4476 "(capture request %d, HAL device: %s (%d)",
4477 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4478 cleanUpFailedRequests(/*sendRequestError*/ false);
4479 return false;
4480 }
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 device: %s (%d)",
4487 mNextRequests[numRequestProcessed].halRequest.frame_number,
4488 strerror(-res), res);
4489 cleanUpFailedRequests(/*sendRequestError*/ false);
4490 return false;
4491 }
4492 return true;
4493}
4494
4495bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4496 status_t res;
4497
4498 for (auto& nextRequest : mNextRequests) {
4499 // Submit request and block until ready for next one
4500 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4501 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4502
4503 if (res != OK) {
4504 // Should only get a failure here for malformed requests or device-level
4505 // errors, so consider all errors fatal. Bad metadata failures should
4506 // come through notify.
4507 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4508 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4509 res);
4510 cleanUpFailedRequests(/*sendRequestError*/ false);
4511 return false;
4512 }
4513
4514 // Mark that the request has be submitted successfully.
4515 nextRequest.submitted = true;
4516
4517 // Update the latest request sent to HAL
4518 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4519 Mutex::Autolock al(mLatestRequestMutex);
4520
4521 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4522 mLatestRequest.acquire(cloned);
4523
4524 sp<Camera3Device> parent = mParent.promote();
4525 if (parent != NULL) {
4526 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4527 0, mLatestRequest);
4528 }
4529 }
4530
4531 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004532 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4533 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004534 }
4535
Emilian Peevaebbe412018-01-15 13:53:24 +00004536 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4537
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004538 // Remove any previously queued triggers (after unlock)
4539 res = removeTriggers(mPrevRequest);
4540 if (res != OK) {
4541 SET_ERR("RequestThread: Unable to remove triggers "
4542 "(capture request %d, HAL device: %s (%d)",
4543 nextRequest.halRequest.frame_number, strerror(-res), res);
4544 cleanUpFailedRequests(/*sendRequestError*/ false);
4545 return false;
4546 }
4547 }
4548 return true;
4549}
4550
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004551nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4552 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4553 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4554 find_camera_metadata_ro_entry(request,
4555 ANDROID_CONTROL_AE_MODE,
4556 &e);
4557 if (e.count == 0) return maxExpectedDuration;
4558
4559 switch (e.data.u8[0]) {
4560 case ANDROID_CONTROL_AE_MODE_OFF:
4561 find_camera_metadata_ro_entry(request,
4562 ANDROID_SENSOR_EXPOSURE_TIME,
4563 &e);
4564 if (e.count > 0) {
4565 maxExpectedDuration = e.data.i64[0];
4566 }
4567 find_camera_metadata_ro_entry(request,
4568 ANDROID_SENSOR_FRAME_DURATION,
4569 &e);
4570 if (e.count > 0) {
4571 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4572 }
4573 break;
4574 default:
4575 find_camera_metadata_ro_entry(request,
4576 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4577 &e);
4578 if (e.count > 1) {
4579 maxExpectedDuration = 1e9 / e.data.u8[0];
4580 }
4581 break;
4582 }
4583
4584 return maxExpectedDuration;
4585}
4586
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004587bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4588 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4589 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4590 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4591 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4592 return true;
4593 }
4594
4595 return false;
4596}
4597
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004598bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4599 ATRACE_CALL();
4600 bool updatesDetected = false;
4601
4602 for (auto tag : mSessionParamKeys) {
4603 camera_metadata_ro_entry entry = settings.find(tag);
4604 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4605
4606 if (entry.count > 0) {
4607 bool isDifferent = false;
4608 if (lastEntry.count > 0) {
4609 // Have a last value, compare to see if changed
4610 if (lastEntry.type == entry.type &&
4611 lastEntry.count == entry.count) {
4612 // Same type and count, compare values
4613 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4614 size_t entryBytes = bytesPerValue * lastEntry.count;
4615 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4616 if (cmp != 0) {
4617 isDifferent = true;
4618 }
4619 } else {
4620 // Count or type has changed
4621 isDifferent = true;
4622 }
4623 } else {
4624 // No last entry, so always consider to be different
4625 isDifferent = true;
4626 }
4627
4628 if (isDifferent) {
4629 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004630 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4631 updatesDetected = true;
4632 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004633 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004634 }
4635 } else if (lastEntry.count > 0) {
4636 // Value has been removed
4637 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4638 mLatestSessionParams.erase(tag);
4639 updatesDetected = true;
4640 }
4641 }
4642
4643 return updatesDetected;
4644}
4645
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004646bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004647 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004648 status_t res;
4649
4650 // Handle paused state.
4651 if (waitIfPaused()) {
4652 return true;
4653 }
4654
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004655 // Wait for the next batch of requests.
4656 waitForNextRequestBatch();
4657 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004658 return true;
4659 }
4660
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004661 // Get the latest request ID, if any
4662 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004663 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004664 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004665 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004666 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004667 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004668 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4669 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004670 }
4671
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004672 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4673 // or a single request from streaming or burst. In either case the first element
4674 // should contain the latest camera settings that we need to check for any session
4675 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004676 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004677 res = OK;
4678
4679 //Input stream buffers are already acquired at this point so an input stream
4680 //will not be able to move to idle state unless we force it.
4681 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4682 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4683 if (res != OK) {
4684 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4685 cleanUpFailedRequests(/*sendRequestError*/ false);
4686 return false;
4687 }
4688 }
4689
4690 if (res == OK) {
4691 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4692 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004693 sp<Camera3Device> parent = mParent.promote();
4694 if (parent != nullptr) {
4695 parent->pauseStateNotify(true);
4696 }
4697
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004698 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4699
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004700 if (parent != nullptr) {
4701 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4702 }
4703
4704 statusTracker->markComponentActive(mStatusId);
4705 setPaused(false);
4706 }
4707
4708 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4709 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4710 if (res != OK) {
4711 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4712 cleanUpFailedRequests(/*sendRequestError*/ false);
4713 return false;
4714 }
4715 }
4716 }
4717 }
4718
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004719 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004720 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004721 if (res == TIMED_OUT) {
4722 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004723 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004724 // Check if any stream is abandoned.
4725 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004726 return true;
4727 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004728 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004729 return false;
4730 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004731
Zhijun Hecc27e112013-10-03 16:12:43 -07004732 // Inform waitUntilRequestProcessed thread of a new request ID
4733 {
4734 Mutex::Autolock al(mLatestRequestMutex);
4735
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004736 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004737 mLatestRequestSignal.signal();
4738 }
4739
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004740 // Submit a batch of requests to HAL.
4741 // Use flush lock only when submitting multilple requests in a batch.
4742 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4743 // which may take a long time to finish so synchronizing flush() and
4744 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4745 // For now, only synchronize for high speed recording and we should figure something out for
4746 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004747 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004748
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004749 if (useFlushLock) {
4750 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004751 }
4752
Zhijun Hef0645c12016-08-02 00:58:11 -07004753 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004754 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004755
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004756 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004757 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004758 if (mInterface->supportBatchRequest()) {
4759 submitRequestSuccess = sendRequestsBatch();
4760 } else {
4761 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004762 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004763 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4764 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004765
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004766 if (useFlushLock) {
4767 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004768 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004769
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004770 // Unset as current request
4771 {
4772 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004773 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004774 }
4775
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004776 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004777}
4778
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004779status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004780 ATRACE_CALL();
4781
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004782 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004783 for (size_t i = 0; i < mNextRequests.size(); i++) {
4784 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004785 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4786 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4787 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4788
4789 // Prepare a request to HAL
4790 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4791
4792 // Insert any queued triggers (before metadata is locked)
4793 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004794 if (res < 0) {
4795 SET_ERR("RequestThread: Unable to insert triggers "
4796 "(capture request %d, HAL device: %s (%d)",
4797 halRequest->frame_number, strerror(-res), res);
4798 return INVALID_OPERATION;
4799 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004800
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004801 int triggerCount = res;
4802 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4803 mPrevTriggers = triggerCount;
4804
4805 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004806 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
4807 // Request settings are all the same within one batch, so only treat the first
4808 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004809 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004810 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004811 /**
4812 * HAL workaround:
4813 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4814 */
4815 res = addDummyTriggerIds(captureRequest);
4816 if (res != OK) {
4817 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4818 "(capture request %d, HAL device: %s (%d)",
4819 halRequest->frame_number, strerror(-res), res);
4820 return INVALID_OPERATION;
4821 }
4822
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004823 {
4824 // Correct metadata regions for distortion correction if enabled
4825 sp<Camera3Device> parent = mParent.promote();
4826 if (parent != nullptr) {
4827 res = parent->mDistortionMapper.correctCaptureRequest(
4828 &(captureRequest->mSettingsList.begin()->metadata));
4829 if (res != OK) {
4830 SET_ERR("RequestThread: Unable to correct capture requests "
4831 "for lens distortion for request %d: %s (%d)",
4832 halRequest->frame_number, strerror(-res), res);
4833 return INVALID_OPERATION;
4834 }
4835 }
4836 }
4837
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004838 /**
4839 * The request should be presorted so accesses in HAL
4840 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4841 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004842 captureRequest->mSettingsList.begin()->metadata.sort();
4843 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004844 mPrevRequest = captureRequest;
4845 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4846
4847 IF_ALOGV() {
4848 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4849 find_camera_metadata_ro_entry(
4850 halRequest->settings,
4851 ANDROID_CONTROL_AF_TRIGGER,
4852 &e
4853 );
4854 if (e.count > 0) {
4855 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4856 __FUNCTION__,
4857 halRequest->frame_number,
4858 e.data.u8[0]);
4859 }
4860 }
4861 } else {
4862 // leave request.settings NULL to indicate 'reuse latest given'
4863 ALOGVV("%s: Request settings are REUSED",
4864 __FUNCTION__);
4865 }
4866
Emilian Peevaebbe412018-01-15 13:53:24 +00004867 if (captureRequest->mSettingsList.size() > 1) {
4868 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4869 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004870 if (newRequest) {
4871 halRequest->physcam_settings =
4872 new const camera_metadata* [halRequest->num_physcam_settings];
4873 } else {
4874 halRequest->physcam_settings = nullptr;
4875 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004876 auto it = ++captureRequest->mSettingsList.begin();
4877 size_t i = 0;
4878 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4879 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004880 if (newRequest) {
4881 it->metadata.sort();
4882 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4883 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004884 }
4885 }
4886
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004887 uint32_t totalNumBuffers = 0;
4888
4889 // Fill in buffers
4890 if (captureRequest->mInputStream != NULL) {
4891 halRequest->input_buffer = &captureRequest->mInputBuffer;
4892 totalNumBuffers += 1;
4893 } else {
4894 halRequest->input_buffer = NULL;
4895 }
4896
4897 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4898 captureRequest->mOutputStreams.size());
4899 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004900 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004901
4902 sp<Camera3Device> parent = mParent.promote();
4903 if (parent == NULL) {
4904 // Should not happen, and nowhere to send errors to, so just log it
4905 CLOGE("RequestThread: Parent is gone");
4906 return INVALID_OPERATION;
4907 }
4908 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
4909
Shuzhen Wang4a472662017-02-26 23:29:04 -08004910 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4911 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004912
4913 // Prepare video buffers for high speed recording on the first video request.
4914 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4915 // Only try to prepare video stream on the first video request.
4916 mPrepareVideoStream = false;
4917
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07004918 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
4919 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004920 while (res == NOT_ENOUGH_DATA) {
4921 res = outputStream->prepareNextBuffer();
4922 }
4923 if (res != OK) {
4924 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4925 __FUNCTION__, strerror(-res), res);
4926 outputStream->cancelPrepare();
4927 }
4928 }
4929
Shuzhen Wang4a472662017-02-26 23:29:04 -08004930 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07004931 waitDuration,
Shuzhen Wang4a472662017-02-26 23:29:04 -08004932 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004933 if (res != OK) {
4934 // Can't get output buffer from gralloc queue - this could be due to
4935 // abandoned queue or other consumer misbehavior, so not a fatal
4936 // error
4937 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4938 " %s (%d)", strerror(-res), res);
4939
4940 return TIMED_OUT;
4941 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004942
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004943 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4944
4945 if (!physicalCameraId.isEmpty()) {
4946 // Physical stream isn't supported for input request.
4947 if (halRequest->input_buffer) {
4948 CLOGE("Physical stream is not supported for input request");
4949 return INVALID_OPERATION;
4950 }
4951 requestedPhysicalCameras.insert(physicalCameraId);
4952 }
4953 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004954 }
4955 totalNumBuffers += halRequest->num_output_buffers;
4956
4957 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08004958 // If this request list is for constrained high speed recording (not
4959 // preview), and the current request is not the last one in the batch,
4960 // do not send callback to the app.
4961 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004962 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004963 hasCallback = false;
4964 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004965 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004966 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01004967 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4968 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4969 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4970 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4971 isStillCapture = true;
4972 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4973 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004974
4975 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
4976 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
4977 isZslCapture = true;
4978 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004979 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004980 res = parent->registerInFlight(halRequest->frame_number,
4981 totalNumBuffers, captureRequest->mResultExtras,
4982 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004983 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004984 calculateMaxExpectedDuration(halRequest->settings),
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004985 requestedPhysicalCameras, isStillCapture, isZslCapture);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004986 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4987 ", burstId = %" PRId32 ".",
4988 __FUNCTION__,
4989 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4990 captureRequest->mResultExtras.burstId);
4991 if (res != OK) {
4992 SET_ERR("RequestThread: Unable to register new in-flight request:"
4993 " %s (%d)", strerror(-res), res);
4994 return INVALID_OPERATION;
4995 }
4996 }
4997
4998 return OK;
4999}
5000
Igor Murashkin1e479c02013-09-06 16:55:14 -07005001CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005002 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005003 Mutex::Autolock al(mLatestRequestMutex);
5004
5005 ALOGV("RequestThread::%s", __FUNCTION__);
5006
5007 return mLatestRequest;
5008}
5009
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005010bool Camera3Device::RequestThread::isStreamPending(
5011 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005012 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005013 Mutex::Autolock l(mRequestLock);
5014
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005015 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005016 if (!nextRequest.submitted) {
5017 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5018 if (stream == s) return true;
5019 }
5020 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005021 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005022 }
5023
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005024 for (const auto& request : mRequestQueue) {
5025 for (const auto& s : request->mOutputStreams) {
5026 if (stream == s) return true;
5027 }
5028 if (stream == request->mInputStream) return true;
5029 }
5030
5031 for (const auto& request : mRepeatingRequests) {
5032 for (const auto& s : request->mOutputStreams) {
5033 if (stream == s) return true;
5034 }
5035 if (stream == request->mInputStream) return true;
5036 }
5037
5038 return false;
5039}
Jianing Weicb0652e2014-03-12 18:29:36 -07005040
Emilian Peev40ead602017-09-26 15:46:36 +01005041bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5042 ATRACE_CALL();
5043 Mutex::Autolock l(mRequestLock);
5044
5045 for (const auto& nextRequest : mNextRequests) {
5046 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5047 if (s.first == streamId) {
5048 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5049 if (it != s.second.end()) {
5050 return true;
5051 }
5052 }
5053 }
5054 }
5055
5056 for (const auto& request : mRequestQueue) {
5057 for (const auto& s : request->mOutputSurfaces) {
5058 if (s.first == streamId) {
5059 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5060 if (it != s.second.end()) {
5061 return true;
5062 }
5063 }
5064 }
5065 }
5066
5067 for (const auto& request : mRepeatingRequests) {
5068 for (const auto& s : request->mOutputSurfaces) {
5069 if (s.first == streamId) {
5070 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5071 if (it != s.second.end()) {
5072 return true;
5073 }
5074 }
5075 }
5076 }
5077
5078 return false;
5079}
5080
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005081nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005082 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005083 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005084 return mExpectedInflightDuration > kMinInflightDuration ?
5085 mExpectedInflightDuration : kMinInflightDuration;
5086}
5087
Emilian Peevaebbe412018-01-15 13:53:24 +00005088void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5089 camera3_capture_request_t *halRequest) {
5090 if ((request == nullptr) || (halRequest == nullptr)) {
5091 ALOGE("%s: Invalid request!", __FUNCTION__);
5092 return;
5093 }
5094
5095 if (halRequest->num_physcam_settings > 0) {
5096 if (halRequest->physcam_id != nullptr) {
5097 delete [] halRequest->physcam_id;
5098 halRequest->physcam_id = nullptr;
5099 }
5100 if (halRequest->physcam_settings != nullptr) {
5101 auto it = ++(request->mSettingsList.begin());
5102 size_t i = 0;
5103 for (; it != request->mSettingsList.end(); it++, i++) {
5104 it->metadata.unlock(halRequest->physcam_settings[i]);
5105 }
5106 delete [] halRequest->physcam_settings;
5107 halRequest->physcam_settings = nullptr;
5108 }
5109 }
5110}
5111
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005112void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5113 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005114 return;
5115 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005116
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005117 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005118 // Skip the ones that have been submitted successfully.
5119 if (nextRequest.submitted) {
5120 continue;
5121 }
5122
5123 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5124 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5125 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5126
5127 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005128 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005129 }
5130
Emilian Peevaebbe412018-01-15 13:53:24 +00005131 cleanupPhysicalSettings(captureRequest, halRequest);
5132
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005133 if (captureRequest->mInputStream != NULL) {
5134 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5135 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5136 }
5137
5138 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005139 //Buffers that failed processing could still have
5140 //valid acquire fence.
5141 int acquireFence = (*outputBuffers)[i].acquire_fence;
5142 if (0 <= acquireFence) {
5143 close(acquireFence);
5144 outputBuffers->editItemAt(i).acquire_fence = -1;
5145 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005146 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5147 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5148 }
5149
5150 if (sendRequestError) {
5151 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005152 sp<NotificationListener> listener = mListener.promote();
5153 if (listener != NULL) {
5154 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005155 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005156 captureRequest->mResultExtras);
5157 }
5158 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005159
5160 // Remove yet-to-be submitted inflight request from inflightMap
5161 {
5162 sp<Camera3Device> parent = mParent.promote();
5163 if (parent != NULL) {
5164 Mutex::Autolock l(parent->mInFlightLock);
5165 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5166 if (idx >= 0) {
5167 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5168 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5169 parent->removeInFlightMapEntryLocked(idx);
5170 }
5171 }
5172 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005173 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005174
5175 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005176 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005177}
5178
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005179void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005180 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005181 // Optimized a bit for the simple steady-state case (single repeating
5182 // request), to avoid putting that request in the queue temporarily.
5183 Mutex::Autolock l(mRequestLock);
5184
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005185 assert(mNextRequests.empty());
5186
5187 NextRequest nextRequest;
5188 nextRequest.captureRequest = waitForNextRequestLocked();
5189 if (nextRequest.captureRequest == nullptr) {
5190 return;
5191 }
5192
5193 nextRequest.halRequest = camera3_capture_request_t();
5194 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005195 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005196
5197 // Wait for additional requests
5198 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5199
5200 for (size_t i = 1; i < batchSize; i++) {
5201 NextRequest additionalRequest;
5202 additionalRequest.captureRequest = waitForNextRequestLocked();
5203 if (additionalRequest.captureRequest == nullptr) {
5204 break;
5205 }
5206
5207 additionalRequest.halRequest = camera3_capture_request_t();
5208 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005209 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005210 }
5211
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005212 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005213 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005214 mNextRequests.size(), batchSize);
5215 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005216 }
5217
5218 return;
5219}
5220
5221sp<Camera3Device::CaptureRequest>
5222 Camera3Device::RequestThread::waitForNextRequestLocked() {
5223 status_t res;
5224 sp<CaptureRequest> nextRequest;
5225
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005226 while (mRequestQueue.empty()) {
5227 if (!mRepeatingRequests.empty()) {
5228 // Always atomically enqueue all requests in a repeating request
5229 // list. Guarantees a complete in-sequence set of captures to
5230 // application.
5231 const RequestList &requests = mRepeatingRequests;
5232 RequestList::const_iterator firstRequest =
5233 requests.begin();
5234 nextRequest = *firstRequest;
5235 mRequestQueue.insert(mRequestQueue.end(),
5236 ++firstRequest,
5237 requests.end());
5238 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005239
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005240 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005241
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005242 break;
5243 }
5244
5245 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5246
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005247 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5248 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005249 Mutex::Autolock pl(mPauseLock);
5250 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005251 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005252 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005253 // Let the tracker know
5254 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5255 if (statusTracker != 0) {
5256 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5257 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005258 }
5259 // Stop waiting for now and let thread management happen
5260 return NULL;
5261 }
5262 }
5263
5264 if (nextRequest == NULL) {
5265 // Don't have a repeating request already in hand, so queue
5266 // must have an entry now.
5267 RequestList::iterator firstRequest =
5268 mRequestQueue.begin();
5269 nextRequest = *firstRequest;
5270 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005271 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5272 sp<NotificationListener> listener = mListener.promote();
5273 if (listener != NULL) {
5274 listener->notifyRequestQueueEmpty();
5275 }
5276 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005277 }
5278
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005279 // In case we've been unpaused by setPaused clearing mDoPause, need to
5280 // update internal pause state (capture/setRepeatingRequest unpause
5281 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005282 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005283 if (mPaused) {
5284 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5285 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5286 if (statusTracker != 0) {
5287 statusTracker->markComponentActive(mStatusId);
5288 }
5289 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005290 mPaused = false;
5291
5292 // Check if we've reconfigured since last time, and reset the preview
5293 // request if so. Can't use 'NULL request == repeat' across configure calls.
5294 if (mReconfigured) {
5295 mPrevRequest.clear();
5296 mReconfigured = false;
5297 }
5298
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005299 if (nextRequest != NULL) {
5300 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005301 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5302 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005303
5304 // Since RequestThread::clear() removes buffers from the input stream,
5305 // get the right buffer here before unlocking mRequestLock
5306 if (nextRequest->mInputStream != NULL) {
5307 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5308 if (res != OK) {
5309 // Can't get input buffer from gralloc queue - this could be due to
5310 // disconnected queue or other producer misbehavior, so not a fatal
5311 // error
5312 ALOGE("%s: Can't get input buffer, skipping request:"
5313 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005314
5315 sp<NotificationListener> listener = mListener.promote();
5316 if (listener != NULL) {
5317 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005318 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005319 nextRequest->mResultExtras);
5320 }
5321 return NULL;
5322 }
5323 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005324 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005325
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005326 return nextRequest;
5327}
5328
5329bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005330 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005331 status_t res;
5332 Mutex::Autolock l(mPauseLock);
5333 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005334 if (mPaused == false) {
5335 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005336 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5337 // Let the tracker know
5338 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5339 if (statusTracker != 0) {
5340 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5341 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005342 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005343
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005344 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005345 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005346 return true;
5347 }
5348 }
5349 // We don't set mPaused to false here, because waitForNextRequest needs
5350 // to further manage the paused state in case of starvation.
5351 return false;
5352}
5353
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005354void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005355 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005356 // With work to do, mark thread as unpaused.
5357 // If paused by request (setPaused), don't resume, to avoid
5358 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005359 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005360 Mutex::Autolock p(mPauseLock);
5361 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005362 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5363 if (mPaused) {
5364 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5365 if (statusTracker != 0) {
5366 statusTracker->markComponentActive(mStatusId);
5367 }
5368 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005369 mPaused = false;
5370 }
5371}
5372
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005373void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5374 sp<Camera3Device> parent = mParent.promote();
5375 if (parent != NULL) {
5376 va_list args;
5377 va_start(args, fmt);
5378
5379 parent->setErrorStateV(fmt, args);
5380
5381 va_end(args);
5382 }
5383}
5384
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005385status_t Camera3Device::RequestThread::insertTriggers(
5386 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005387 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005388 Mutex::Autolock al(mTriggerMutex);
5389
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005390 sp<Camera3Device> parent = mParent.promote();
5391 if (parent == NULL) {
5392 CLOGE("RequestThread: Parent is gone");
5393 return DEAD_OBJECT;
5394 }
5395
Emilian Peevaebbe412018-01-15 13:53:24 +00005396 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005397 size_t count = mTriggerMap.size();
5398
5399 for (size_t i = 0; i < count; ++i) {
5400 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005401 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005402
5403 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5404 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5405 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005406 if (isAeTrigger) {
5407 request->mResultExtras.precaptureTriggerId = triggerId;
5408 mCurrentPreCaptureTriggerId = triggerId;
5409 } else {
5410 request->mResultExtras.afTriggerId = triggerId;
5411 mCurrentAfTriggerId = triggerId;
5412 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005413 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005414 }
5415
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005416 camera_metadata_entry entry = metadata.find(tag);
5417
5418 if (entry.count > 0) {
5419 /**
5420 * Already has an entry for this trigger in the request.
5421 * Rewrite it with our requested trigger value.
5422 */
5423 RequestTrigger oldTrigger = trigger;
5424
5425 oldTrigger.entryValue = entry.data.u8[0];
5426
5427 mTriggerReplacedMap.add(tag, oldTrigger);
5428 } else {
5429 /**
5430 * More typical, no trigger entry, so we just add it
5431 */
5432 mTriggerRemovedMap.add(tag, trigger);
5433 }
5434
5435 status_t res;
5436
5437 switch (trigger.getTagType()) {
5438 case TYPE_BYTE: {
5439 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5440 res = metadata.update(tag,
5441 &entryValue,
5442 /*count*/1);
5443 break;
5444 }
5445 case TYPE_INT32:
5446 res = metadata.update(tag,
5447 &trigger.entryValue,
5448 /*count*/1);
5449 break;
5450 default:
5451 ALOGE("%s: Type not supported: 0x%x",
5452 __FUNCTION__,
5453 trigger.getTagType());
5454 return INVALID_OPERATION;
5455 }
5456
5457 if (res != OK) {
5458 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5459 ", value %d", __FUNCTION__, trigger.getTagName(),
5460 trigger.entryValue);
5461 return res;
5462 }
5463
5464 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5465 trigger.getTagName(),
5466 trigger.entryValue);
5467 }
5468
5469 mTriggerMap.clear();
5470
5471 return count;
5472}
5473
5474status_t Camera3Device::RequestThread::removeTriggers(
5475 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005476 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005477 Mutex::Autolock al(mTriggerMutex);
5478
Emilian Peevaebbe412018-01-15 13:53:24 +00005479 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005480
5481 /**
5482 * Replace all old entries with their old values.
5483 */
5484 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5485 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5486
5487 status_t res;
5488
5489 uint32_t tag = trigger.metadataTag;
5490 switch (trigger.getTagType()) {
5491 case TYPE_BYTE: {
5492 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5493 res = metadata.update(tag,
5494 &entryValue,
5495 /*count*/1);
5496 break;
5497 }
5498 case TYPE_INT32:
5499 res = metadata.update(tag,
5500 &trigger.entryValue,
5501 /*count*/1);
5502 break;
5503 default:
5504 ALOGE("%s: Type not supported: 0x%x",
5505 __FUNCTION__,
5506 trigger.getTagType());
5507 return INVALID_OPERATION;
5508 }
5509
5510 if (res != OK) {
5511 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5512 ", trigger value %d", __FUNCTION__,
5513 trigger.getTagName(), trigger.entryValue);
5514 return res;
5515 }
5516 }
5517 mTriggerReplacedMap.clear();
5518
5519 /**
5520 * Remove all new entries.
5521 */
5522 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5523 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5524 status_t res = metadata.erase(trigger.metadataTag);
5525
5526 if (res != OK) {
5527 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5528 ", trigger value %d", __FUNCTION__,
5529 trigger.getTagName(), trigger.entryValue);
5530 return res;
5531 }
5532 }
5533 mTriggerRemovedMap.clear();
5534
5535 return OK;
5536}
5537
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005538status_t Camera3Device::RequestThread::addDummyTriggerIds(
5539 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005540 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005541 static const int32_t dummyTriggerId = 1;
5542 status_t res;
5543
Emilian Peevaebbe412018-01-15 13:53:24 +00005544 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005545
5546 // If AF trigger is active, insert a dummy AF trigger ID if none already
5547 // exists
5548 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5549 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5550 if (afTrigger.count > 0 &&
5551 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5552 afId.count == 0) {
5553 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5554 if (res != OK) return res;
5555 }
5556
5557 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5558 // if none already exists
5559 camera_metadata_entry pcTrigger =
5560 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5561 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5562 if (pcTrigger.count > 0 &&
5563 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5564 pcId.count == 0) {
5565 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5566 &dummyTriggerId, 1);
5567 if (res != OK) return res;
5568 }
5569
5570 return OK;
5571}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005572
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005573/**
5574 * PreparerThread inner class methods
5575 */
5576
5577Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005578 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005579 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005580}
5581
5582Camera3Device::PreparerThread::~PreparerThread() {
5583 Thread::requestExitAndWait();
5584 if (mCurrentStream != nullptr) {
5585 mCurrentStream->cancelPrepare();
5586 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5587 mCurrentStream.clear();
5588 }
5589 clear();
5590}
5591
Ruben Brunkc78ac262015-08-13 17:58:46 -07005592status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005593 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005594 status_t res;
5595
5596 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005597 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005598
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005599 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005600 if (res == OK) {
5601 // No preparation needed, fire listener right off
5602 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005603 if (listener != NULL) {
5604 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005605 }
5606 return OK;
5607 } else if (res != NOT_ENOUGH_DATA) {
5608 return res;
5609 }
5610
5611 // Need to prepare, start up thread if necessary
5612 if (!mActive) {
5613 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5614 // isn't running
5615 Thread::requestExitAndWait();
5616 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5617 if (res != OK) {
5618 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005619 if (listener != NULL) {
5620 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005621 }
5622 return res;
5623 }
5624 mCancelNow = false;
5625 mActive = true;
5626 ALOGV("%s: Preparer stream started", __FUNCTION__);
5627 }
5628
5629 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005630 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005631 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5632
5633 return OK;
5634}
5635
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005636void Camera3Device::PreparerThread::pause() {
5637 ATRACE_CALL();
5638
5639 Mutex::Autolock l(mLock);
5640
5641 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5642 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5643 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5644 int currentMaxCount = mCurrentMaxCount;
5645 mPendingStreams.clear();
5646 mCancelNow = true;
5647 while (mActive) {
5648 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5649 if (res == TIMED_OUT) {
5650 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5651 return;
5652 } else if (res != OK) {
5653 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5654 return;
5655 }
5656 }
5657
5658 //Check whether the prepare thread was able to complete the current
5659 //stream. In case work is still pending emplace it along with the rest
5660 //of the streams in the pending list.
5661 if (currentStream != nullptr) {
5662 if (!mCurrentPrepareComplete) {
5663 pendingStreams.emplace(currentMaxCount, currentStream);
5664 }
5665 }
5666
5667 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5668 for (const auto& it : mPendingStreams) {
5669 it.second->cancelPrepare();
5670 }
5671}
5672
5673status_t Camera3Device::PreparerThread::resume() {
5674 ATRACE_CALL();
5675 status_t res;
5676
5677 Mutex::Autolock l(mLock);
5678 sp<NotificationListener> listener = mListener.promote();
5679
5680 if (mActive) {
5681 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5682 return NO_INIT;
5683 }
5684
5685 auto it = mPendingStreams.begin();
5686 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005687 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005688 if (res == OK) {
5689 if (listener != NULL) {
5690 listener->notifyPrepared(it->second->getId());
5691 }
5692 it = mPendingStreams.erase(it);
5693 } else if (res != NOT_ENOUGH_DATA) {
5694 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5695 res, strerror(-res));
5696 it = mPendingStreams.erase(it);
5697 } else {
5698 it++;
5699 }
5700 }
5701
5702 if (mPendingStreams.empty()) {
5703 return OK;
5704 }
5705
5706 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5707 if (res != OK) {
5708 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5709 __FUNCTION__, res, strerror(-res));
5710 return res;
5711 }
5712 mCancelNow = false;
5713 mActive = true;
5714 ALOGV("%s: Preparer stream started", __FUNCTION__);
5715
5716 return OK;
5717}
5718
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005719status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005720 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005721 Mutex::Autolock l(mLock);
5722
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005723 for (const auto& it : mPendingStreams) {
5724 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005725 }
5726 mPendingStreams.clear();
5727 mCancelNow = true;
5728
5729 return OK;
5730}
5731
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005732void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005733 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005734 Mutex::Autolock l(mLock);
5735 mListener = listener;
5736}
5737
5738bool Camera3Device::PreparerThread::threadLoop() {
5739 status_t res;
5740 {
5741 Mutex::Autolock l(mLock);
5742 if (mCurrentStream == nullptr) {
5743 // End thread if done with work
5744 if (mPendingStreams.empty()) {
5745 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5746 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5747 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5748 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005749 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005750 return false;
5751 }
5752
5753 // Get next stream to prepare
5754 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005755 mCurrentStream = it->second;
5756 mCurrentMaxCount = it->first;
5757 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005758 mPendingStreams.erase(it);
5759 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5760 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5761 } else if (mCancelNow) {
5762 mCurrentStream->cancelPrepare();
5763 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5764 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5765 mCurrentStream.clear();
5766 mCancelNow = false;
5767 return true;
5768 }
5769 }
5770
5771 res = mCurrentStream->prepareNextBuffer();
5772 if (res == NOT_ENOUGH_DATA) return true;
5773 if (res != OK) {
5774 // Something bad happened; try to recover by cancelling prepare and
5775 // signalling listener anyway
5776 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5777 mCurrentStream->getId(), res, strerror(-res));
5778 mCurrentStream->cancelPrepare();
5779 }
5780
5781 // This stream has finished, notify listener
5782 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005783 sp<NotificationListener> listener = mListener.promote();
5784 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005785 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5786 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005787 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005788 }
5789
5790 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5791 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005792 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005793
5794 return true;
5795}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005796
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005797/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005798 * Static callback forwarding methods from HAL to instance
5799 */
5800
5801void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5802 const camera3_capture_result *result) {
5803 Camera3Device *d =
5804 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005805
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005806 d->processCaptureResult(result);
5807}
5808
5809void Camera3Device::sNotify(const camera3_callback_ops *cb,
5810 const camera3_notify_msg *msg) {
5811 Camera3Device *d =
5812 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5813 d->notify(msg);
5814}
5815
5816}; // namespace android