blob: 4c6718c5dbfd940dfea35c7cd342295e0d0b0977 [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Shuzhen Wang5c22c152017-12-31 17:12:25 -080042#include <utility>
43
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080044#include <utils/Log.h>
45#include <utils/Trace.h>
46#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070047#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070048
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080049#include <android/hardware/camera2/ICameraDeviceUser.h>
50
Igor Murashkinff3e31d2013-10-23 16:40:06 -070051#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070052#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "device3/Camera3Device.h"
54#include "device3/Camera3OutputStream.h"
55#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070056#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070057#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070058#include "CameraService.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080059
60using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080061using namespace android::hardware::camera;
62using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080063
64namespace android {
65
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080066Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080067 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080068 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070069 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070070 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070071 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070072 mUsePartialResult(false),
73 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080074 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070075 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070076 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070077 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070078 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000079 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010080 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
81 mLastTemplateId(-1)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080082{
83 ATRACE_CALL();
84 camera3_callback_ops::notify = &sNotify;
85 camera3_callback_ops::process_capture_result = &sProcessCaptureResult;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080086 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080087}
88
89Camera3Device::~Camera3Device()
90{
91 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080092 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080093 disconnect();
94}
95
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080096const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080097 return mId;
98}
99
Emilian Peevbd8c5032018-02-14 23:05:40 +0000100status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800101 ATRACE_CALL();
102 Mutex::Autolock il(mInterfaceLock);
103 Mutex::Autolock l(mLock);
104
105 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
106 if (mStatus != STATUS_UNINITIALIZED) {
107 CLOGE("Already initialized!");
108 return INVALID_OPERATION;
109 }
110 if (manager == nullptr) return INVALID_OPERATION;
111
112 sp<ICameraDeviceSession> session;
113 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800114 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800115 /*out*/ &session);
116 ATRACE_END();
117 if (res != OK) {
118 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
119 return res;
120 }
121
Steven Moreland5ff9c912017-03-09 23:13:00 -0800122 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700124 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125 session->close();
126 return res;
127 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800128
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700129 std::vector<std::string> physicalCameraIds;
130 bool isLogical = CameraProviderManager::isLogicalCamera(mDeviceInfo, &physicalCameraIds);
131 if (isLogical) {
132 for (auto& physicalId : physicalCameraIds) {
133 res = manager->getCameraCharacteristics(physicalId, &mPhysicalDeviceInfoMap[physicalId]);
134 if (res != OK) {
135 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
136 physicalId.c_str(), strerror(-res), res);
137 session->close();
138 return res;
139 }
140 }
141 }
142
Yifan Hongf79b5542017-04-11 14:44:25 -0700143 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700144 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
145 [&queue](const auto& descriptor) {
146 queue = std::make_shared<RequestMetadataQueue>(descriptor);
147 if (!queue->isValid() || queue->availableToWrite() <= 0) {
148 ALOGE("HAL returns empty request metadata fmq, not use it");
149 queue = nullptr;
150 // don't use the queue onwards.
151 }
152 });
153 if (!requestQueueRet.isOk()) {
154 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
155 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700156 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700157 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700158
159 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700160 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700161 [&resQueue](const auto& descriptor) {
162 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
163 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700164 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700165 resQueue = nullptr;
166 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700167 }
168 });
169 if (!resultQueueRet.isOk()) {
170 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
171 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700172 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700173 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700174 IF_ALOGV() {
175 session->interfaceChain([](
176 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
177 ALOGV("Session interface chain:");
178 for (auto iface : interfaceChain) {
179 ALOGV(" %s", iface.c_str());
180 }
181 });
182 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700183
Yin-Chia Yehdb1e8642017-07-14 15:19:30 -0700184 mInterface = new HalInterface(session, queue);
Emilian Peev71c73a22017-03-21 16:35:51 +0000185 std::string providerType;
186 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000187 mTagMonitor.initialize(mVendorTagId);
188 if (!monitorTags.isEmpty()) {
189 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
190 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800191
192 return initializeCommonLocked();
193}
194
195status_t Camera3Device::initializeCommonLocked() {
196
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700197 /** Start up status tracker thread */
198 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800199 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700200 if (res != OK) {
201 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
202 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800203 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700204 mStatusTracker.clear();
205 return res;
206 }
207
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700208 /** Register in-flight map to the status tracker */
209 mInFlightStatusId = mStatusTracker->addComponent();
210
Zhijun He125684a2015-12-26 15:07:30 -0800211 /** Create buffer manager */
212 mBufferManager = new Camera3BufferManager();
213
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000214 Vector<int32_t> sessionParamKeys;
215 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
216 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
217 if (sessionKeysEntry.count > 0) {
218 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
219 }
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700220 /** Start up request queue thread */
Emilian Peevac3ce6c2017-12-12 15:27:02 +0000221 mRequestThread = new RequestThread(this, mStatusTracker, mInterface, sessionParamKeys);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800222 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800223 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700224 SET_ERR_L("Unable to start request queue thread: %s (%d)",
225 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800226 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800227 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800228 return res;
229 }
230
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700231 mPreparerThread = new PreparerThread();
232
Ruben Brunk183f0562015-08-12 12:55:02 -0700233 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800234 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700235 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700236 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700237 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800238
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800239 // Measure the clock domain offset between camera and video/hw_composer
240 camera_metadata_entry timestampSource =
241 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
242 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
243 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
244 mTimestampOffset = getMonoToBoottimeOffset();
245 }
246
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700247 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100248 camera_metadata_entry partialResultsCount =
249 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
250 if (partialResultsCount.count > 0) {
251 mNumPartialResults = partialResultsCount.data.i32[0];
252 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700253 }
254
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700255 camera_metadata_entry configs =
256 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
257 for (uint32_t i = 0; i < configs.count; i += 4) {
258 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
259 configs.data.i32[i + 3] ==
260 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
261 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
262 configs.data.i32[i + 2]));
263 }
264 }
265
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700266 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
267 res = mDistortionMapper.setupStaticInfo(mDeviceInfo);
268 if (res != OK) {
269 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
270 return res;
271 }
272 }
273
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800274 return OK;
275}
276
277status_t Camera3Device::disconnect() {
278 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700279 Mutex::Autolock il(mInterfaceLock);
Emilian Peev26d975d2018-07-05 14:52:57 +0100280 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800281
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700282 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800283
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700284 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700285 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700286 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700287 {
288 Mutex::Autolock l(mLock);
289 if (mStatus == STATUS_UNINITIALIZED) return res;
290
291 if (mStatus == STATUS_ACTIVE ||
292 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
293 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700294 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700295 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700296 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700297 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700298 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700299 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700300 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
301 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700302 // Continue to close device even in case of error
303 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700304 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800305 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800306
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700307 if (mStatus == STATUS_ERROR) {
308 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700309 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700310
311 if (mStatusTracker != NULL) {
312 mStatusTracker->requestExit();
313 }
314
315 if (mRequestThread != NULL) {
316 mRequestThread->requestExit();
317 }
318
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700319 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
320 for (size_t i = 0; i < mOutputStreams.size(); i++) {
321 streams.push_back(mOutputStreams[i]);
322 }
323 if (mInputStream != nullptr) {
324 streams.push_back(mInputStream);
325 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700326 }
327
328 // Joining done without holding mLock, otherwise deadlocks may ensue
329 // as the threads try to access parent state
330 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
331 // HAL may be in a bad state, so waiting for request thread
332 // (which may be stuck in the HAL processCaptureRequest call)
333 // could be dangerous.
334 mRequestThread->join();
335 }
336
337 if (mStatusTracker != NULL) {
338 mStatusTracker->join();
339 }
340
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800341 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700342 {
343 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800344 mRequestThread.clear();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700345 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800346 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700347 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800348
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700349 // Call close without internal mutex held, as the HAL close may need to
350 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800351 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700352
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700353 flushInflightRequests();
354
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700355 {
356 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800357 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700358 mOutputStreams.clear();
359 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700360 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700361 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700362 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700363 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800364
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700365 for (auto& weakStream : streams) {
366 sp<Camera3StreamInterface> stream = weakStream.promote();
367 if (stream != nullptr) {
368 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
369 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
370 }
371 }
372
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700373 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700374 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800375}
376
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700377// For dumping/debugging only -
378// try to acquire a lock a few times, eventually give up to proceed with
379// debug/dump operations
380bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
381 bool gotLock = false;
382 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
383 if (lock.tryLock() == NO_ERROR) {
384 gotLock = true;
385 break;
386 } else {
387 usleep(kDumpSleepDuration);
388 }
389 }
390 return gotLock;
391}
392
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700393Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
394 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100395 const int STREAM_CONFIGURATION_SIZE = 4;
396 const int STREAM_FORMAT_OFFSET = 0;
397 const int STREAM_WIDTH_OFFSET = 1;
398 const int STREAM_HEIGHT_OFFSET = 2;
399 const int STREAM_IS_INPUT_OFFSET = 3;
400 camera_metadata_ro_entry_t availableStreamConfigs =
401 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
402 if (availableStreamConfigs.count == 0 ||
403 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
404 return Size(0, 0);
405 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700406
Emilian Peev08dd2452017-04-06 16:55:14 +0100407 // Get max jpeg size (area-wise).
408 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
409 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
410 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
411 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
412 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
413 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
414 && format == HAL_PIXEL_FORMAT_BLOB &&
415 (width * height > maxJpegWidth * maxJpegHeight)) {
416 maxJpegWidth = width;
417 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700418 }
419 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100420
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700421 return Size(maxJpegWidth, maxJpegHeight);
422}
423
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800424nsecs_t Camera3Device::getMonoToBoottimeOffset() {
425 // try three times to get the clock offset, choose the one
426 // with the minimum gap in measurements.
427 const int tries = 3;
428 nsecs_t bestGap, measured;
429 for (int i = 0; i < tries; ++i) {
430 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
431 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
432 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
433 const nsecs_t gap = tmono2 - tmono;
434 if (i == 0 || gap < bestGap) {
435 bestGap = gap;
436 measured = tbase - ((tmono + tmono2) >> 1);
437 }
438 }
439 return measured;
440}
441
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800442hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
443 int frameworkFormat) {
444 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
445}
446
447DataspaceFlags Camera3Device::mapToHidlDataspace(
448 android_dataspace dataSpace) {
449 return dataSpace;
450}
451
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700452BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100453 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700454 return usage;
455}
456
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800457StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
458 switch (rotation) {
459 case CAMERA3_STREAM_ROTATION_0:
460 return StreamRotation::ROTATION_0;
461 case CAMERA3_STREAM_ROTATION_90:
462 return StreamRotation::ROTATION_90;
463 case CAMERA3_STREAM_ROTATION_180:
464 return StreamRotation::ROTATION_180;
465 case CAMERA3_STREAM_ROTATION_270:
466 return StreamRotation::ROTATION_270;
467 }
468 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
469 return StreamRotation::ROTATION_0;
470}
471
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800472status_t Camera3Device::mapToStreamConfigurationMode(
473 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
474 if (mode == nullptr) return BAD_VALUE;
475 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
476 switch(operationMode) {
477 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
478 *mode = StreamConfigurationMode::NORMAL_MODE;
479 break;
480 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
481 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
482 break;
483 default:
484 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
485 return BAD_VALUE;
486 }
487 } else {
488 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800489 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800490 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800491}
492
493camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
494 switch (status) {
495 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
496 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
497 }
498 return CAMERA3_BUFFER_STATUS_ERROR;
499}
500
501int Camera3Device::mapToFrameworkFormat(
502 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
503 return static_cast<uint32_t>(pixelFormat);
504}
505
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700506android_dataspace Camera3Device::mapToFrameworkDataspace(
507 DataspaceFlags dataSpace) {
508 return static_cast<android_dataspace>(dataSpace);
509}
510
Emilian Peev050f5dc2017-05-18 14:43:56 +0100511uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700512 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700513 return usage;
514}
515
Emilian Peev050f5dc2017-05-18 14:43:56 +0100516uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700517 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700518 return usage;
519}
520
Zhijun Hef7da0962014-04-24 13:27:56 -0700521ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700522 // Get max jpeg size (area-wise).
523 Size maxJpegResolution = getMaxJpegResolution();
524 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800525 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
526 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700527 return BAD_VALUE;
528 }
529
Zhijun Hef7da0962014-04-24 13:27:56 -0700530 // Get max jpeg buffer size
531 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700532 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
533 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800534 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
535 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700536 return BAD_VALUE;
537 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700538 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800539 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700540
541 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700542 float scaleFactor = ((float) (width * height)) /
543 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800544 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
545 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700546 if (jpegBufferSize > maxJpegBufferSize) {
547 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700548 }
549
550 return jpegBufferSize;
551}
552
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700553ssize_t Camera3Device::getPointCloudBufferSize() const {
554 const int FLOATS_PER_POINT=4;
555 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
556 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800557 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
558 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700559 return BAD_VALUE;
560 }
561 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
562 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
563 return maxBytesForPointCloud;
564}
565
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800566ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800567 const int PER_CONFIGURATION_SIZE = 3;
568 const int WIDTH_OFFSET = 0;
569 const int HEIGHT_OFFSET = 1;
570 const int SIZE_OFFSET = 2;
571 camera_metadata_ro_entry rawOpaqueSizes =
572 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800573 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800574 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800575 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
576 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800577 return BAD_VALUE;
578 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700579
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800580 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
581 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
582 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
583 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
584 }
585 }
586
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800587 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
588 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800589 return BAD_VALUE;
590}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700591
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800592status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
593 ATRACE_CALL();
594 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700595
596 // Try to lock, but continue in case of failure (to avoid blocking in
597 // deadlocks)
598 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
599 bool gotLock = tryLockSpinRightRound(mLock);
600
601 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800602 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
603 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700604 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800605 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
606 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700607
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800608 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700609
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800610 String16 templatesOption("-t");
611 int n = args.size();
612 for (int i = 0; i < n; i++) {
613 if (args[i] == templatesOption) {
614 dumpTemplates = true;
615 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000616 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700617 if (i + 1 < n) {
618 String8 monitorTags = String8(args[i + 1]);
619 if (monitorTags == "off") {
620 mTagMonitor.disableMonitoring();
621 } else {
622 mTagMonitor.parseTagsToMonitor(monitorTags);
623 }
624 } else {
625 mTagMonitor.disableMonitoring();
626 }
627 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800628 }
629
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800630 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800631
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800632 const char *status =
633 mStatus == STATUS_ERROR ? "ERROR" :
634 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700635 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
636 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800637 mStatus == STATUS_ACTIVE ? "ACTIVE" :
638 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700639
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800640 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700641 if (mStatus == STATUS_ERROR) {
642 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
643 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800644 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800645 const char *mode =
646 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
647 mOperatingMode == static_cast<int>(
648 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
649 "CUSTOM";
650 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800651
652 if (mInputStream != NULL) {
653 write(fd, lines.string(), lines.size());
654 mInputStream->dump(fd, args);
655 } else {
656 lines.appendFormat(" No input stream.\n");
657 write(fd, lines.string(), lines.size());
658 }
659 for (size_t i = 0; i < mOutputStreams.size(); i++) {
660 mOutputStreams[i]->dump(fd,args);
661 }
662
Zhijun He431503c2016-03-07 17:30:16 -0800663 if (mBufferManager != NULL) {
664 lines = String8(" Camera3 Buffer Manager:\n");
665 write(fd, lines.string(), lines.size());
666 mBufferManager->dump(fd, args);
667 }
Zhijun He125684a2015-12-26 15:07:30 -0800668
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700669 lines = String8(" In-flight requests:\n");
670 if (mInFlightMap.size() == 0) {
671 lines.append(" None\n");
672 } else {
673 for (size_t i = 0; i < mInFlightMap.size(); i++) {
674 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700675 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700676 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800677 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700678 r.numBuffersLeft);
679 }
680 }
681 write(fd, lines.string(), lines.size());
682
Shuzhen Wang686f6442017-06-20 16:16:04 -0700683 if (mRequestThread != NULL) {
684 mRequestThread->dumpCaptureRequestLatency(fd,
685 " ProcessCaptureRequest latency histogram:");
686 }
687
Igor Murashkin1e479c02013-09-06 16:55:14 -0700688 {
689 lines = String8(" Last request sent:\n");
690 write(fd, lines.string(), lines.size());
691
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700692 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700693 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
694 }
695
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800696 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800697 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800698 "TEMPLATE_PREVIEW",
699 "TEMPLATE_STILL_CAPTURE",
700 "TEMPLATE_VIDEO_RECORD",
701 "TEMPLATE_VIDEO_SNAPSHOT",
702 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800703 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800704 };
705
706 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800707 camera_metadata_t *templateRequest = nullptr;
708 mInterface->constructDefaultRequestSettings(
709 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800710 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800711 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800712 lines.append(" Not supported\n");
713 write(fd, lines.string(), lines.size());
714 } else {
715 write(fd, lines.string(), lines.size());
716 dump_indented_camera_metadata(templateRequest,
717 fd, /*verbosity*/2, /*indentation*/8);
718 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800719 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800720 }
721 }
722
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700723 mTagMonitor.dumpMonitoredMetadata(fd);
724
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800725 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800726 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800727 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800728 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800729 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800730
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700731 if (gotLock) mLock.unlock();
732 if (gotInterfaceLock) mInterfaceLock.unlock();
733
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800734 return OK;
735}
736
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700737const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800738 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800739 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
740 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700741 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800742 mStatus == STATUS_ERROR ?
743 "when in error state" : "before init");
744 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700745 if (physicalId.isEmpty()) {
746 return mDeviceInfo;
747 } else {
748 std::string id(physicalId.c_str());
749 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
750 return mPhysicalDeviceInfoMap.at(id);
751 } else {
752 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
753 return mDeviceInfo;
754 }
755 }
756}
757
758const CameraMetadata& Camera3Device::info() const {
759 String8 emptyId;
760 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800761}
762
Jianing Wei90e59c92014-03-12 18:29:36 -0700763status_t Camera3Device::checkStatusOkToCaptureLocked() {
764 switch (mStatus) {
765 case STATUS_ERROR:
766 CLOGE("Device has encountered a serious error");
767 return INVALID_OPERATION;
768 case STATUS_UNINITIALIZED:
769 CLOGE("Device not initialized");
770 return INVALID_OPERATION;
771 case STATUS_UNCONFIGURED:
772 case STATUS_CONFIGURED:
773 case STATUS_ACTIVE:
774 // OK
775 break;
776 default:
777 SET_ERR_L("Unexpected status: %d", mStatus);
778 return INVALID_OPERATION;
779 }
780 return OK;
781}
782
783status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000784 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700785 const std::list<const SurfaceMap> &surfaceMaps,
786 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700787 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700788 if (requestList == NULL) {
789 CLOGE("requestList cannot be NULL.");
790 return BAD_VALUE;
791 }
792
Jianing Weicb0652e2014-03-12 18:29:36 -0700793 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000794 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700795 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
796 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
797 ++metadataIt, ++surfaceMapIt) {
798 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700799 if (newRequest == 0) {
800 CLOGE("Can't create capture request");
801 return BAD_VALUE;
802 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700803
Shuzhen Wang9d066012016-09-30 11:30:20 -0700804 newRequest->mRepeating = repeating;
805
Jianing Weicb0652e2014-03-12 18:29:36 -0700806 // Setup burst Id and request Id
807 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000808 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
809 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700810 CLOGE("RequestID entry exists; but must not be empty in metadata");
811 return BAD_VALUE;
812 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000813 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
814 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700815 } else {
816 CLOGE("RequestID does not exist in metadata");
817 return BAD_VALUE;
818 }
819
Jianing Wei90e59c92014-03-12 18:29:36 -0700820 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700821
822 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700823 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700824 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
825 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
826 return BAD_VALUE;
827 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700828
829 // Setup batch size if this is a high speed video recording request.
830 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
831 auto firstRequest = requestList->begin();
832 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
833 if (outputStream->isVideoStream()) {
834 (*firstRequest)->mBatchSize = requestList->size();
835 break;
836 }
837 }
838 }
839
Jianing Wei90e59c92014-03-12 18:29:36 -0700840 return OK;
841}
842
Jianing Weicb0652e2014-03-12 18:29:36 -0700843status_t Camera3Device::capture(CameraMetadata &request, int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800844 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800845
Emilian Peevaebbe412018-01-15 13:53:24 +0000846 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700847 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000848 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700849
Emilian Peevaebbe412018-01-15 13:53:24 +0000850 return captureList(requestsList, surfaceMaps, /*lastFrameNumber*/NULL);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700851}
852
Emilian Peevaebbe412018-01-15 13:53:24 +0000853void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700854 std::list<const SurfaceMap>& surfaceMaps,
855 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000856 PhysicalCameraSettingsList requestList;
857 requestList.push_back({std::string(getId().string()), request});
858 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700859
860 SurfaceMap surfaceMap;
861 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
862 // With no surface list passed in, stream and surface will have 1-to-1
863 // mapping. So the surface index is 0 for each stream in the surfaceMap.
864 for (size_t i = 0; i < streams.count; i++) {
865 surfaceMap[streams.data.i32[i]].push_back(0);
866 }
867 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800868}
869
Jianing Wei90e59c92014-03-12 18:29:36 -0700870status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000871 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700872 const std::list<const SurfaceMap> &surfaceMaps,
873 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700874 /*out*/
875 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700876 ATRACE_CALL();
877 Mutex::Autolock il(mInterfaceLock);
878 Mutex::Autolock l(mLock);
879
880 status_t res = checkStatusOkToCaptureLocked();
881 if (res != OK) {
882 // error logged by previous call
883 return res;
884 }
885
886 RequestList requestList;
887
Shuzhen Wang0129d522016-10-30 22:43:41 -0700888 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
889 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700890 if (res != OK) {
891 // error logged by previous call
892 return res;
893 }
894
895 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700896 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700897 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700898 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700899 }
900
901 if (res == OK) {
902 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
903 if (res != OK) {
904 SET_ERR_L("Can't transition to active in %f seconds!",
905 kActiveTimeout/1e9);
906 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800907 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700908 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700909 } else {
910 CLOGE("Cannot queue request. Impossible.");
911 return BAD_VALUE;
912 }
913
914 return res;
915}
916
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800917hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800918 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800919 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -0700920 // Ideally we should grab mLock, but that can lead to deadlock, and
921 // it's not super important to get up to date value of mStatus for this
922 // warning print, hence skipping the lock here
923 if (mStatus == STATUS_ERROR) {
924 // Per API contract, HAL should act as closed after device error
925 // But mStatus can be set to error by framework as well, so just log
926 // a warning here.
927 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700928 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700929
930 if (mProcessCaptureResultLock.tryLock() != OK) {
931 // This should never happen; it indicates a wrong client implementation
932 // that doesn't follow the contract. But, we can be tolerant here.
933 ALOGE("%s: callback overlapped! waiting 1s...",
934 __FUNCTION__);
935 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
936 ALOGE("%s: cannot acquire lock in 1s, dropping results",
937 __FUNCTION__);
938 // really don't know what to do, so bail out.
939 return hardware::Void();
940 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800941 }
Yifan Honga640c5a2017-04-12 16:30:31 -0700942 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800943 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -0700944 }
945 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -0800946 return hardware::Void();
947}
948
Shuzhen Wang5c22c152017-12-31 17:12:25 -0800949// Only one processCaptureResult should be called at a time, so
950// the locks won't block. The locks are present here simply to enforce this.
951hardware::Return<void> Camera3Device::processCaptureResult(
952 const hardware::hidl_vec<
953 hardware::camera::device::V3_2::CaptureResult>& results) {
954 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
955
956 // Ideally we should grab mLock, but that can lead to deadlock, and
957 // it's not super important to get up to date value of mStatus for this
958 // warning print, hence skipping the lock here
959 if (mStatus == STATUS_ERROR) {
960 // Per API contract, HAL should act as closed after device error
961 // But mStatus can be set to error by framework as well, so just log
962 // a warning here.
963 ALOGW("%s: received capture result in error state.", __FUNCTION__);
964 }
965
966 if (mProcessCaptureResultLock.tryLock() != OK) {
967 // This should never happen; it indicates a wrong client implementation
968 // that doesn't follow the contract. But, we can be tolerant here.
969 ALOGE("%s: callback overlapped! waiting 1s...",
970 __FUNCTION__);
971 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
972 ALOGE("%s: cannot acquire lock in 1s, dropping results",
973 __FUNCTION__);
974 // really don't know what to do, so bail out.
975 return hardware::Void();
976 }
977 }
978 for (const auto& result : results) {
979 processOneCaptureResultLocked(result, noPhysMetadata);
980 }
981 mProcessCaptureResultLock.unlock();
982 return hardware::Void();
983}
984
985status_t Camera3Device::readOneCameraMetadataLocked(
986 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
987 const hardware::camera::device::V3_2::CameraMetadata& result) {
988 if (fmqResultSize > 0) {
989 resultMetadata.resize(fmqResultSize);
990 if (mResultMetadataQueue == nullptr) {
991 return NO_MEMORY; // logged in initialize()
992 }
993 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
994 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
995 __FUNCTION__, fmqResultSize);
996 return INVALID_OPERATION;
997 }
998 } else {
999 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1000 result.size());
1001 }
1002
1003 if (resultMetadata.size() != 0) {
1004 status_t res;
1005 const camera_metadata_t* metadata =
1006 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1007 size_t expected_metadata_size = resultMetadata.size();
1008 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1009 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1010 __FUNCTION__, strerror(-res), res);
1011 return INVALID_OPERATION;
1012 }
1013 }
1014
1015 return OK;
1016}
1017
Yifan Honga640c5a2017-04-12 16:30:31 -07001018void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001019 const hardware::camera::device::V3_2::CaptureResult& result,
1020 const hardware::hidl_vec<
1021 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001022 camera3_capture_result r;
1023 status_t res;
1024 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001025
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001026 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001027 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001028 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1029 if (res != OK) {
1030 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1031 __FUNCTION__, result.frameNumber);
1032 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001033 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001034 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001035
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001036 // Read and validate physical camera metadata
1037 size_t physResultCount = physicalCameraMetadatas.size();
1038 std::vector<const char*> physCamIds(physResultCount);
1039 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1040 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1041 physResultMetadata.resize(physResultCount);
1042 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1043 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1044 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1045 if (res != OK) {
1046 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1047 __FUNCTION__, result.frameNumber,
1048 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001049 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001050 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001051 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1052 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1053 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001054 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001055 r.num_physcam_metadata = physResultCount;
1056 r.physcam_ids = physCamIds.data();
1057 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001058
1059 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1060 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1061 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1062 auto& bDst = outputBuffers[i];
1063 const StreamBuffer &bSrc = result.outputBuffers[i];
1064
1065 ssize_t idx = mOutputStreams.indexOfKey(bSrc.streamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001066 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001067 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1068 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001069 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001070 }
1071 bDst.stream = mOutputStreams.valueAt(idx)->asHalStream();
1072
1073 buffer_handle_t *buffer;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08001074 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001075 if (res != OK) {
1076 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1077 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001078 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001079 }
1080 bDst.buffer = buffer;
1081 bDst.status = mapHidlBufferStatus(bSrc.status);
1082 bDst.acquire_fence = -1;
1083 if (bSrc.releaseFence == nullptr) {
1084 bDst.release_fence = -1;
1085 } else if (bSrc.releaseFence->numFds == 1) {
1086 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1087 } else {
1088 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1089 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001090 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001091 }
1092 }
1093 r.num_output_buffers = outputBuffers.size();
1094 r.output_buffers = outputBuffers.data();
1095
1096 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001097 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001098 r.input_buffer = nullptr;
1099 } else {
1100 if (mInputStream->getId() != result.inputBuffer.streamId) {
1101 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1102 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001103 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001104 }
1105 inputBuffer.stream = mInputStream->asHalStream();
1106 buffer_handle_t *buffer;
1107 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1108 &buffer);
1109 if (res != OK) {
1110 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1111 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001112 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001113 }
1114 inputBuffer.buffer = buffer;
1115 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1116 inputBuffer.acquire_fence = -1;
1117 if (result.inputBuffer.releaseFence == nullptr) {
1118 inputBuffer.release_fence = -1;
1119 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1120 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1121 } else {
1122 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1123 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001124 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001125 }
1126 r.input_buffer = &inputBuffer;
1127 }
1128
1129 r.partial_result = result.partialResult;
1130
1131 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001132}
1133
1134hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001135 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001136 // Ideally we should grab mLock, but that can lead to deadlock, and
1137 // it's not super important to get up to date value of mStatus for this
1138 // warning print, hence skipping the lock here
1139 if (mStatus == STATUS_ERROR) {
1140 // Per API contract, HAL should act as closed after device error
1141 // But mStatus can be set to error by framework as well, so just log
1142 // a warning here.
1143 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001144 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001145
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001146 for (const auto& msg : msgs) {
1147 notify(msg);
1148 }
1149 return hardware::Void();
1150}
1151
1152void Camera3Device::notify(
1153 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1154
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001155 camera3_notify_msg m;
1156 switch (msg.type) {
1157 case MsgType::ERROR:
1158 m.type = CAMERA3_MSG_ERROR;
1159 m.message.error.frame_number = msg.msg.error.frameNumber;
1160 if (msg.msg.error.errorStreamId >= 0) {
1161 ssize_t idx = mOutputStreams.indexOfKey(msg.msg.error.errorStreamId);
Emilian Peevbe3d40c2017-03-27 13:03:10 +01001162 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001163 ALOGE("%s: Frame %d: Invalid error stream id %d",
1164 __FUNCTION__, m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001165 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001166 }
1167 m.message.error.error_stream = mOutputStreams.valueAt(idx)->asHalStream();
1168 } else {
1169 m.message.error.error_stream = nullptr;
1170 }
1171 switch (msg.msg.error.errorCode) {
1172 case ErrorCode::ERROR_DEVICE:
1173 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1174 break;
1175 case ErrorCode::ERROR_REQUEST:
1176 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1177 break;
1178 case ErrorCode::ERROR_RESULT:
1179 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1180 break;
1181 case ErrorCode::ERROR_BUFFER:
1182 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1183 break;
1184 }
1185 break;
1186 case MsgType::SHUTTER:
1187 m.type = CAMERA3_MSG_SHUTTER;
1188 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1189 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1190 break;
1191 }
1192 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001193}
1194
Emilian Peevaebbe412018-01-15 13:53:24 +00001195status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001196 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001197 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001198 ATRACE_CALL();
1199
Emilian Peevaebbe412018-01-15 13:53:24 +00001200 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001201}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001202
Jianing Weicb0652e2014-03-12 18:29:36 -07001203status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1204 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001205 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001206
Emilian Peevaebbe412018-01-15 13:53:24 +00001207 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001208 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001209 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001210
Emilian Peevaebbe412018-01-15 13:53:24 +00001211 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001212 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001213}
1214
Emilian Peevaebbe412018-01-15 13:53:24 +00001215status_t Camera3Device::setStreamingRequestList(
1216 const List<const PhysicalCameraSettingsList> &requestsList,
1217 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001218 ATRACE_CALL();
1219
Emilian Peevaebbe412018-01-15 13:53:24 +00001220 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001221}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001222
1223sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001224 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001225 status_t res;
1226
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001227 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001228 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1229 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001230 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1231 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001232 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001233 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001234 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001235 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001236 } else if (mStatus == STATUS_UNCONFIGURED) {
1237 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001238 CLOGE("No streams configured");
1239 return NULL;
1240 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001241 }
1242
Shuzhen Wang0129d522016-10-30 22:43:41 -07001243 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001244 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001245}
1246
Jianing Weicb0652e2014-03-12 18:29:36 -07001247status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001248 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001249 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001250 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001251
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001252 switch (mStatus) {
1253 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001254 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001255 return INVALID_OPERATION;
1256 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001257 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001258 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001259 case STATUS_UNCONFIGURED:
1260 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001261 case STATUS_ACTIVE:
1262 // OK
1263 break;
1264 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001265 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001266 return INVALID_OPERATION;
1267 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001268 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001269
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001270 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001271}
1272
1273status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1274 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001275 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001276
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001277 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001278}
1279
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001280status_t Camera3Device::createInputStream(
1281 uint32_t width, uint32_t height, int format, int *id) {
1282 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001283 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001284 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001285 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001286 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1287 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001288
1289 status_t res;
1290 bool wasActive = false;
1291
1292 switch (mStatus) {
1293 case STATUS_ERROR:
1294 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1295 return INVALID_OPERATION;
1296 case STATUS_UNINITIALIZED:
1297 ALOGE("%s: Device not initialized", __FUNCTION__);
1298 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001299 case STATUS_UNCONFIGURED:
1300 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001301 // OK
1302 break;
1303 case STATUS_ACTIVE:
1304 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001305 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001306 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001307 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001308 return res;
1309 }
1310 wasActive = true;
1311 break;
1312 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001313 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001314 return INVALID_OPERATION;
1315 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001316 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001317
1318 if (mInputStream != 0) {
1319 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1320 return INVALID_OPERATION;
1321 }
1322
1323 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1324 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001325 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001326
1327 mInputStream = newStream;
1328
1329 *id = mNextStreamId++;
1330
1331 // Continue captures if active at start
1332 if (wasActive) {
1333 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001334 // Reuse current operating mode and session parameters for new stream config
1335 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001336 if (res != OK) {
1337 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1338 __FUNCTION__, mNextStreamId, strerror(-res), res);
1339 return res;
1340 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001341 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001342 }
1343
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001344 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001345 return OK;
1346}
1347
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001348status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001349 uint32_t width, uint32_t height, int format,
1350 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001351 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001352 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001353 ATRACE_CALL();
1354
1355 if (consumer == nullptr) {
1356 ALOGE("%s: consumer must not be null", __FUNCTION__);
1357 return BAD_VALUE;
1358 }
1359
1360 std::vector<sp<Surface>> consumers;
1361 consumers.push_back(consumer);
1362
1363 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001364 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1365 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001366}
1367
1368status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1369 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1370 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001371 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001372 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001373 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001374
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001375 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001376 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001377 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001378 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001379 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1380 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1381 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001382
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001383 status_t res;
1384 bool wasActive = false;
1385
1386 switch (mStatus) {
1387 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001388 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001389 return INVALID_OPERATION;
1390 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001391 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001392 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001393 case STATUS_UNCONFIGURED:
1394 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001395 // OK
1396 break;
1397 case STATUS_ACTIVE:
1398 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001399 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001400 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001401 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001402 return res;
1403 }
1404 wasActive = true;
1405 break;
1406 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001407 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001408 return INVALID_OPERATION;
1409 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001410 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001411
1412 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001413
Shuzhen Wang0129d522016-10-30 22:43:41 -07001414 if (consumers.size() == 0 && !hasDeferredConsumer) {
1415 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1416 return BAD_VALUE;
1417 }
Zhijun He5d677d12016-05-29 16:52:39 -07001418
Shuzhen Wang0129d522016-10-30 22:43:41 -07001419 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001420 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1421 return BAD_VALUE;
1422 }
1423
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001424 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001425 ssize_t blobBufferSize;
1426 if (dataSpace != HAL_DATASPACE_DEPTH) {
1427 blobBufferSize = getJpegBufferSize(width, height);
1428 if (blobBufferSize <= 0) {
1429 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1430 return BAD_VALUE;
1431 }
1432 } else {
1433 blobBufferSize = getPointCloudBufferSize();
1434 if (blobBufferSize <= 0) {
1435 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1436 return BAD_VALUE;
1437 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001438 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001439 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001440 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001441 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001442 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1443 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1444 if (rawOpaqueBufferSize <= 0) {
1445 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1446 return BAD_VALUE;
1447 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001448 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001449 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001450 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001451 } else if (isShared) {
1452 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1453 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001454 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001455 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001456 newStream = new Camera3OutputStream(mNextStreamId,
1457 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001458 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001459 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001460 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001461 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001462 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001463 }
Emilian Peev40ead602017-09-26 15:46:36 +01001464
1465 size_t consumerCount = consumers.size();
1466 for (size_t i = 0; i < consumerCount; i++) {
1467 int id = newStream->getSurfaceId(consumers[i]);
1468 if (id < 0) {
1469 SET_ERR_L("Invalid surface id");
1470 return BAD_VALUE;
1471 }
1472 if (surfaceIds != nullptr) {
1473 surfaceIds->push_back(id);
1474 }
1475 }
1476
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001477 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001478
Emilian Peev08dd2452017-04-06 16:55:14 +01001479 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001480
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001481 res = mOutputStreams.add(mNextStreamId, newStream);
1482 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001483 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001484 return res;
1485 }
1486
1487 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001488 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001489
1490 // Continue captures if active at start
1491 if (wasActive) {
1492 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001493 // Reuse current operating mode and session parameters for new stream config
1494 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001495 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001496 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1497 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001498 return res;
1499 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001500 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001501 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001502 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001503 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001504}
1505
Emilian Peev710c1422017-08-30 11:19:38 +01001506status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001507 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001508 if (nullptr == streamInfo) {
1509 return BAD_VALUE;
1510 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001511 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001512 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001513
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001514 switch (mStatus) {
1515 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001516 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001517 return INVALID_OPERATION;
1518 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001519 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001520 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001521 case STATUS_UNCONFIGURED:
1522 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523 case STATUS_ACTIVE:
1524 // OK
1525 break;
1526 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001527 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001528 return INVALID_OPERATION;
1529 }
1530
1531 ssize_t idx = mOutputStreams.indexOfKey(id);
1532 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001533 CLOGE("Stream %d is unknown", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 return idx;
1535 }
1536
Emilian Peev710c1422017-08-30 11:19:38 +01001537 streamInfo->width = mOutputStreams[idx]->getWidth();
1538 streamInfo->height = mOutputStreams[idx]->getHeight();
1539 streamInfo->format = mOutputStreams[idx]->getFormat();
1540 streamInfo->dataSpace = mOutputStreams[idx]->getDataSpace();
1541 streamInfo->formatOverridden = mOutputStreams[idx]->isFormatOverridden();
1542 streamInfo->originalFormat = mOutputStreams[idx]->getOriginalFormat();
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07001543 streamInfo->dataSpaceOverridden = mOutputStreams[idx]->isDataSpaceOverridden();
1544 streamInfo->originalDataSpace = mOutputStreams[idx]->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001546}
1547
1548status_t Camera3Device::setStreamTransform(int id,
1549 int transform) {
1550 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001551 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001553
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001554 switch (mStatus) {
1555 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001556 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001557 return INVALID_OPERATION;
1558 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001559 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001560 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001561 case STATUS_UNCONFIGURED:
1562 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001563 case STATUS_ACTIVE:
1564 // OK
1565 break;
1566 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001567 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001568 return INVALID_OPERATION;
1569 }
1570
1571 ssize_t idx = mOutputStreams.indexOfKey(id);
1572 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001573 CLOGE("Stream %d does not exist",
1574 id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001575 return BAD_VALUE;
1576 }
1577
1578 return mOutputStreams.editValueAt(idx)->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001579}
1580
1581status_t Camera3Device::deleteStream(int id) {
1582 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001583 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001584 Mutex::Autolock l(mLock);
1585 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001586
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001587 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001588
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001589 // CameraDevice semantics require device to already be idle before
1590 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001591 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001592 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001593 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001594 }
1595
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001596 if (mStatus == STATUS_ERROR) {
1597 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1598 __FUNCTION__, mId.string());
1599 return -EBUSY;
1600 }
1601
Igor Murashkin2fba5842013-04-22 14:03:54 -07001602 sp<Camera3StreamInterface> deletedStream;
Zhijun He5f446352014-01-22 09:49:33 -08001603 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001604 if (mInputStream != NULL && id == mInputStream->getId()) {
1605 deletedStream = mInputStream;
1606 mInputStream.clear();
1607 } else {
Zhijun He5f446352014-01-22 09:49:33 -08001608 if (outputStreamIdx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001609 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001610 return BAD_VALUE;
1611 }
Zhijun He5f446352014-01-22 09:49:33 -08001612 }
1613
1614 // Delete output stream or the output part of a bi-directional stream.
1615 if (outputStreamIdx != NAME_NOT_FOUND) {
1616 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001617 mOutputStreams.removeItem(id);
1618 }
1619
1620 // Free up the stream endpoint so that it can be used by some other stream
1621 res = deletedStream->disconnect();
1622 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001623 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001624 // fall through since we want to still list the stream as deleted.
1625 }
1626 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001627 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001628
1629 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001630}
1631
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001632status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001633 ATRACE_CALL();
1634 ALOGV("%s: E", __FUNCTION__);
1635
1636 Mutex::Autolock il(mInterfaceLock);
1637 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001638
Emilian Peev811d2952018-05-25 11:08:40 +01001639 // In case the client doesn't include any session parameter, try a
1640 // speculative configuration using the values from the last cached
1641 // default request.
1642 if (sessionParams.isEmpty() &&
1643 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1644 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1645 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1646 mLastTemplateId);
1647 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1648 operatingMode);
1649 }
1650
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001651 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
1652}
1653
1654status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
1655 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001656 //Filter out any incoming session parameters
1657 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001658 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
1659 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001660 CameraMetadata filteredParams(availableSessionKeys.count);
1661 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
1662 filteredParams.getAndLock());
1663 set_camera_metadata_vendor_id(meta, mVendorTagId);
1664 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001665 if (availableSessionKeys.count > 0) {
1666 for (size_t i = 0; i < availableSessionKeys.count; i++) {
1667 camera_metadata_ro_entry entry = params.find(
1668 availableSessionKeys.data.i32[i]);
1669 if (entry.count > 0) {
1670 filteredParams.update(entry);
1671 }
1672 }
1673 }
1674
1675 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07001676}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001677
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001678status_t Camera3Device::getInputBufferProducer(
1679 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001680 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07001681 Mutex::Autolock il(mInterfaceLock);
1682 Mutex::Autolock l(mLock);
1683
1684 if (producer == NULL) {
1685 return BAD_VALUE;
1686 } else if (mInputStream == NULL) {
1687 return INVALID_OPERATION;
1688 }
1689
1690 return mInputStream->getInputBufferProducer(producer);
1691}
1692
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001693status_t Camera3Device::createDefaultRequest(int templateId,
1694 CameraMetadata *request) {
1695 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07001696 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08001697
1698 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
1699 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
1700 IPCThreadState::self()->getCallingUid(), nullptr, 0);
1701 return BAD_VALUE;
1702 }
1703
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001704 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001705
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001706 {
1707 Mutex::Autolock l(mLock);
1708 switch (mStatus) {
1709 case STATUS_ERROR:
1710 CLOGE("Device has encountered a serious error");
1711 return INVALID_OPERATION;
1712 case STATUS_UNINITIALIZED:
1713 CLOGE("Device is not initialized!");
1714 return INVALID_OPERATION;
1715 case STATUS_UNCONFIGURED:
1716 case STATUS_CONFIGURED:
1717 case STATUS_ACTIVE:
1718 // OK
1719 break;
1720 default:
1721 SET_ERR_L("Unexpected status: %d", mStatus);
1722 return INVALID_OPERATION;
1723 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001724
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001725 if (!mRequestTemplateCache[templateId].isEmpty()) {
1726 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001727 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001728 return OK;
1729 }
Zhijun Hea1530f12014-09-14 12:44:20 -07001730 }
1731
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001732 camera_metadata_t *rawRequest;
1733 status_t res = mInterface->constructDefaultRequestSettings(
1734 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001735
1736 {
1737 Mutex::Autolock l(mLock);
1738 if (res == BAD_VALUE) {
1739 ALOGI("%s: template %d is not supported on this camera device",
1740 __FUNCTION__, templateId);
1741 return res;
1742 } else if (res != OK) {
1743 CLOGE("Unable to construct request template %d: %s (%d)",
1744 templateId, strerror(-res), res);
1745 return res;
1746 }
1747
1748 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
1749 mRequestTemplateCache[templateId].acquire(rawRequest);
1750
1751 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01001752 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001753 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001754 return OK;
1755}
1756
1757status_t Camera3Device::waitUntilDrained() {
1758 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001759 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001760 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001761 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001762
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001763 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07001764}
1765
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001766status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001767 switch (mStatus) {
1768 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001769 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001770 ALOGV("%s: Already idle", __FUNCTION__);
1771 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001772 case STATUS_CONFIGURED:
1773 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001774 case STATUS_ERROR:
1775 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001776 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001777 break;
1778 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001779 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001780 return INVALID_OPERATION;
1781 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001782 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
1783 maxExpectedDuration);
1784 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07001785 if (res != OK) {
1786 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
1787 res);
1788 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001789 return res;
1790}
1791
Ruben Brunk183f0562015-08-12 12:55:02 -07001792
1793void Camera3Device::internalUpdateStatusLocked(Status status) {
1794 mStatus = status;
1795 mRecentStatusUpdates.add(mStatus);
1796 mStatusChanged.broadcast();
1797}
1798
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001799void Camera3Device::pauseStateNotify(bool enable) {
1800 Mutex::Autolock il(mInterfaceLock);
1801 Mutex::Autolock l(mLock);
1802
1803 mPauseStateNotify = enable;
1804}
1805
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001806// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001807status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001808 mRequestThread->setPaused(true);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001809
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001810 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1811 maxExpectedDuration);
1812 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001813 if (res != OK) {
1814 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07001815 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001816 }
1817
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001818 return res;
1819}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001820
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001821// Resume after internalPauseAndWaitLocked
1822status_t Camera3Device::internalResumeLocked() {
1823 status_t res;
1824
1825 mRequestThread->setPaused(false);
1826
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08001827 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
1828 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001829 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
1830 if (res != OK) {
1831 SET_ERR_L("Can't transition to active in %f seconds!",
1832 kActiveTimeout/1e9);
1833 }
1834 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001835 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001836}
1837
Ruben Brunk183f0562015-08-12 12:55:02 -07001838status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001839 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07001840
1841 size_t startIndex = 0;
1842 if (mStatusWaiters == 0) {
1843 // Clear the list of recent statuses if there are no existing threads waiting on updates to
1844 // this status list
1845 mRecentStatusUpdates.clear();
1846 } else {
1847 // If other threads are waiting on updates to this status list, set the position of the
1848 // first element that this list will check rather than clearing the list.
1849 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001850 }
1851
Ruben Brunk183f0562015-08-12 12:55:02 -07001852 mStatusWaiters++;
1853
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001854 bool stateSeen = false;
1855 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07001856 if (active == (mStatus == STATUS_ACTIVE)) {
1857 // Desired state is current
1858 break;
1859 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001860
1861 res = mStatusChanged.waitRelative(mLock, timeout);
1862 if (res != OK) break;
1863
Ruben Brunk183f0562015-08-12 12:55:02 -07001864 // This is impossible, but if not, could result in subtle deadlocks and invalid state
1865 // transitions.
1866 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
1867 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
1868 __FUNCTION__);
1869
1870 // Encountered desired state since we began waiting
1871 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001872 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
1873 stateSeen = true;
1874 break;
1875 }
1876 }
1877 } while (!stateSeen);
1878
Ruben Brunk183f0562015-08-12 12:55:02 -07001879 mStatusWaiters--;
1880
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001881 return res;
1882}
1883
1884
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07001885status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001886 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001887 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001888
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001889 if (listener != NULL && mListener != NULL) {
1890 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
1891 }
1892 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07001893 mRequestThread->setNotificationListener(listener);
1894 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001895
1896 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001897}
1898
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07001899bool Camera3Device::willNotify3A() {
1900 return false;
1901}
1902
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001903status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07001904 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001905 status_t res;
1906 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001907
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001908 while (mResultQueue.empty()) {
1909 res = mResultSignal.waitRelative(mOutputLock, timeout);
1910 if (res == TIMED_OUT) {
1911 return res;
1912 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001913 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
1914 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001915 return res;
1916 }
1917 }
1918 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001919}
1920
Jianing Weicb0652e2014-03-12 18:29:36 -07001921status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001922 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001923 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001924
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001925 if (mResultQueue.empty()) {
1926 return NOT_ENOUGH_DATA;
1927 }
1928
Jianing Weicb0652e2014-03-12 18:29:36 -07001929 if (frame == NULL) {
1930 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
1931 return BAD_VALUE;
1932 }
1933
1934 CaptureResult &result = *(mResultQueue.begin());
1935 frame->mResultExtras = result.mResultExtras;
1936 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001937 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07001938 mResultQueue.erase(mResultQueue.begin());
1939
1940 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001941}
1942
1943status_t Camera3Device::triggerAutofocus(uint32_t id) {
1944 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001945 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001946
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001947 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
1948 // Mix-in this trigger into the next request and only the next request.
1949 RequestTrigger trigger[] = {
1950 {
1951 ANDROID_CONTROL_AF_TRIGGER,
1952 ANDROID_CONTROL_AF_TRIGGER_START
1953 },
1954 {
1955 ANDROID_CONTROL_AF_TRIGGER_ID,
1956 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001957 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001958 };
1959
1960 return mRequestThread->queueTrigger(trigger,
1961 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001962}
1963
1964status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
1965 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001966 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001967
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001968 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
1969 // Mix-in this trigger into the next request and only the next request.
1970 RequestTrigger trigger[] = {
1971 {
1972 ANDROID_CONTROL_AF_TRIGGER,
1973 ANDROID_CONTROL_AF_TRIGGER_CANCEL
1974 },
1975 {
1976 ANDROID_CONTROL_AF_TRIGGER_ID,
1977 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001978 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001979 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001980
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001981 return mRequestThread->queueTrigger(trigger,
1982 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001983}
1984
1985status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
1986 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001987 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001988
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001989 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
1990 // Mix-in this trigger into the next request and only the next request.
1991 RequestTrigger trigger[] = {
1992 {
1993 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
1994 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
1995 },
1996 {
1997 ANDROID_CONTROL_AE_PRECAPTURE_ID,
1998 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07001999 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002000 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002001
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002002 return mRequestThread->queueTrigger(trigger,
2003 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002004}
2005
Jianing Weicb0652e2014-03-12 18:29:36 -07002006status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002007 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002008 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002009 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002010
Zhijun He7ef20392014-04-21 16:04:17 -07002011 {
2012 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002013 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002014 }
2015
Emilian Peev08dd2452017-04-06 16:55:14 +01002016 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002017}
2018
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002019status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002020 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2021}
2022
2023status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002024 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002025 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002026 Mutex::Autolock il(mInterfaceLock);
2027 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002028
2029 sp<Camera3StreamInterface> stream;
2030 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2031 if (outputStreamIdx == NAME_NOT_FOUND) {
2032 CLOGE("Stream %d does not exist", streamId);
2033 return BAD_VALUE;
2034 }
2035
2036 stream = mOutputStreams.editValueAt(outputStreamIdx);
2037
2038 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002039 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002040 return BAD_VALUE;
2041 }
2042
2043 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002044 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002045 return BAD_VALUE;
2046 }
2047
Ruben Brunkc78ac262015-08-13 17:58:46 -07002048 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002049}
2050
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002051status_t Camera3Device::tearDown(int streamId) {
2052 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002053 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002054 Mutex::Autolock il(mInterfaceLock);
2055 Mutex::Autolock l(mLock);
2056
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002057 sp<Camera3StreamInterface> stream;
2058 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2059 if (outputStreamIdx == NAME_NOT_FOUND) {
2060 CLOGE("Stream %d does not exist", streamId);
2061 return BAD_VALUE;
2062 }
2063
2064 stream = mOutputStreams.editValueAt(outputStreamIdx);
2065
2066 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2067 CLOGE("Stream %d is a target of a in-progress request", streamId);
2068 return BAD_VALUE;
2069 }
2070
2071 return stream->tearDown();
2072}
2073
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002074status_t Camera3Device::addBufferListenerForStream(int streamId,
2075 wp<Camera3StreamBufferListener> listener) {
2076 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002077 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002078 Mutex::Autolock il(mInterfaceLock);
2079 Mutex::Autolock l(mLock);
2080
2081 sp<Camera3StreamInterface> stream;
2082 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(streamId);
2083 if (outputStreamIdx == NAME_NOT_FOUND) {
2084 CLOGE("Stream %d does not exist", streamId);
2085 return BAD_VALUE;
2086 }
2087
2088 stream = mOutputStreams.editValueAt(outputStreamIdx);
2089 stream->addBufferListener(listener);
2090
2091 return OK;
2092}
2093
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002094/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002095 * Methods called by subclasses
2096 */
2097
2098void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002099 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002100 {
2101 // Need mLock to safely update state and synchronize to current
2102 // state of methods in flight.
2103 Mutex::Autolock l(mLock);
2104 // We can get various system-idle notices from the status tracker
2105 // while starting up. Only care about them if we've actually sent
2106 // in some requests recently.
2107 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2108 return;
2109 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002110 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2111 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002112 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002113
2114 // Skip notifying listener if we're doing some user-transparent
2115 // state changes
2116 if (mPauseStateNotify) return;
2117 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002118
2119 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002120 {
2121 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002122 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002123 }
2124 if (idle && listener != NULL) {
2125 listener->notifyIdle();
2126 }
2127}
2128
Shuzhen Wang758c2152017-01-10 18:26:18 -08002129status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002130 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002131 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002132 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2133 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002134
2135 if (surfaceIds == nullptr) {
2136 return BAD_VALUE;
2137 }
2138
Zhijun He5d677d12016-05-29 16:52:39 -07002139 Mutex::Autolock il(mInterfaceLock);
2140 Mutex::Autolock l(mLock);
2141
Shuzhen Wang758c2152017-01-10 18:26:18 -08002142 if (consumers.size() == 0) {
2143 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002144 return BAD_VALUE;
2145 }
2146
2147 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2148 if (idx == NAME_NOT_FOUND) {
2149 CLOGE("Stream %d is unknown", streamId);
2150 return idx;
2151 }
2152 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
Shuzhen Wang758c2152017-01-10 18:26:18 -08002153 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002154 if (res != OK) {
2155 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2156 return res;
2157 }
2158
Emilian Peev40ead602017-09-26 15:46:36 +01002159 for (auto &consumer : consumers) {
2160 int id = stream->getSurfaceId(consumer);
2161 if (id < 0) {
2162 CLOGE("Invalid surface id!");
2163 return BAD_VALUE;
2164 }
2165 surfaceIds->push_back(id);
2166 }
2167
Shuzhen Wang0129d522016-10-30 22:43:41 -07002168 if (stream->isConsumerConfigurationDeferred()) {
2169 if (!stream->isConfiguring()) {
2170 CLOGE("Stream %d was already fully configured.", streamId);
2171 return INVALID_OPERATION;
2172 }
Zhijun He5d677d12016-05-29 16:52:39 -07002173
Shuzhen Wang0129d522016-10-30 22:43:41 -07002174 res = stream->finishConfiguration();
2175 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002176 // If finishConfiguration fails due to abandoned surface, do not set
2177 // device to error state.
2178 bool isSurfaceAbandoned =
2179 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2180 if (!isSurfaceAbandoned) {
2181 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2182 stream->getId(), strerror(-res), res);
2183 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002184 return res;
2185 }
Zhijun He5d677d12016-05-29 16:52:39 -07002186 }
2187
2188 return OK;
2189}
2190
Emilian Peev40ead602017-09-26 15:46:36 +01002191status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2192 const std::vector<OutputStreamInfo> &outputInfo,
2193 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2194 Mutex::Autolock il(mInterfaceLock);
2195 Mutex::Autolock l(mLock);
2196
2197 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2198 if (idx == NAME_NOT_FOUND) {
2199 CLOGE("Stream %d is unknown", streamId);
2200 return idx;
2201 }
2202
2203 for (const auto &it : removedSurfaceIds) {
2204 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2205 CLOGE("Shared surface still part of a pending request!");
2206 return -EBUSY;
2207 }
2208 }
2209
2210 sp<Camera3OutputStreamInterface> stream = mOutputStreams[idx];
2211 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2212 if (res != OK) {
2213 CLOGE("Stream %d failed to update stream (error %d %s) ",
2214 streamId, res, strerror(-res));
2215 if (res == UNKNOWN_ERROR) {
2216 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2217 __FUNCTION__);
2218 }
2219 return res;
2220 }
2221
2222 return res;
2223}
2224
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002225status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2226 Mutex::Autolock il(mInterfaceLock);
2227 Mutex::Autolock l(mLock);
2228
2229 int idx = mOutputStreams.indexOfKey(streamId);
2230 if (idx == NAME_NOT_FOUND) {
2231 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2232 return BAD_VALUE;
2233 }
2234
2235 sp<Camera3OutputStreamInterface> stream = mOutputStreams.editValueAt(idx);
2236 return stream->dropBuffers(dropping);
2237}
2238
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002239/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002240 * Camera3Device private methods
2241 */
2242
2243sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002244 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002245 ATRACE_CALL();
2246 status_t res;
2247
2248 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002249 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002250
2251 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002252 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002253 if (inputStreams.count > 0) {
2254 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002255 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002256 CLOGE("Request references unknown input stream %d",
2257 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002258 return NULL;
2259 }
2260 // Lazy completion of stream configuration (allocation/registration)
2261 // on first use
2262 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002263 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002264 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002265 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002266 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002267 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002268 return NULL;
2269 }
2270 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002271 // Check if stream is being prepared
2272 if (mInputStream->isPreparing()) {
2273 CLOGE("Request references an input stream that's being prepared!");
2274 return NULL;
2275 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002276
2277 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002278 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002279 }
2280
2281 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002282 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002283 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002284 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002285 return NULL;
2286 }
2287
2288 for (size_t i = 0; i < streams.count; i++) {
Zhijun Hed1d64672013-09-06 15:00:01 -07002289 int idx = mOutputStreams.indexOfKey(streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002290 if (idx == NAME_NOT_FOUND) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002291 CLOGE("Request references unknown stream %d",
2292 streams.data.u8[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002293 return NULL;
2294 }
Igor Murashkin2fba5842013-04-22 14:03:54 -07002295 sp<Camera3OutputStreamInterface> stream =
2296 mOutputStreams.editValueAt(idx);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002297
Zhijun He5d677d12016-05-29 16:52:39 -07002298 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002299 auto iter = surfaceMap.find(streams.data.i32[i]);
2300 if (iter != surfaceMap.end()) {
2301 const std::vector<size_t>& surfaces = iter->second;
2302 for (const auto& surface : surfaces) {
2303 if (stream->isConsumerConfigurationDeferred(surface)) {
2304 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2305 "due to deferred consumer", stream->getId(), surface);
2306 return NULL;
2307 }
2308 }
2309 newRequest->mOutputSurfaces[i] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002310 }
2311
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002312 // Lazy completion of stream configuration (allocation/registration)
2313 // on first use
2314 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002315 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002316 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002317 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2318 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002319 return NULL;
2320 }
2321 }
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002322 // Check if stream is being prepared
2323 if (stream->isPreparing()) {
2324 CLOGE("Request references an output stream that's being prepared!");
2325 return NULL;
2326 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002327
2328 newRequest->mOutputStreams.push(stream);
2329 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002330 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002331 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002332
2333 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002334}
2335
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002336bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2337 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2338 Size size = mSupportedOpaqueInputSizes[i];
2339 if (size.width == width && size.height == height) {
2340 return true;
2341 }
2342 }
2343
2344 return false;
2345}
2346
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002347void Camera3Device::cancelStreamsConfigurationLocked() {
2348 int res = OK;
2349 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2350 res = mInputStream->cancelConfiguration();
2351 if (res != OK) {
2352 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2353 mInputStream->getId(), strerror(-res), res);
2354 }
2355 }
2356
2357 for (size_t i = 0; i < mOutputStreams.size(); i++) {
2358 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.editValueAt(i);
2359 if (outputStream->isConfiguring()) {
2360 res = outputStream->cancelConfiguration();
2361 if (res != OK) {
2362 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2363 outputStream->getId(), strerror(-res), res);
2364 }
2365 }
2366 }
2367
2368 // Return state to that at start of call, so that future configures
2369 // properly clean things up
2370 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2371 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002372
2373 res = mPreparerThread->resume();
2374 if (res != OK) {
2375 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2376 }
2377}
2378
2379bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2380 ATRACE_CALL();
2381 bool ret = false;
2382
2383 Mutex::Autolock il(mInterfaceLock);
2384 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2385
2386 Mutex::Autolock l(mLock);
2387 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2388 if (rc == NO_ERROR) {
2389 mNeedConfig = true;
2390 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2391 if (rc == NO_ERROR) {
2392 ret = true;
2393 mPauseStateNotify = false;
2394 //Moving to active state while holding 'mLock' is important.
2395 //There could be pending calls to 'create-/deleteStream' which
2396 //will trigger another stream configuration while the already
2397 //present streams end up with outstanding buffers that will
2398 //not get drained.
2399 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002400 } else if (rc == DEAD_OBJECT) {
2401 // DEAD_OBJECT can be returned if either the consumer surface is
2402 // abandoned, or the HAL has died.
2403 // - If the HAL has died, configureStreamsLocked call will set
2404 // device to error state,
2405 // - If surface is abandoned, we should not set device to error
2406 // state.
2407 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002408 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002409 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002410 }
2411 } else {
2412 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2413 }
2414
2415 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002416}
2417
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002418status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002419 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002420 ATRACE_CALL();
2421 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002422
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002423 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002424 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002425 return INVALID_OPERATION;
2426 }
2427
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002428 if (operatingMode < 0) {
2429 CLOGE("Invalid operating mode: %d", operatingMode);
2430 return BAD_VALUE;
2431 }
2432
2433 bool isConstrainedHighSpeed =
2434 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2435 operatingMode;
2436
2437 if (mOperatingMode != operatingMode) {
2438 mNeedConfig = true;
2439 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2440 mOperatingMode = operatingMode;
2441 }
2442
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002443 if (!mNeedConfig) {
2444 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2445 return OK;
2446 }
2447
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002448 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2449 // adding a dummy stream instead.
2450 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2451 if (mOutputStreams.size() == 0) {
2452 addDummyStreamLocked();
2453 } else {
2454 tryRemoveDummyStreamLocked();
2455 }
2456
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002457 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002458 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002459
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002460 mPreparerThread->pause();
2461
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002462 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002463 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002464 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2465
2466 Vector<camera3_stream_t*> streams;
2467 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002468 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002469
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002470
2471 if (mInputStream != NULL) {
2472 camera3_stream_t *inputStream;
2473 inputStream = mInputStream->startConfiguration();
2474 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002475 CLOGE("Can't start input stream configuration");
2476 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002477 return INVALID_OPERATION;
2478 }
2479 streams.add(inputStream);
2480 }
2481
2482 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002483
2484 // Don't configure bidi streams twice, nor add them twice to the list
2485 if (mOutputStreams[i].get() ==
2486 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2487
2488 config.num_streams--;
2489 continue;
2490 }
2491
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002492 camera3_stream_t *outputStream;
2493 outputStream = mOutputStreams.editValueAt(i)->startConfiguration();
2494 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002495 CLOGE("Can't start output stream configuration");
2496 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002497 return INVALID_OPERATION;
2498 }
2499 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002500
2501 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB &&
2502 outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
Emilian Peev192ee832018-01-31 14:46:47 +00002503 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2504 // always occupy the initial entry.
2505 bufferSizes[k] = static_cast<uint32_t>(
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002506 getJpegBufferSize(outputStream->width, outputStream->height));
2507 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002508 }
2509
2510 config.streams = streams.editArray();
2511
2512 // Do the HAL configuration; will potentially touch stream
2513 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002514
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002515 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002516 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002517 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002518
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002519 if (res == BAD_VALUE) {
2520 // HAL rejected this set of streams as unsupported, clean up config
2521 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002522 CLOGE("Set of requested inputs/outputs not supported by HAL");
2523 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002524 return BAD_VALUE;
2525 } else if (res != OK) {
2526 // Some other kind of error from configure_streams - this is not
2527 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002528 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2529 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002530 return res;
2531 }
2532
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002533 // Finish all stream configuration immediately.
2534 // TODO: Try to relax this later back to lazy completion, which should be
2535 // faster
2536
Igor Murashkin073f8572013-05-02 14:59:28 -07002537 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002538 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002539 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002540 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002541 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002542 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002543 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2544 return DEAD_OBJECT;
2545 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002546 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002547 }
2548 }
2549
2550 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin073f8572013-05-02 14:59:28 -07002551 sp<Camera3OutputStreamInterface> outputStream =
2552 mOutputStreams.editValueAt(i);
Zhijun He5d677d12016-05-29 16:52:39 -07002553 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002554 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002555 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002556 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002557 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002558 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002559 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2560 return DEAD_OBJECT;
2561 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002562 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002563 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002564 }
2565 }
2566
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002567 // Request thread needs to know to avoid using repeat-last-settings protocol
2568 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002569 if (notifyRequestThread) {
2570 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2571 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002572
Zhijun He90f7c372016-08-16 16:19:43 -07002573 char value[PROPERTY_VALUE_MAX];
2574 property_get("camera.fifo.disable", value, "0");
2575 int32_t disableFifo = atoi(value);
2576 if (disableFifo != 1) {
2577 // Boost priority of request thread to SCHED_FIFO.
2578 pid_t requestThreadTid = mRequestThread->getTid();
2579 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002580 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002581 if (res != OK) {
2582 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2583 strerror(-res), res);
2584 } else {
2585 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2586 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002587 }
2588
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002589 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002590 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2591 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2592 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2593 sessionParams.unlock(newSessionParams);
2594 mSessionParams.unlock(currentSessionParams);
2595 if (updateSessionParams) {
2596 mSessionParams = sessionParams;
2597 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002598
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002599 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002600
Ruben Brunk183f0562015-08-12 12:55:02 -07002601 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2602 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002603
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002604 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002605
Zhijun He0a210512014-07-24 13:45:15 -07002606 // tear down the deleted streams after configure streams.
2607 mDeletedStreams.clear();
2608
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002609 auto rc = mPreparerThread->resume();
2610 if (rc != OK) {
2611 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2612 return rc;
2613 }
2614
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002615 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002616}
2617
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002618status_t Camera3Device::addDummyStreamLocked() {
2619 ATRACE_CALL();
2620 status_t res;
2621
2622 if (mDummyStreamId != NO_STREAM) {
2623 // Should never be adding a second dummy stream when one is already
2624 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002625 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2626 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002627 return INVALID_OPERATION;
2628 }
2629
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002630 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002631
2632 sp<Camera3OutputStreamInterface> dummyStream =
2633 new Camera3DummyStream(mNextStreamId);
2634
2635 res = mOutputStreams.add(mNextStreamId, dummyStream);
2636 if (res < 0) {
2637 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2638 return res;
2639 }
2640
2641 mDummyStreamId = mNextStreamId;
2642 mNextStreamId++;
2643
2644 return OK;
2645}
2646
2647status_t Camera3Device::tryRemoveDummyStreamLocked() {
2648 ATRACE_CALL();
2649 status_t res;
2650
2651 if (mDummyStreamId == NO_STREAM) return OK;
2652 if (mOutputStreams.size() == 1) return OK;
2653
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002654 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002655
2656 // Ok, have a dummy stream and there's at least one other output stream,
2657 // so remove the dummy
2658
2659 sp<Camera3StreamInterface> deletedStream;
2660 ssize_t outputStreamIdx = mOutputStreams.indexOfKey(mDummyStreamId);
2661 if (outputStreamIdx == NAME_NOT_FOUND) {
2662 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
2663 return INVALID_OPERATION;
2664 }
2665
2666 deletedStream = mOutputStreams.editValueAt(outputStreamIdx);
2667 mOutputStreams.removeItemsAt(outputStreamIdx);
2668
2669 // Free up the stream endpoint so that it can be used by some other stream
2670 res = deletedStream->disconnect();
2671 if (res != OK) {
2672 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
2673 // fall through since we want to still list the stream as deleted.
2674 }
2675 mDeletedStreams.add(deletedStream);
2676 mDummyStreamId = NO_STREAM;
2677
2678 return res;
2679}
2680
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002681void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002682 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002683 Mutex::Autolock l(mLock);
2684 va_list args;
2685 va_start(args, fmt);
2686
2687 setErrorStateLockedV(fmt, args);
2688
2689 va_end(args);
2690}
2691
2692void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
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 setErrorStateLockedV(fmt, args);
2696}
2697
2698void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
2699 va_list args;
2700 va_start(args, fmt);
2701
2702 setErrorStateLockedV(fmt, args);
2703
2704 va_end(args);
2705}
2706
2707void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002708 // Print out all error messages to log
2709 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002710 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002711
2712 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07002713 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002714
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002715 mErrorCause = errorCause;
2716
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07002717 if (mRequestThread != nullptr) {
2718 mRequestThread->setPaused(true);
2719 }
Ruben Brunk183f0562015-08-12 12:55:02 -07002720 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002721
2722 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002723 sp<NotificationListener> listener = mListener.promote();
2724 if (listener != NULL) {
2725 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002726 CaptureResultExtras());
2727 }
2728
2729 // Save stack trace. View by dumping it later.
2730 CameraTraces::saveTrace();
2731 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002732}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002733
2734/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002735 * In-flight request management
2736 */
2737
Jianing Weicb0652e2014-03-12 18:29:36 -07002738status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07002739 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002740 bool hasAppCallback, nsecs_t maxExpectedDuration,
Emilian Peev9dd21f42018-08-03 13:39:29 +01002741 std::set<String8>& physicalCameraIds, bool isStillCapture) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002742 ATRACE_CALL();
2743 Mutex::Autolock l(mInFlightLock);
2744
2745 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07002746 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Emilian Peev9dd21f42018-08-03 13:39:29 +01002747 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002748 if (res < 0) return res;
2749
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002750 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002751 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2752 // avoid a deadlock during reprocess requests.
2753 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002754 if (mStatusTracker != nullptr) {
2755 mStatusTracker->markComponentActive(mInFlightStatusId);
2756 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07002757 }
2758
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002759 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07002760 return OK;
2761}
2762
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002763void Camera3Device::returnOutputBuffers(
2764 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
2765 nsecs_t timestamp) {
2766 for (size_t i = 0; i < numBuffers; i++)
2767 {
2768 Camera3Stream *stream = Camera3Stream::cast(outputBuffers[i].stream);
2769 status_t res = stream->returnBuffer(outputBuffers[i], timestamp);
2770 // Note: stream may be deallocated at this point, if this buffer was
2771 // the last reference to it.
2772 if (res != OK) {
2773 ALOGE("Can't return buffer to its stream: %s (%d)",
2774 strerror(-res), res);
2775 }
2776 }
2777}
2778
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002779void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002780 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002781 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002782 mInFlightMap.removeItemsAt(idx, 1);
2783
2784 // Indicate idle inFlightMap to the status tracker
2785 if (mInFlightMap.size() == 0) {
Emilian Peev26d975d2018-07-05 14:52:57 +01002786 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
2787 // avoid a deadlock during reprocess requests.
2788 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07002789 if (mStatusTracker != nullptr) {
2790 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
2791 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002792 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002793 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002794}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002795
2796void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
2797
2798 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2799 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
2800
2801 nsecs_t sensorTimestamp = request.sensorTimestamp;
2802 nsecs_t shutterTimestamp = request.shutterTimestamp;
2803
2804 // Check if it's okay to remove the request from InFlightMap:
2805 // In the case of a successful request:
2806 // all input and output buffers, all result metadata, shutter callback
2807 // arrived.
2808 // In the case of a unsuccessful request:
2809 // all input and output buffers arrived.
2810 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07002811 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002812 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01002813 if (request.stillCapture) {
2814 ATRACE_ASYNC_END("still capture", frameNumber);
2815 }
2816
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002817 ATRACE_ASYNC_END("frame capture", frameNumber);
2818
Shuzhen Wang403044a2017-02-26 23:29:04 -08002819 // Sanity check - if sensor timestamp matches shutter timestamp in the
2820 // case of request having callback.
2821 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002822 sensorTimestamp != shutterTimestamp) {
2823 SET_ERR("sensor timestamp (%" PRId64
2824 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
2825 sensorTimestamp, frameNumber, shutterTimestamp);
2826 }
2827
2828 // for an unsuccessful request, it may have pending output buffers to
2829 // return.
2830 assert(request.requestStatus != OK ||
2831 request.pendingOutputBuffers.size() == 0);
2832 returnOutputBuffers(request.pendingOutputBuffers.array(),
2833 request.pendingOutputBuffers.size(), 0);
2834
Shuzhen Wangcadb3302016-11-04 14:17:56 -07002835 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002836 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
2837 }
2838
2839 // Sanity check - if we have too many in-flight frames, something has
2840 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002841 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002842 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07002843 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
2844 kInFlightWarnLimitHighSpeed) {
2845 CLOGE("In-flight list too large for high speed configuration: %zu",
2846 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002847 }
2848}
2849
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002850void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002851 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002852 { // First return buffers cached in mInFlightMap
2853 Mutex::Autolock l(mInFlightLock);
2854 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
2855 const InFlightRequest &request = mInFlightMap.valueAt(idx);
2856 returnOutputBuffers(request.pendingOutputBuffers.array(),
2857 request.pendingOutputBuffers.size(), 0);
2858 }
2859 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002860 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002861 }
2862
2863 // Then return all inflight buffers not returned by HAL
2864 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
2865 mInterface->getInflightBufferKeys(&inflightKeys);
2866
2867 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
2868 for (auto& pair : inflightKeys) {
2869 int32_t frameNumber = pair.first;
2870 int32_t streamId = pair.second;
2871 buffer_handle_t* buffer;
2872 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
2873 if (res != OK) {
2874 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
2875 __FUNCTION__, frameNumber, streamId);
2876 continue;
2877 }
2878
2879 camera3_stream_buffer_t streamBuffer;
2880 streamBuffer.buffer = buffer;
2881 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2882 streamBuffer.acquire_fence = -1;
2883 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002884
2885 // First check if the buffer belongs to deleted stream
2886 bool streamDeleted = false;
2887 for (auto& stream : mDeletedStreams) {
2888 if (streamId == stream->getId()) {
2889 streamDeleted = true;
2890 // Return buffer to deleted stream
2891 camera3_stream* halStream = stream->asHalStream();
2892 streamBuffer.stream = halStream;
2893 switch (halStream->stream_type) {
2894 case CAMERA3_STREAM_OUTPUT:
2895 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0);
2896 if (res != OK) {
2897 ALOGE("%s: Can't return output buffer for frame %d to"
2898 " stream %d: %s (%d)", __FUNCTION__,
2899 frameNumber, streamId, strerror(-res), res);
2900 }
2901 break;
2902 case CAMERA3_STREAM_INPUT:
2903 res = stream->returnInputBuffer(streamBuffer);
2904 if (res != OK) {
2905 ALOGE("%s: Can't return input buffer for frame %d to"
2906 " stream %d: %s (%d)", __FUNCTION__,
2907 frameNumber, streamId, strerror(-res), res);
2908 }
2909 break;
2910 default: // Bi-direcitonal stream is deprecated
2911 ALOGE("%s: stream %d has unknown stream type %d",
2912 __FUNCTION__, streamId, halStream->stream_type);
2913 break;
2914 }
2915 break;
2916 }
2917 }
2918 if (streamDeleted) {
2919 continue;
2920 }
2921
2922 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002923 if (streamId == inputStreamId) {
2924 streamBuffer.stream = mInputStream->asHalStream();
2925 res = mInputStream->returnInputBuffer(streamBuffer);
2926 if (res != OK) {
2927 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002928 " stream %d: %s (%d)", __FUNCTION__,
2929 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002930 }
2931 } else {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07002932 ssize_t idx = mOutputStreams.indexOfKey(streamId);
2933 if (idx == NAME_NOT_FOUND) {
2934 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
2935 continue;
2936 }
2937 streamBuffer.stream = mOutputStreams.valueAt(idx)->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07002938 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
2939 }
2940 }
2941}
2942
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002943void Camera3Device::insertResultLocked(CaptureResult *result,
2944 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002945 if (result == nullptr) return;
2946
Emilian Peev71c73a22017-03-21 16:35:51 +00002947 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2948 result->mMetadata.getAndLock());
2949 set_camera_metadata_vendor_id(meta, mVendorTagId);
2950 result->mMetadata.unlock(meta);
2951
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002952 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
2953 (int32_t*)&frameNumber, 1) != OK) {
2954 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
2955 return;
2956 }
2957
2958 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
2959 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
2960 return;
2961 }
2962
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002963 // Valid result, insert into queue
2964 List<CaptureResult>::iterator queuedResult =
2965 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
2966 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
2967 ", burstId = %" PRId32, __FUNCTION__,
2968 queuedResult->mResultExtras.requestId,
2969 queuedResult->mResultExtras.frameNumber,
2970 queuedResult->mResultExtras.burstId);
2971
2972 mResultSignal.signal();
2973}
2974
2975
2976void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002977 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002978 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002979 Mutex::Autolock l(mOutputLock);
2980
2981 CaptureResult captureResult;
2982 captureResult.mResultExtras = resultExtras;
2983 captureResult.mMetadata = partialResult;
2984
Emilian Peev7e25e5e2017-04-07 15:48:49 +01002985 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08002986}
2987
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002988
2989void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
2990 CaptureResultExtras &resultExtras,
2991 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002992 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002993 bool reprocess,
2994 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002995 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08002996 if (pendingMetadata.isEmpty())
2997 return;
2998
2999 Mutex::Autolock l(mOutputLock);
3000
3001 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003002 if (reprocess) {
3003 if (frameNumber < mNextReprocessResultFrameNumber) {
3004 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003005 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003006 frameNumber, mNextReprocessResultFrameNumber);
3007 return;
3008 }
3009 mNextReprocessResultFrameNumber = frameNumber + 1;
3010 } else {
3011 if (frameNumber < mNextResultFrameNumber) {
3012 SET_ERR("Out-of-order capture result metadata submitted! "
3013 "(got frame number %d, expecting %d)",
3014 frameNumber, mNextResultFrameNumber);
3015 return;
3016 }
3017 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003018 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003019
3020 CaptureResult captureResult;
3021 captureResult.mResultExtras = resultExtras;
3022 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003023 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003024
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003025 // Append any previous partials to form a complete result
3026 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3027 captureResult.mMetadata.append(collectedPartialResult);
3028 }
3029
3030 captureResult.mMetadata.sort();
3031
3032 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003033 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3034 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003035 SET_ERR("No timestamp provided by HAL for frame %d!",
3036 frameNumber);
3037 return;
3038 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003039 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3040 camera_metadata_entry timestamp =
3041 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3042 if (timestamp.count == 0) {
3043 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3044 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3045 return;
3046 }
3047 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003048
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003049 // Fix up some result metadata to account for HAL-level distortion correction
3050 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3051 if (res != OK) {
3052 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3053 frameNumber, strerror(res), res);
3054 return;
3055 }
3056
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003057 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3058 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3059
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003060 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003061}
3062
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003063/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003064 * Camera HAL device callback methods
3065 */
3066
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003067void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003068 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003069
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003070 status_t res;
3071
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003072 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003073 if (result->result == NULL && result->num_output_buffers == 0 &&
3074 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003075 SET_ERR("No result data provided by HAL for frame %d",
3076 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003077 return;
3078 }
Zhijun He204e3292014-07-14 17:09:23 -07003079
Zhijun He204e3292014-07-14 17:09:23 -07003080 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003081 result->result != NULL &&
3082 result->partial_result != 1) {
3083 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3084 " if partial result is not supported",
3085 frameNumber, result->partial_result);
3086 return;
3087 }
3088
3089 bool isPartialResult = false;
3090 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003091 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003092
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003093 // Get shutter timestamp and resultExtras from list of in-flight requests,
3094 // where it was added by the shutter notification for this frame. If the
3095 // shutter timestamp isn't received yet, append the output buffers to the
3096 // in-flight request and they will be returned when the shutter timestamp
3097 // arrives. Update the in-flight status and remove the in-flight entry if
3098 // all result data and shutter timestamp have been received.
3099 nsecs_t shutterTimestamp = 0;
3100
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003101 {
3102 Mutex::Autolock l(mInFlightLock);
3103 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3104 if (idx == NAME_NOT_FOUND) {
3105 SET_ERR("Unknown frame number for capture result: %d",
3106 frameNumber);
3107 return;
3108 }
3109 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003110 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3111 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003112 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003113 __FUNCTION__, request.resultExtras.requestId,
3114 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003115 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003116 // Always update the partial count to the latest one if it's not 0
3117 // (buffers only). When framework aggregates adjacent partial results
3118 // into one, the latest partial count will be used.
3119 if (result->partial_result != 0)
3120 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003121
3122 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003123 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003124 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3125 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3126 " the range of [1, %d] when metadata is included in the result",
3127 frameNumber, result->partial_result, mNumPartialResults);
3128 return;
3129 }
3130 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003131 if (isPartialResult && result->num_physcam_metadata) {
3132 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3133 " physical camera result", frameNumber);
3134 return;
3135 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003136 if (isPartialResult) {
3137 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003138 }
3139
Shuzhen Wang4a472662017-02-26 23:29:04 -08003140 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003141 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003142 sendPartialCaptureResult(result->result, request.resultExtras,
3143 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003144 }
3145 }
3146
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003147 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003148 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003149
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003150 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003151 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003152 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3153 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3154 request.physicalCameraIds.size(), result->num_physcam_metadata);
3155 return;
3156 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003157 if (request.haveResultMetadata) {
3158 SET_ERR("Called multiple times with metadata for frame %d",
3159 frameNumber);
3160 return;
3161 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003162 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3163 String8 physicalId(result->physcam_ids[i]);
3164 std::set<String8>::iterator cameraIdIter =
3165 request.physicalCameraIds.find(physicalId);
3166 if (cameraIdIter != request.physicalCameraIds.end()) {
3167 request.physicalCameraIds.erase(cameraIdIter);
3168 } else {
3169 SET_ERR("Total result for frame %d has already returned for camera %s",
3170 frameNumber, physicalId.c_str());
3171 return;
3172 }
3173 }
Zhijun He204e3292014-07-14 17:09:23 -07003174 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003175 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003176 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003177 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003178 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003179 request.haveResultMetadata = true;
3180 }
3181
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003182 uint32_t numBuffersReturned = result->num_output_buffers;
3183 if (result->input_buffer != NULL) {
3184 if (hasInputBufferInRequest) {
3185 numBuffersReturned += 1;
3186 } else {
3187 ALOGW("%s: Input buffer should be NULL if there is no input"
3188 " buffer sent in the request",
3189 __FUNCTION__);
3190 }
3191 }
3192 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003193 if (request.numBuffersLeft < 0) {
3194 SET_ERR("Too many buffers returned for frame %d",
3195 frameNumber);
3196 return;
3197 }
3198
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003199 camera_metadata_ro_entry_t entry;
3200 res = find_camera_metadata_ro_entry(result->result,
3201 ANDROID_SENSOR_TIMESTAMP, &entry);
3202 if (res == OK && entry.count == 1) {
3203 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003204 }
3205
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003206 // If shutter event isn't received yet, append the output buffers to
3207 // the in-flight request. Otherwise, return the output buffers to
3208 // streams.
3209 if (shutterTimestamp == 0) {
3210 request.pendingOutputBuffers.appendArray(result->output_buffers,
3211 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003212 } else {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003213 returnOutputBuffers(result->output_buffers,
3214 result->num_output_buffers, shutterTimestamp);
Igor Murashkind2c90692013-04-02 12:32:32 -07003215 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003216
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003217 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003218 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3219 CameraMetadata physicalMetadata;
3220 physicalMetadata.append(result->physcam_metadata[i]);
3221 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3222 physicalMetadata});
3223 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003224 if (shutterTimestamp == 0) {
3225 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003226 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003227 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003228 CameraMetadata metadata;
3229 metadata = result->result;
3230 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003231 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003232 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003233 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003234 }
3235
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003236 removeInFlightRequestIfReadyLocked(idx);
3237 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003238
Zhijun Hef0d962a2014-06-30 10:24:11 -07003239 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003240 if (hasInputBufferInRequest) {
3241 Camera3Stream *stream =
3242 Camera3Stream::cast(result->input_buffer->stream);
3243 res = stream->returnInputBuffer(*(result->input_buffer));
3244 // Note: stream may be deallocated at this point, if this buffer was the
3245 // last reference to it.
3246 if (res != OK) {
3247 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3248 " its stream:%s (%d)", __FUNCTION__,
3249 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003250 }
3251 } else {
3252 ALOGW("%s: Input buffer should be NULL if there is no input"
3253 " buffer sent in the request, skipping input buffer return.",
3254 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003255 }
3256 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003257}
3258
3259void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003260 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003261 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003262 {
3263 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003264 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003265 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003266
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003267 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003268 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003269 return;
3270 }
3271
3272 switch (msg->type) {
3273 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003274 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003275 break;
3276 }
3277 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003278 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003279 break;
3280 }
3281 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003282 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003283 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003284 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003285}
3286
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003287void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003288 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003289 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003290 // Map camera HAL error codes to ICameraDeviceCallback error codes
3291 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003292 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003293 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003294 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003295 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003296 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003297 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003298 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003299 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003300 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003301 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003302 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003303 };
3304
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003305 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003306 ((msg.error_code >= 0) &&
3307 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3308 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003309 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003310
3311 int streamId = 0;
3312 if (msg.error_stream != NULL) {
3313 Camera3Stream *stream =
3314 Camera3Stream::cast(msg.error_stream);
3315 streamId = stream->getId();
3316 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003317 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3318 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003319 streamId, msg.error_code);
3320
3321 CaptureResultExtras resultExtras;
3322 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003323 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003324 // SET_ERR calls notifyError
3325 SET_ERR("Camera HAL reported serious device error");
3326 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003327 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3328 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3329 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003330 {
3331 Mutex::Autolock l(mInFlightLock);
3332 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3333 if (idx >= 0) {
3334 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3335 r.requestStatus = msg.error_code;
3336 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003337 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3338 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3339 errorCode) {
3340 r.skipResultMetadata = true;
3341 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003342 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3343 errorCode) {
3344 // In case of missing result check whether the buffers
3345 // returned. If they returned, then remove inflight
3346 // request.
3347 removeInFlightRequestIfReadyLocked(idx);
3348 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003349 } else {
3350 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003351 ALOGE("Camera %s: %s: cannot find in-flight request on "
3352 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003353 resultExtras.frameNumber);
3354 }
3355 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003356 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003357 if (listener != NULL) {
3358 listener->notifyError(errorCode, resultExtras);
3359 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003360 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003361 }
3362 break;
3363 default:
3364 // SET_ERR calls notifyError
3365 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3366 break;
3367 }
3368}
3369
3370void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003371 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003372 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003373 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003374
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003375 // Set timestamp for the request in the in-flight tracking
3376 // and get the request ID to send upstream
3377 {
3378 Mutex::Autolock l(mInFlightLock);
3379 idx = mInFlightMap.indexOfKey(msg.frame_number);
3380 if (idx >= 0) {
3381 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003382
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003383 // Verify ordering of shutter notifications
3384 {
3385 Mutex::Autolock l(mOutputLock);
3386 // TODO: need to track errors for tighter bounds on expected frame number.
3387 if (r.hasInputBuffer) {
3388 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3389 SET_ERR("Shutter notification out-of-order. Expected "
3390 "notification for frame %d, got frame %d",
3391 mNextReprocessShutterFrameNumber, msg.frame_number);
3392 return;
3393 }
3394 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3395 } else {
3396 if (msg.frame_number < mNextShutterFrameNumber) {
3397 SET_ERR("Shutter notification out-of-order. Expected "
3398 "notification for frame %d, got frame %d",
3399 mNextShutterFrameNumber, msg.frame_number);
3400 return;
3401 }
3402 mNextShutterFrameNumber = msg.frame_number + 1;
3403 }
3404 }
3405
Shuzhen Wang4a472662017-02-26 23:29:04 -08003406 r.shutterTimestamp = msg.timestamp;
3407 if (r.hasCallback) {
3408 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003409 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003410 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003411 // Call listener, if any
3412 if (listener != NULL) {
3413 listener->notifyShutter(r.resultExtras, msg.timestamp);
3414 }
3415 // send pending result and buffers
3416 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3417 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003418 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003419 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003420 returnOutputBuffers(r.pendingOutputBuffers.array(),
3421 r.pendingOutputBuffers.size(), r.shutterTimestamp);
3422 r.pendingOutputBuffers.clear();
3423
3424 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003425 }
3426 }
3427 if (idx < 0) {
3428 SET_ERR("Shutter notification for non-existent frame number %d",
3429 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003430 }
3431}
3432
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003433CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003434 ALOGV("%s", __FUNCTION__);
3435
Igor Murashkin1e479c02013-09-06 16:55:14 -07003436 CameraMetadata retVal;
3437
3438 if (mRequestThread != NULL) {
3439 retVal = mRequestThread->getLatestRequest();
3440 }
3441
Igor Murashkin1e479c02013-09-06 16:55:14 -07003442 return retVal;
3443}
3444
Jianing Weicb0652e2014-03-12 18:29:36 -07003445
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003446void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3447 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3448 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3449}
3450
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003451/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003452 * HalInterface inner class methods
3453 */
3454
Yifan Hongf79b5542017-04-11 14:44:25 -07003455Camera3Device::HalInterface::HalInterface(
3456 sp<ICameraDeviceSession> &session,
3457 std::shared_ptr<RequestMetadataQueue> queue) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003458 mHidlSession(session),
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003459 mRequestMetadataQueue(queue) {
3460 // Check with hardware service manager if we can downcast these interfaces
3461 // Somewhat expensive, so cache the results at startup
3462 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3463 if (castResult_3_4.isOk()) {
3464 mHidlSession_3_4 = castResult_3_4;
3465 }
3466 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3467 if (castResult_3_3.isOk()) {
3468 mHidlSession_3_3 = castResult_3_3;
3469 }
3470}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003471
Emilian Peev31abd0a2017-05-11 18:37:46 +01003472Camera3Device::HalInterface::HalInterface() {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003473
3474Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003475 mHidlSession(other.mHidlSession),
3476 mRequestMetadataQueue(other.mRequestMetadataQueue) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003477
3478bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003479 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003480}
3481
3482void Camera3Device::HalInterface::clear() {
Emilian Peev9e740b02018-01-30 18:28:03 +00003483 mHidlSession_3_4.clear();
3484 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003485 mHidlSession.clear();
3486}
3487
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003488bool Camera3Device::HalInterface::supportBatchRequest() {
3489 return mHidlSession != nullptr;
3490}
3491
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003492status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3493 camera3_request_template_t templateId,
3494 /*out*/ camera_metadata_t **requestTemplate) {
3495 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3496 if (!valid()) return INVALID_OPERATION;
3497 status_t res = OK;
3498
Emilian Peev31abd0a2017-05-11 18:37:46 +01003499 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003500
3501 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003502 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003503 status = s;
3504 if (status == common::V1_0::Status::OK) {
3505 const camera_metadata *r =
3506 reinterpret_cast<const camera_metadata_t*>(request.data());
3507 size_t expectedSize = request.size();
3508 int ret = validate_camera_metadata_structure(r, &expectedSize);
3509 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3510 *requestTemplate = clone_camera_metadata(r);
3511 if (*requestTemplate == nullptr) {
3512 ALOGE("%s: Unable to clone camera metadata received from HAL",
3513 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003514 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003515 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003516 } else {
3517 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
3518 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003519 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003520 }
3521 };
3522 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003523 RequestTemplate id;
3524 switch (templateId) {
3525 case CAMERA3_TEMPLATE_PREVIEW:
3526 id = RequestTemplate::PREVIEW;
3527 break;
3528 case CAMERA3_TEMPLATE_STILL_CAPTURE:
3529 id = RequestTemplate::STILL_CAPTURE;
3530 break;
3531 case CAMERA3_TEMPLATE_VIDEO_RECORD:
3532 id = RequestTemplate::VIDEO_RECORD;
3533 break;
3534 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
3535 id = RequestTemplate::VIDEO_SNAPSHOT;
3536 break;
3537 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
3538 id = RequestTemplate::ZERO_SHUTTER_LAG;
3539 break;
3540 case CAMERA3_TEMPLATE_MANUAL:
3541 id = RequestTemplate::MANUAL;
3542 break;
3543 default:
3544 // Unknown template ID, or this HAL is too old to support it
3545 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003546 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08003547 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003548
Emilian Peev31abd0a2017-05-11 18:37:46 +01003549 if (!err.isOk()) {
3550 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3551 res = DEAD_OBJECT;
3552 } else {
3553 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003554 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003555
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003556 return res;
3557}
3558
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003559status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00003560 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003561 ATRACE_NAME("CameraHal::configureStreams");
3562 if (!valid()) return INVALID_OPERATION;
3563 status_t res = OK;
3564
Emilian Peev31abd0a2017-05-11 18:37:46 +01003565 // Convert stream config to HIDL
3566 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003567 device::V3_2::StreamConfiguration requestedConfiguration3_2;
3568 device::V3_4::StreamConfiguration requestedConfiguration3_4;
3569 requestedConfiguration3_2.streams.resize(config->num_streams);
3570 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003571 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003572 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
3573 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01003574 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003575
Emilian Peev31abd0a2017-05-11 18:37:46 +01003576 Camera3Stream* cam3stream = Camera3Stream::cast(src);
3577 cam3stream->setBufferFreedListener(this);
3578 int streamId = cam3stream->getId();
3579 StreamType streamType;
3580 switch (src->stream_type) {
3581 case CAMERA3_STREAM_OUTPUT:
3582 streamType = StreamType::OUTPUT;
3583 break;
3584 case CAMERA3_STREAM_INPUT:
3585 streamType = StreamType::INPUT;
3586 break;
3587 default:
3588 ALOGE("%s: Stream %d: Unsupported stream type %d",
3589 __FUNCTION__, streamId, config->streams[i]->stream_type);
3590 return BAD_VALUE;
3591 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003592 dst3_2.id = streamId;
3593 dst3_2.streamType = streamType;
3594 dst3_2.width = src->width;
3595 dst3_2.height = src->height;
3596 dst3_2.format = mapToPixelFormat(src->format);
3597 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
3598 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
3599 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
3600 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00003601 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003602 if (src->physical_camera_id != nullptr) {
3603 dst3_4.physicalCameraId = src->physical_camera_id;
3604 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003605
3606 activeStreams.insert(streamId);
3607 // Create Buffer ID map if necessary
3608 if (mBufferIdMaps.count(streamId) == 0) {
3609 mBufferIdMaps.emplace(streamId, BufferIdMap{});
3610 }
3611 }
3612 // remove BufferIdMap for deleted streams
3613 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
3614 int streamId = it->first;
3615 bool active = activeStreams.count(streamId) > 0;
3616 if (!active) {
3617 it = mBufferIdMaps.erase(it);
3618 } else {
3619 ++it;
3620 }
3621 }
3622
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003623 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003624 res = mapToStreamConfigurationMode(
3625 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003626 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01003627 if (res != OK) {
3628 return res;
3629 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003630 requestedConfiguration3_2.operationMode = operationMode;
3631 requestedConfiguration3_4.operationMode = operationMode;
3632 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003633 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
3634 get_camera_metadata_size(sessionParams));
3635
Emilian Peev31abd0a2017-05-11 18:37:46 +01003636 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003637 device::V3_3::HalStreamConfiguration finalConfiguration;
Emilian Peev31abd0a2017-05-11 18:37:46 +01003638 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003639
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003640 // See if we have v3.4 or v3.3 HAL
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003641 if (mHidlSession_3_4 != nullptr) {
3642 // We do; use v3.4 for the call
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003643 ALOGV("%s: v3.4 device found", __FUNCTION__);
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003644 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003645 auto err = mHidlSession_3_4->configureStreams_3_4(requestedConfiguration3_4,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003646 [&status, &finalConfiguration3_4]
3647 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
3648 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003649 status = s;
3650 });
3651 if (!err.isOk()) {
3652 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3653 return DEAD_OBJECT;
3654 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003655 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
3656 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
3657 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
3658 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003659 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003660 // We do; use v3.3 for the call
3661 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003662 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01003663 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003664 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003665 finalConfiguration = halConfiguration;
3666 status = s;
3667 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003668 if (!err.isOk()) {
3669 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3670 return DEAD_OBJECT;
3671 }
3672 } else {
3673 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
3674 ALOGV("%s: v3.2 device found", __FUNCTION__);
3675 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003676 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003677 [&status, &finalConfiguration_3_2]
3678 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
3679 finalConfiguration_3_2 = halConfiguration;
3680 status = s;
3681 });
3682 if (!err.isOk()) {
3683 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3684 return DEAD_OBJECT;
3685 }
3686 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
3687 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
3688 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
3689 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08003690 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003691 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003692 }
3693
3694 if (status != common::V1_0::Status::OK ) {
3695 return CameraProviderManager::mapToStatusT(status);
3696 }
3697
3698 // And convert output stream configuration from HIDL
3699
3700 for (size_t i = 0; i < config->num_streams; i++) {
3701 camera3_stream_t *dst = config->streams[i];
3702 int streamId = Camera3Stream::cast(dst)->getId();
3703
3704 // Start scan at i, with the assumption that the stream order matches
3705 size_t realIdx = i;
3706 bool found = false;
3707 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003708 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003709 found = true;
3710 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003711 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003712 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
3713 }
3714 if (!found) {
3715 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
3716 __FUNCTION__, streamId);
3717 return INVALID_OPERATION;
3718 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003719 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003720
Emilian Peev710c1422017-08-30 11:19:38 +01003721 Camera3Stream* dstStream = Camera3Stream::cast(dst);
3722 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003723 dstStream->setDataSpaceOverride(false);
3724 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
3725 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
3726
Emilian Peev31abd0a2017-05-11 18:37:46 +01003727 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
3728 if (dst->format != overrideFormat) {
3729 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
3730 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003731 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003732 if (dst->data_space != overrideDataSpace) {
3733 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
3734 streamId, dst->format);
3735 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003736 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01003737 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003738 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
3739
Emilian Peev31abd0a2017-05-11 18:37:46 +01003740 // Override allowed with IMPLEMENTATION_DEFINED
3741 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003742 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08003743 }
3744
Emilian Peev31abd0a2017-05-11 18:37:46 +01003745 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003746 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003747 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003748 __FUNCTION__, streamId);
3749 return INVALID_OPERATION;
3750 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003751 dstStream->setUsage(
3752 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01003753 } else {
3754 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003755 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003756 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
3757 __FUNCTION__, streamId);
3758 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003759 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003760 dstStream->setUsage(
3761 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003762 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07003763 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003764 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01003765
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003766 return res;
3767}
3768
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003769void Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
3770 /*out*/device::V3_2::CaptureRequest* captureRequest,
3771 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003772 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003773 if (captureRequest == nullptr || handlesCreated == nullptr) {
3774 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
3775 __FUNCTION__, captureRequest, handlesCreated);
3776 return;
3777 }
3778
3779 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07003780
3781 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003782
3783 {
3784 std::lock_guard<std::mutex> lock(mInflightLock);
3785 if (request->input_buffer != nullptr) {
3786 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
3787 buffer_handle_t buf = *(request->input_buffer->buffer);
3788 auto pair = getBufferId(buf, streamId);
3789 bool isNewBuffer = pair.first;
3790 uint64_t bufferId = pair.second;
3791 captureRequest->inputBuffer.streamId = streamId;
3792 captureRequest->inputBuffer.bufferId = bufferId;
3793 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
3794 captureRequest->inputBuffer.status = BufferStatus::OK;
3795 native_handle_t *acquireFence = nullptr;
3796 if (request->input_buffer->acquire_fence != -1) {
3797 acquireFence = native_handle_create(1,0);
3798 acquireFence->data[0] = request->input_buffer->acquire_fence;
3799 handlesCreated->push_back(acquireFence);
3800 }
3801 captureRequest->inputBuffer.acquireFence = acquireFence;
3802 captureRequest->inputBuffer.releaseFence = nullptr;
3803
3804 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3805 request->input_buffer->buffer,
3806 request->input_buffer->acquire_fence);
3807 } else {
3808 captureRequest->inputBuffer.streamId = -1;
3809 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
3810 }
3811
3812 captureRequest->outputBuffers.resize(request->num_output_buffers);
3813 for (size_t i = 0; i < request->num_output_buffers; i++) {
3814 const camera3_stream_buffer_t *src = request->output_buffers + i;
3815 StreamBuffer &dst = captureRequest->outputBuffers[i];
3816 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
3817 buffer_handle_t buf = *(src->buffer);
3818 auto pair = getBufferId(buf, streamId);
3819 bool isNewBuffer = pair.first;
3820 dst.streamId = streamId;
3821 dst.bufferId = pair.second;
3822 dst.buffer = isNewBuffer ? buf : nullptr;
3823 dst.status = BufferStatus::OK;
3824 native_handle_t *acquireFence = nullptr;
3825 if (src->acquire_fence != -1) {
3826 acquireFence = native_handle_create(1,0);
3827 acquireFence->data[0] = src->acquire_fence;
3828 handlesCreated->push_back(acquireFence);
3829 }
3830 dst.acquireFence = acquireFence;
3831 dst.releaseFence = nullptr;
3832
3833 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
3834 src->buffer, src->acquire_fence);
3835 }
3836 }
3837}
3838
3839status_t Camera3Device::HalInterface::processBatchCaptureRequests(
3840 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
3841 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
3842 if (!valid()) return INVALID_OPERATION;
3843
Emilian Peevaebbe412018-01-15 13:53:24 +00003844 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
3845 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3846 if (castResult_3_4.isOk()) {
3847 hidlSession_3_4 = castResult_3_4;
3848 }
3849
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003850 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00003851 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003852 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00003853 if (hidlSession_3_4 != nullptr) {
3854 captureRequests_3_4.resize(batchSize);
3855 } else {
3856 captureRequests.resize(batchSize);
3857 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003858 std::vector<native_handle_t*> handlesCreated;
3859
3860 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00003861 if (hidlSession_3_4 != nullptr) {
3862 wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
3863 /*out*/&handlesCreated);
3864 } else {
3865 wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i], /*out*/&handlesCreated);
3866 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003867 }
3868
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07003869 std::vector<device::V3_2::BufferCache> cachesToRemove;
3870 {
3871 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
3872 for (auto& pair : mFreedBuffers) {
3873 // The stream might have been removed since onBufferFreed
3874 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
3875 cachesToRemove.push_back({pair.first, pair.second});
3876 }
3877 }
3878 mFreedBuffers.clear();
3879 }
3880
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003881 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
3882 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07003883
3884 // Write metadata to FMQ.
3885 for (size_t i = 0; i < batchSize; i++) {
3886 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00003887 device::V3_2::CaptureRequest* captureRequest;
3888 if (hidlSession_3_4 != nullptr) {
3889 captureRequest = &captureRequests_3_4[i].v3_2;
3890 } else {
3891 captureRequest = &captureRequests[i];
3892 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003893
3894 if (request->settings != nullptr) {
3895 size_t settingsSize = get_camera_metadata_size(request->settings);
3896 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3897 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
3898 captureRequest->settings.resize(0);
3899 captureRequest->fmqSettingsSize = settingsSize;
3900 } else {
3901 if (mRequestMetadataQueue != nullptr) {
3902 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3903 }
3904 captureRequest->settings.setToExternal(
3905 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
3906 get_camera_metadata_size(request->settings));
3907 captureRequest->fmqSettingsSize = 0u;
3908 }
3909 } else {
3910 // A null request settings maps to a size-0 CameraMetadata
3911 captureRequest->settings.resize(0);
3912 captureRequest->fmqSettingsSize = 0u;
3913 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003914
3915 if (hidlSession_3_4 != nullptr) {
3916 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
3917 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00003918 if (request->physcam_settings != nullptr) {
3919 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
3920 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
3921 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
3922 settingsSize)) {
3923 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
3924 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
3925 settingsSize;
3926 } else {
3927 if (mRequestMetadataQueue != nullptr) {
3928 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
3929 }
3930 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
3931 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
3932 request->physcam_settings[j])),
3933 get_camera_metadata_size(request->physcam_settings[j]));
3934 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00003935 }
Emilian Peev00420d22018-02-05 21:33:13 +00003936 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00003937 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00003938 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00003939 }
3940 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
3941 request->physcam_id[j];
3942 }
3943 }
Yifan Hongf79b5542017-04-11 14:44:25 -07003944 }
Emilian Peevaebbe412018-01-15 13:53:24 +00003945
3946 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003947 auto resultCallback =
3948 [&status, &numRequestProcessed] (auto s, uint32_t n) {
3949 status = s;
3950 *numRequestProcessed = n;
3951 };
Emilian Peevaebbe412018-01-15 13:53:24 +00003952 if (hidlSession_3_4 != nullptr) {
3953 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003954 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003955 } else {
3956 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07003957 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00003958 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07003959 if (!err.isOk()) {
3960 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3961 return DEAD_OBJECT;
3962 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003963 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
3964 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
3965 __FUNCTION__, *numRequestProcessed, batchSize);
3966 status = common::V1_0::Status::INTERNAL_ERROR;
3967 }
3968
3969 for (auto& handle : handlesCreated) {
3970 native_handle_delete(handle);
3971 }
3972 return CameraProviderManager::mapToStatusT(status);
3973}
3974
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003975status_t Camera3Device::HalInterface::processCaptureRequest(
3976 camera3_capture_request_t *request) {
3977 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003978 if (!valid()) return INVALID_OPERATION;
3979 status_t res = OK;
3980
Emilian Peev31abd0a2017-05-11 18:37:46 +01003981 uint32_t numRequestProcessed = 0;
3982 std::vector<camera3_capture_request_t*> requests(1);
3983 requests[0] = request;
3984 res = processBatchCaptureRequests(requests, &numRequestProcessed);
3985
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003986 return res;
3987}
3988
3989status_t Camera3Device::HalInterface::flush() {
3990 ATRACE_NAME("CameraHal::flush");
3991 if (!valid()) return INVALID_OPERATION;
3992 status_t res = OK;
3993
Emilian Peev31abd0a2017-05-11 18:37:46 +01003994 auto err = mHidlSession->flush();
3995 if (!err.isOk()) {
3996 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
3997 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003998 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003999 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004000 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004001
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004002 return res;
4003}
4004
Emilian Peev31abd0a2017-05-11 18:37:46 +01004005status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004006 ATRACE_NAME("CameraHal::dump");
4007 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004008
Emilian Peev31abd0a2017-05-11 18:37:46 +01004009 // Handled by CameraProviderManager::dump
4010
4011 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004012}
4013
4014status_t Camera3Device::HalInterface::close() {
4015 ATRACE_NAME("CameraHal::close()");
4016 if (!valid()) return INVALID_OPERATION;
4017 status_t res = OK;
4018
Emilian Peev31abd0a2017-05-11 18:37:46 +01004019 auto err = mHidlSession->close();
4020 // Interface will be dead shortly anyway, so don't log errors
4021 if (!err.isOk()) {
4022 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004023 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004024
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004025 return res;
4026}
4027
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004028void Camera3Device::HalInterface::getInflightBufferKeys(
4029 std::vector<std::pair<int32_t, int32_t>>* out) {
4030 std::lock_guard<std::mutex> lock(mInflightLock);
4031 out->clear();
4032 out->reserve(mInflightBufferMap.size());
4033 for (auto& pair : mInflightBufferMap) {
4034 uint64_t key = pair.first;
4035 int32_t streamId = key & 0xFFFFFFFF;
4036 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4037 out->push_back(std::make_pair(frameNumber, streamId));
4038 }
4039 return;
4040}
4041
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004042status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004043 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004044 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004045 auto pair = std::make_pair(buffer, acquireFence);
4046 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004047 return OK;
4048}
4049
4050status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004051 int32_t frameNumber, int32_t streamId,
4052 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004053 std::lock_guard<std::mutex> lock(mInflightLock);
4054
4055 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4056 auto it = mInflightBufferMap.find(key);
4057 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004058 auto pair = it->second;
4059 *buffer = pair.first;
4060 int acquireFence = pair.second;
4061 if (acquireFence > 0) {
4062 ::close(acquireFence);
4063 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004064 mInflightBufferMap.erase(it);
4065 return OK;
4066}
4067
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004068std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4069 const buffer_handle_t& buf, int streamId) {
4070 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4071
4072 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4073 auto it = bIdMap.find(buf);
4074 if (it == bIdMap.end()) {
4075 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004076 ALOGV("stream %d now have %zu buffer caches, buf %p",
4077 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004078 return std::make_pair(true, mNextBufferId - 1);
4079 } else {
4080 return std::make_pair(false, it->second);
4081 }
4082}
4083
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004084void Camera3Device::HalInterface::onBufferFreed(
4085 int streamId, const native_handle_t* handle) {
4086 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4087 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4088 auto mapIt = mBufferIdMaps.find(streamId);
4089 if (mapIt == mBufferIdMaps.end()) {
4090 // streamId might be from a deleted stream here
4091 ALOGI("%s: stream %d has been removed",
4092 __FUNCTION__, streamId);
4093 return;
4094 }
4095 BufferIdMap& bIdMap = mapIt->second;
4096 auto it = bIdMap.find(handle);
4097 if (it == bIdMap.end()) {
4098 ALOGW("%s: cannot find buffer %p in stream %d",
4099 __FUNCTION__, handle, streamId);
4100 return;
4101 } else {
4102 bufferId = it->second;
4103 bIdMap.erase(it);
4104 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4105 __FUNCTION__, streamId, bIdMap.size(), handle);
4106 }
4107 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4108}
4109
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004110/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004111 * RequestThread inner class methods
4112 */
4113
4114Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004115 sp<StatusTracker> statusTracker,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004116 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004117 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004118 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004119 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004120 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004121 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004122 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004123 mReconfigured(false),
4124 mDoPause(false),
4125 mPaused(true),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004126 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004127 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004128 mCurrentAfTriggerId(0),
4129 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004130 mRepeatingLastFrameNumber(
4131 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004132 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004133 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004134 mRequestLatency(kRequestLatencyBinSize),
4135 mSessionParamKeys(sessionParamKeys),
4136 mLatestSessionParams(sessionParamKeys.size()) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004137 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004138}
4139
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004140Camera3Device::RequestThread::~RequestThread() {}
4141
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004142void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004143 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004144 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004145 Mutex::Autolock l(mRequestLock);
4146 mListener = listener;
4147}
4148
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004149void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4150 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004151 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004152 Mutex::Autolock l(mRequestLock);
4153 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004154 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004155 // Prepare video stream for high speed recording.
4156 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004157 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004158}
4159
Jianing Wei90e59c92014-03-12 18:29:36 -07004160status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004161 List<sp<CaptureRequest> > &requests,
4162 /*out*/
4163 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004164 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004165 Mutex::Autolock l(mRequestLock);
4166 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4167 ++it) {
4168 mRequestQueue.push_back(*it);
4169 }
4170
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004171 if (lastFrameNumber != NULL) {
4172 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4173 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4174 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4175 *lastFrameNumber);
4176 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004177
Jianing Wei90e59c92014-03-12 18:29:36 -07004178 unpauseForNewRequests();
4179
4180 return OK;
4181}
4182
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004183
4184status_t Camera3Device::RequestThread::queueTrigger(
4185 RequestTrigger trigger[],
4186 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004187 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004188 Mutex::Autolock l(mTriggerMutex);
4189 status_t ret;
4190
4191 for (size_t i = 0; i < count; ++i) {
4192 ret = queueTriggerLocked(trigger[i]);
4193
4194 if (ret != OK) {
4195 return ret;
4196 }
4197 }
4198
4199 return OK;
4200}
4201
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004202const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4203 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004204 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004205 if (d != nullptr) return d->mId;
4206 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004207}
4208
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004209status_t Camera3Device::RequestThread::queueTriggerLocked(
4210 RequestTrigger trigger) {
4211
4212 uint32_t tag = trigger.metadataTag;
4213 ssize_t index = mTriggerMap.indexOfKey(tag);
4214
4215 switch (trigger.getTagType()) {
4216 case TYPE_BYTE:
4217 // fall-through
4218 case TYPE_INT32:
4219 break;
4220 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004221 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4222 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004223 return INVALID_OPERATION;
4224 }
4225
4226 /**
4227 * Collect only the latest trigger, since we only have 1 field
4228 * in the request settings per trigger tag, and can't send more than 1
4229 * trigger per request.
4230 */
4231 if (index != NAME_NOT_FOUND) {
4232 mTriggerMap.editValueAt(index) = trigger;
4233 } else {
4234 mTriggerMap.add(tag, trigger);
4235 }
4236
4237 return OK;
4238}
4239
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004240status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004241 const RequestList &requests,
4242 /*out*/
4243 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004244 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004245 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004246 if (lastFrameNumber != NULL) {
4247 *lastFrameNumber = mRepeatingLastFrameNumber;
4248 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004249 mRepeatingRequests.clear();
4250 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4251 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004252
4253 unpauseForNewRequests();
4254
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004255 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004256 return OK;
4257}
4258
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004259bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004260 if (mRepeatingRequests.empty()) {
4261 return false;
4262 }
4263 int32_t requestId = requestIn->mResultExtras.requestId;
4264 const RequestList &repeatRequests = mRepeatingRequests;
4265 // All repeating requests are guaranteed to have same id so only check first quest
4266 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4267 return (firstRequest->mResultExtras.requestId == requestId);
4268}
4269
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004270status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004271 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004272 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004273 return clearRepeatingRequestsLocked(lastFrameNumber);
4274
4275}
4276
4277status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004278 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004279 if (lastFrameNumber != NULL) {
4280 *lastFrameNumber = mRepeatingLastFrameNumber;
4281 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004282 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004283 return OK;
4284}
4285
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004286status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004287 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004288 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004289 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004290 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004291
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004292 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004293
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004294 // Send errors for all requests pending in the request queue, including
4295 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004296 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004297 if (listener != NULL) {
4298 for (RequestList::iterator it = mRequestQueue.begin();
4299 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004300 // Abort the input buffers for reprocess requests.
4301 if ((*it)->mInputStream != NULL) {
4302 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004303 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4304 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004305 if (res != OK) {
4306 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4307 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4308 } else {
4309 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4310 if (res != OK) {
4311 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4312 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4313 }
4314 }
4315 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004316 // Set the frame number this request would have had, if it
4317 // had been submitted; this frame number will not be reused.
4318 // The requestId and burstId fields were set when the request was
4319 // submitted originally (in convertMetadataListToRequestListLocked)
4320 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004321 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004322 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004323 }
4324 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004325 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004326
4327 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004328 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004329 if (lastFrameNumber != NULL) {
4330 *lastFrameNumber = mRepeatingLastFrameNumber;
4331 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004332 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004333 return OK;
4334}
4335
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004336status_t Camera3Device::RequestThread::flush() {
4337 ATRACE_CALL();
4338 Mutex::Autolock l(mFlushLock);
4339
Emilian Peev08dd2452017-04-06 16:55:14 +01004340 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004341}
4342
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004343void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004344 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004345 Mutex::Autolock l(mPauseLock);
4346 mDoPause = paused;
4347 mDoPauseSignal.signal();
4348}
4349
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004350status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4351 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004352 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004353 Mutex::Autolock l(mLatestRequestMutex);
4354 status_t res;
4355 while (mLatestRequestId != requestId) {
4356 nsecs_t startTime = systemTime();
4357
4358 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4359 if (res != OK) return res;
4360
4361 timeout -= (systemTime() - startTime);
4362 }
4363
4364 return OK;
4365}
4366
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004367void Camera3Device::RequestThread::requestExit() {
4368 // Call parent to set up shutdown
4369 Thread::requestExit();
4370 // The exit from any possible waits
4371 mDoPauseSignal.signal();
4372 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07004373
4374 mRequestLatency.log("ProcessCaptureRequest latency histogram");
4375 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004376}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004377
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004378void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004379 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004380 bool surfaceAbandoned = false;
4381 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004382 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004383 {
4384 Mutex::Autolock l(mRequestLock);
4385 // Check all streams needed by repeating requests are still valid. Otherwise, stop
4386 // repeating requests.
4387 for (const auto& request : mRepeatingRequests) {
4388 for (const auto& s : request->mOutputStreams) {
4389 if (s->isAbandoned()) {
4390 surfaceAbandoned = true;
4391 clearRepeatingRequestsLocked(&lastFrameNumber);
4392 break;
4393 }
4394 }
4395 if (surfaceAbandoned) {
4396 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004397 }
4398 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004399 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004400 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004401
4402 if (listener != NULL && surfaceAbandoned) {
4403 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07004404 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004405}
4406
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004407bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004408 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004409 status_t res;
4410 size_t batchSize = mNextRequests.size();
4411 std::vector<camera3_capture_request_t*> requests(batchSize);
4412 uint32_t numRequestProcessed = 0;
4413 for (size_t i = 0; i < batchSize; i++) {
4414 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07004415 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004416 }
4417
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004418 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
4419
4420 bool triggerRemoveFailed = false;
4421 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
4422 for (size_t i = 0; i < numRequestProcessed; i++) {
4423 NextRequest& nextRequest = mNextRequests.editItemAt(i);
4424 nextRequest.submitted = true;
4425
4426
4427 // Update the latest request sent to HAL
4428 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4429 Mutex::Autolock al(mLatestRequestMutex);
4430
4431 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4432 mLatestRequest.acquire(cloned);
4433
4434 sp<Camera3Device> parent = mParent.promote();
4435 if (parent != NULL) {
4436 parent->monitorMetadata(TagMonitor::REQUEST,
4437 nextRequest.halRequest.frame_number,
4438 0, mLatestRequest);
4439 }
4440 }
4441
4442 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004443 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4444 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004445 }
4446
Emilian Peevaebbe412018-01-15 13:53:24 +00004447 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4448
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004449 if (!triggerRemoveFailed) {
4450 // Remove any previously queued triggers (after unlock)
4451 status_t removeTriggerRes = removeTriggers(mPrevRequest);
4452 if (removeTriggerRes != OK) {
4453 triggerRemoveFailed = true;
4454 triggerFailedRequest = nextRequest;
4455 }
4456 }
4457 }
4458
4459 if (triggerRemoveFailed) {
4460 SET_ERR("RequestThread: Unable to remove triggers "
4461 "(capture request %d, HAL device: %s (%d)",
4462 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
4463 cleanUpFailedRequests(/*sendRequestError*/ false);
4464 return false;
4465 }
4466
4467 if (res != OK) {
4468 // Should only get a failure here for malformed requests or device-level
4469 // errors, so consider all errors fatal. Bad metadata failures should
4470 // come through notify.
4471 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
4472 mNextRequests[numRequestProcessed].halRequest.frame_number,
4473 strerror(-res), res);
4474 cleanUpFailedRequests(/*sendRequestError*/ false);
4475 return false;
4476 }
4477 return true;
4478}
4479
4480bool Camera3Device::RequestThread::sendRequestsOneByOne() {
4481 status_t res;
4482
4483 for (auto& nextRequest : mNextRequests) {
4484 // Submit request and block until ready for next one
4485 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
4486 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
4487
4488 if (res != OK) {
4489 // Should only get a failure here for malformed requests or device-level
4490 // errors, so consider all errors fatal. Bad metadata failures should
4491 // come through notify.
4492 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
4493 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
4494 res);
4495 cleanUpFailedRequests(/*sendRequestError*/ false);
4496 return false;
4497 }
4498
4499 // Mark that the request has be submitted successfully.
4500 nextRequest.submitted = true;
4501
4502 // Update the latest request sent to HAL
4503 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
4504 Mutex::Autolock al(mLatestRequestMutex);
4505
4506 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
4507 mLatestRequest.acquire(cloned);
4508
4509 sp<Camera3Device> parent = mParent.promote();
4510 if (parent != NULL) {
4511 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
4512 0, mLatestRequest);
4513 }
4514 }
4515
4516 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004517 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
4518 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004519 }
4520
Emilian Peevaebbe412018-01-15 13:53:24 +00004521 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
4522
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004523 // Remove any previously queued triggers (after unlock)
4524 res = removeTriggers(mPrevRequest);
4525 if (res != OK) {
4526 SET_ERR("RequestThread: Unable to remove triggers "
4527 "(capture request %d, HAL device: %s (%d)",
4528 nextRequest.halRequest.frame_number, strerror(-res), res);
4529 cleanUpFailedRequests(/*sendRequestError*/ false);
4530 return false;
4531 }
4532 }
4533 return true;
4534}
4535
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004536nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
4537 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
4538 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4539 find_camera_metadata_ro_entry(request,
4540 ANDROID_CONTROL_AE_MODE,
4541 &e);
4542 if (e.count == 0) return maxExpectedDuration;
4543
4544 switch (e.data.u8[0]) {
4545 case ANDROID_CONTROL_AE_MODE_OFF:
4546 find_camera_metadata_ro_entry(request,
4547 ANDROID_SENSOR_EXPOSURE_TIME,
4548 &e);
4549 if (e.count > 0) {
4550 maxExpectedDuration = e.data.i64[0];
4551 }
4552 find_camera_metadata_ro_entry(request,
4553 ANDROID_SENSOR_FRAME_DURATION,
4554 &e);
4555 if (e.count > 0) {
4556 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
4557 }
4558 break;
4559 default:
4560 find_camera_metadata_ro_entry(request,
4561 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
4562 &e);
4563 if (e.count > 1) {
4564 maxExpectedDuration = 1e9 / e.data.u8[0];
4565 }
4566 break;
4567 }
4568
4569 return maxExpectedDuration;
4570}
4571
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004572bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
4573 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
4574 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
4575 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
4576 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
4577 return true;
4578 }
4579
4580 return false;
4581}
4582
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004583bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
4584 ATRACE_CALL();
4585 bool updatesDetected = false;
4586
4587 for (auto tag : mSessionParamKeys) {
4588 camera_metadata_ro_entry entry = settings.find(tag);
4589 camera_metadata_entry lastEntry = mLatestSessionParams.find(tag);
4590
4591 if (entry.count > 0) {
4592 bool isDifferent = false;
4593 if (lastEntry.count > 0) {
4594 // Have a last value, compare to see if changed
4595 if (lastEntry.type == entry.type &&
4596 lastEntry.count == entry.count) {
4597 // Same type and count, compare values
4598 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
4599 size_t entryBytes = bytesPerValue * lastEntry.count;
4600 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
4601 if (cmp != 0) {
4602 isDifferent = true;
4603 }
4604 } else {
4605 // Count or type has changed
4606 isDifferent = true;
4607 }
4608 } else {
4609 // No last entry, so always consider to be different
4610 isDifferent = true;
4611 }
4612
4613 if (isDifferent) {
4614 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004615 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
4616 updatesDetected = true;
4617 }
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004618 mLatestSessionParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004619 }
4620 } else if (lastEntry.count > 0) {
4621 // Value has been removed
4622 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
4623 mLatestSessionParams.erase(tag);
4624 updatesDetected = true;
4625 }
4626 }
4627
4628 return updatesDetected;
4629}
4630
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004631bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004632 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004633 status_t res;
4634
4635 // Handle paused state.
4636 if (waitIfPaused()) {
4637 return true;
4638 }
4639
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004640 // Wait for the next batch of requests.
4641 waitForNextRequestBatch();
4642 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004643 return true;
4644 }
4645
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004646 // Get the latest request ID, if any
4647 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004648 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00004649 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004650 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004651 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004652 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004653 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
4654 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004655 }
4656
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004657 // 'mNextRequests' will at this point contain either a set of HFR batched requests
4658 // or a single request from streaming or burst. In either case the first element
4659 // should contain the latest camera settings that we need to check for any session
4660 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00004661 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004662 res = OK;
4663
4664 //Input stream buffers are already acquired at this point so an input stream
4665 //will not be able to move to idle state unless we force it.
4666 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4667 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
4668 if (res != OK) {
4669 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
4670 cleanUpFailedRequests(/*sendRequestError*/ false);
4671 return false;
4672 }
4673 }
4674
4675 if (res == OK) {
4676 sp<StatusTracker> statusTracker = mStatusTracker.promote();
4677 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08004678 sp<Camera3Device> parent = mParent.promote();
4679 if (parent != nullptr) {
4680 parent->pauseStateNotify(true);
4681 }
4682
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004683 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
4684
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004685 if (parent != nullptr) {
4686 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
4687 }
4688
4689 statusTracker->markComponentActive(mStatusId);
4690 setPaused(false);
4691 }
4692
4693 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
4694 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
4695 if (res != OK) {
4696 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
4697 cleanUpFailedRequests(/*sendRequestError*/ false);
4698 return false;
4699 }
4700 }
4701 }
4702 }
4703
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004704 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004705 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004706 if (res == TIMED_OUT) {
4707 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004708 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004709 // Check if any stream is abandoned.
4710 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004711 return true;
4712 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004713 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004714 return false;
4715 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004716
Zhijun Hecc27e112013-10-03 16:12:43 -07004717 // Inform waitUntilRequestProcessed thread of a new request ID
4718 {
4719 Mutex::Autolock al(mLatestRequestMutex);
4720
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004721 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07004722 mLatestRequestSignal.signal();
4723 }
4724
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004725 // Submit a batch of requests to HAL.
4726 // Use flush lock only when submitting multilple requests in a batch.
4727 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
4728 // which may take a long time to finish so synchronizing flush() and
4729 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
4730 // For now, only synchronize for high speed recording and we should figure something out for
4731 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004732 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07004733
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004734 if (useFlushLock) {
4735 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004736 }
4737
Zhijun Hef0645c12016-08-02 00:58:11 -07004738 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004739 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07004740
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004741 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07004742 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004743 if (mInterface->supportBatchRequest()) {
4744 submitRequestSuccess = sendRequestsBatch();
4745 } else {
4746 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004747 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07004748 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
4749 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07004750
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004751 if (useFlushLock) {
4752 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004753 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004754
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004755 // Unset as current request
4756 {
4757 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004758 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004759 }
4760
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004761 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004762}
4763
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004764status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004765 ATRACE_CALL();
4766
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004767 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004768 for (size_t i = 0; i < mNextRequests.size(); i++) {
4769 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004770 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
4771 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
4772 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
4773
4774 // Prepare a request to HAL
4775 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
4776
4777 // Insert any queued triggers (before metadata is locked)
4778 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004779 if (res < 0) {
4780 SET_ERR("RequestThread: Unable to insert triggers "
4781 "(capture request %d, HAL device: %s (%d)",
4782 halRequest->frame_number, strerror(-res), res);
4783 return INVALID_OPERATION;
4784 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004785
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004786 int triggerCount = res;
4787 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
4788 mPrevTriggers = triggerCount;
4789
4790 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004791 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
4792 // Request settings are all the same within one batch, so only treat the first
4793 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07004794 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00004795 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004796 /**
4797 * HAL workaround:
4798 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
4799 */
4800 res = addDummyTriggerIds(captureRequest);
4801 if (res != OK) {
4802 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
4803 "(capture request %d, HAL device: %s (%d)",
4804 halRequest->frame_number, strerror(-res), res);
4805 return INVALID_OPERATION;
4806 }
4807
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07004808 {
4809 // Correct metadata regions for distortion correction if enabled
4810 sp<Camera3Device> parent = mParent.promote();
4811 if (parent != nullptr) {
4812 res = parent->mDistortionMapper.correctCaptureRequest(
4813 &(captureRequest->mSettingsList.begin()->metadata));
4814 if (res != OK) {
4815 SET_ERR("RequestThread: Unable to correct capture requests "
4816 "for lens distortion for request %d: %s (%d)",
4817 halRequest->frame_number, strerror(-res), res);
4818 return INVALID_OPERATION;
4819 }
4820 }
4821 }
4822
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004823 /**
4824 * The request should be presorted so accesses in HAL
4825 * are O(logn). Sidenote, sorting a sorted metadata is nop.
4826 */
Emilian Peevaebbe412018-01-15 13:53:24 +00004827 captureRequest->mSettingsList.begin()->metadata.sort();
4828 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004829 mPrevRequest = captureRequest;
4830 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
4831
4832 IF_ALOGV() {
4833 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4834 find_camera_metadata_ro_entry(
4835 halRequest->settings,
4836 ANDROID_CONTROL_AF_TRIGGER,
4837 &e
4838 );
4839 if (e.count > 0) {
4840 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
4841 __FUNCTION__,
4842 halRequest->frame_number,
4843 e.data.u8[0]);
4844 }
4845 }
4846 } else {
4847 // leave request.settings NULL to indicate 'reuse latest given'
4848 ALOGVV("%s: Request settings are REUSED",
4849 __FUNCTION__);
4850 }
4851
Emilian Peevaebbe412018-01-15 13:53:24 +00004852 if (captureRequest->mSettingsList.size() > 1) {
4853 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
4854 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00004855 if (newRequest) {
4856 halRequest->physcam_settings =
4857 new const camera_metadata* [halRequest->num_physcam_settings];
4858 } else {
4859 halRequest->physcam_settings = nullptr;
4860 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004861 auto it = ++captureRequest->mSettingsList.begin();
4862 size_t i = 0;
4863 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
4864 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00004865 if (newRequest) {
4866 it->metadata.sort();
4867 halRequest->physcam_settings[i] = it->metadata.getAndLock();
4868 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004869 }
4870 }
4871
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004872 uint32_t totalNumBuffers = 0;
4873
4874 // Fill in buffers
4875 if (captureRequest->mInputStream != NULL) {
4876 halRequest->input_buffer = &captureRequest->mInputBuffer;
4877 totalNumBuffers += 1;
4878 } else {
4879 halRequest->input_buffer = NULL;
4880 }
4881
4882 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
4883 captureRequest->mOutputStreams.size());
4884 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004885 std::set<String8> requestedPhysicalCameras;
Shuzhen Wang4a472662017-02-26 23:29:04 -08004886 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
4887 sp<Camera3OutputStreamInterface> outputStream = captureRequest->mOutputStreams.editItemAt(j);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004888
4889 // Prepare video buffers for high speed recording on the first video request.
4890 if (mPrepareVideoStream && outputStream->isVideoStream()) {
4891 // Only try to prepare video stream on the first video request.
4892 mPrepareVideoStream = false;
4893
4894 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX);
4895 while (res == NOT_ENOUGH_DATA) {
4896 res = outputStream->prepareNextBuffer();
4897 }
4898 if (res != OK) {
4899 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
4900 __FUNCTION__, strerror(-res), res);
4901 outputStream->cancelPrepare();
4902 }
4903 }
4904
Shuzhen Wang4a472662017-02-26 23:29:04 -08004905 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
4906 captureRequest->mOutputSurfaces[j]);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004907 if (res != OK) {
4908 // Can't get output buffer from gralloc queue - this could be due to
4909 // abandoned queue or other consumer misbehavior, so not a fatal
4910 // error
4911 ALOGE("RequestThread: Can't get output buffer, skipping request:"
4912 " %s (%d)", strerror(-res), res);
4913
4914 return TIMED_OUT;
4915 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07004916
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004917 String8 physicalCameraId = outputStream->getPhysicalCameraId();
4918
4919 if (!physicalCameraId.isEmpty()) {
4920 // Physical stream isn't supported for input request.
4921 if (halRequest->input_buffer) {
4922 CLOGE("Physical stream is not supported for input request");
4923 return INVALID_OPERATION;
4924 }
4925 requestedPhysicalCameras.insert(physicalCameraId);
4926 }
4927 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004928 }
4929 totalNumBuffers += halRequest->num_output_buffers;
4930
4931 // Log request in the in-flight queue
4932 sp<Camera3Device> parent = mParent.promote();
4933 if (parent == NULL) {
4934 // Should not happen, and nowhere to send errors to, so just log it
4935 CLOGE("RequestThread: Parent is gone");
4936 return INVALID_OPERATION;
4937 }
Shuzhen Wang4a472662017-02-26 23:29:04 -08004938
4939 // If this request list is for constrained high speed recording (not
4940 // preview), and the current request is not the last one in the batch,
4941 // do not send callback to the app.
4942 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07004943 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08004944 hasCallback = false;
4945 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01004946 bool isStillCapture = false;
4947 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
4948 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
4949 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
4950 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
4951 isStillCapture = true;
4952 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
4953 }
4954 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004955 res = parent->registerInFlight(halRequest->frame_number,
4956 totalNumBuffers, captureRequest->mResultExtras,
4957 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07004958 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08004959 calculateMaxExpectedDuration(halRequest->settings),
Emilian Peev9dd21f42018-08-03 13:39:29 +01004960 requestedPhysicalCameras, isStillCapture);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004961 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
4962 ", burstId = %" PRId32 ".",
4963 __FUNCTION__,
4964 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
4965 captureRequest->mResultExtras.burstId);
4966 if (res != OK) {
4967 SET_ERR("RequestThread: Unable to register new in-flight request:"
4968 " %s (%d)", strerror(-res), res);
4969 return INVALID_OPERATION;
4970 }
4971 }
4972
4973 return OK;
4974}
4975
Igor Murashkin1e479c02013-09-06 16:55:14 -07004976CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004977 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07004978 Mutex::Autolock al(mLatestRequestMutex);
4979
4980 ALOGV("RequestThread::%s", __FUNCTION__);
4981
4982 return mLatestRequest;
4983}
4984
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004985bool Camera3Device::RequestThread::isStreamPending(
4986 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004987 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004988 Mutex::Autolock l(mRequestLock);
4989
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004990 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07004991 if (!nextRequest.submitted) {
4992 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
4993 if (stream == s) return true;
4994 }
4995 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004996 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07004997 }
4998
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004999 for (const auto& request : mRequestQueue) {
5000 for (const auto& s : request->mOutputStreams) {
5001 if (stream == s) return true;
5002 }
5003 if (stream == request->mInputStream) return true;
5004 }
5005
5006 for (const auto& request : mRepeatingRequests) {
5007 for (const auto& s : request->mOutputStreams) {
5008 if (stream == s) return true;
5009 }
5010 if (stream == request->mInputStream) return true;
5011 }
5012
5013 return false;
5014}
Jianing Weicb0652e2014-03-12 18:29:36 -07005015
Emilian Peev40ead602017-09-26 15:46:36 +01005016bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5017 ATRACE_CALL();
5018 Mutex::Autolock l(mRequestLock);
5019
5020 for (const auto& nextRequest : mNextRequests) {
5021 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5022 if (s.first == streamId) {
5023 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5024 if (it != s.second.end()) {
5025 return true;
5026 }
5027 }
5028 }
5029 }
5030
5031 for (const auto& request : mRequestQueue) {
5032 for (const auto& s : request->mOutputSurfaces) {
5033 if (s.first == streamId) {
5034 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5035 if (it != s.second.end()) {
5036 return true;
5037 }
5038 }
5039 }
5040 }
5041
5042 for (const auto& request : mRepeatingRequests) {
5043 for (const auto& s : request->mOutputSurfaces) {
5044 if (s.first == streamId) {
5045 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5046 if (it != s.second.end()) {
5047 return true;
5048 }
5049 }
5050 }
5051 }
5052
5053 return false;
5054}
5055
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005056nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005057 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005058 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005059 return mExpectedInflightDuration > kMinInflightDuration ?
5060 mExpectedInflightDuration : kMinInflightDuration;
5061}
5062
Emilian Peevaebbe412018-01-15 13:53:24 +00005063void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5064 camera3_capture_request_t *halRequest) {
5065 if ((request == nullptr) || (halRequest == nullptr)) {
5066 ALOGE("%s: Invalid request!", __FUNCTION__);
5067 return;
5068 }
5069
5070 if (halRequest->num_physcam_settings > 0) {
5071 if (halRequest->physcam_id != nullptr) {
5072 delete [] halRequest->physcam_id;
5073 halRequest->physcam_id = nullptr;
5074 }
5075 if (halRequest->physcam_settings != nullptr) {
5076 auto it = ++(request->mSettingsList.begin());
5077 size_t i = 0;
5078 for (; it != request->mSettingsList.end(); it++, i++) {
5079 it->metadata.unlock(halRequest->physcam_settings[i]);
5080 }
5081 delete [] halRequest->physcam_settings;
5082 halRequest->physcam_settings = nullptr;
5083 }
5084 }
5085}
5086
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005087void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5088 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005089 return;
5090 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005091
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005092 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005093 // Skip the ones that have been submitted successfully.
5094 if (nextRequest.submitted) {
5095 continue;
5096 }
5097
5098 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5099 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5100 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5101
5102 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005103 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005104 }
5105
Emilian Peevaebbe412018-01-15 13:53:24 +00005106 cleanupPhysicalSettings(captureRequest, halRequest);
5107
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005108 if (captureRequest->mInputStream != NULL) {
5109 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5110 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5111 }
5112
5113 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005114 //Buffers that failed processing could still have
5115 //valid acquire fence.
5116 int acquireFence = (*outputBuffers)[i].acquire_fence;
5117 if (0 <= acquireFence) {
5118 close(acquireFence);
5119 outputBuffers->editItemAt(i).acquire_fence = -1;
5120 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005121 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5122 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0);
5123 }
5124
5125 if (sendRequestError) {
5126 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005127 sp<NotificationListener> listener = mListener.promote();
5128 if (listener != NULL) {
5129 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005130 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005131 captureRequest->mResultExtras);
5132 }
5133 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005134
5135 // Remove yet-to-be submitted inflight request from inflightMap
5136 {
5137 sp<Camera3Device> parent = mParent.promote();
5138 if (parent != NULL) {
5139 Mutex::Autolock l(parent->mInFlightLock);
5140 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5141 if (idx >= 0) {
5142 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5143 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5144 parent->removeInFlightMapEntryLocked(idx);
5145 }
5146 }
5147 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005148 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005149
5150 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005151 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005152}
5153
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005154void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005155 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005156 // Optimized a bit for the simple steady-state case (single repeating
5157 // request), to avoid putting that request in the queue temporarily.
5158 Mutex::Autolock l(mRequestLock);
5159
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005160 assert(mNextRequests.empty());
5161
5162 NextRequest nextRequest;
5163 nextRequest.captureRequest = waitForNextRequestLocked();
5164 if (nextRequest.captureRequest == nullptr) {
5165 return;
5166 }
5167
5168 nextRequest.halRequest = camera3_capture_request_t();
5169 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005170 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005171
5172 // Wait for additional requests
5173 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5174
5175 for (size_t i = 1; i < batchSize; i++) {
5176 NextRequest additionalRequest;
5177 additionalRequest.captureRequest = waitForNextRequestLocked();
5178 if (additionalRequest.captureRequest == nullptr) {
5179 break;
5180 }
5181
5182 additionalRequest.halRequest = camera3_capture_request_t();
5183 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005184 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005185 }
5186
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005187 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005188 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005189 mNextRequests.size(), batchSize);
5190 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005191 }
5192
5193 return;
5194}
5195
5196sp<Camera3Device::CaptureRequest>
5197 Camera3Device::RequestThread::waitForNextRequestLocked() {
5198 status_t res;
5199 sp<CaptureRequest> nextRequest;
5200
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005201 while (mRequestQueue.empty()) {
5202 if (!mRepeatingRequests.empty()) {
5203 // Always atomically enqueue all requests in a repeating request
5204 // list. Guarantees a complete in-sequence set of captures to
5205 // application.
5206 const RequestList &requests = mRepeatingRequests;
5207 RequestList::const_iterator firstRequest =
5208 requests.begin();
5209 nextRequest = *firstRequest;
5210 mRequestQueue.insert(mRequestQueue.end(),
5211 ++firstRequest,
5212 requests.end());
5213 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005214
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005215 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005216
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005217 break;
5218 }
5219
5220 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5221
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005222 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5223 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005224 Mutex::Autolock pl(mPauseLock);
5225 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005226 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005227 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005228 // Let the tracker know
5229 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5230 if (statusTracker != 0) {
5231 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5232 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005233 }
5234 // Stop waiting for now and let thread management happen
5235 return NULL;
5236 }
5237 }
5238
5239 if (nextRequest == NULL) {
5240 // Don't have a repeating request already in hand, so queue
5241 // must have an entry now.
5242 RequestList::iterator firstRequest =
5243 mRequestQueue.begin();
5244 nextRequest = *firstRequest;
5245 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005246 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5247 sp<NotificationListener> listener = mListener.promote();
5248 if (listener != NULL) {
5249 listener->notifyRequestQueueEmpty();
5250 }
5251 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005252 }
5253
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005254 // In case we've been unpaused by setPaused clearing mDoPause, need to
5255 // update internal pause state (capture/setRepeatingRequest unpause
5256 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005257 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005258 if (mPaused) {
5259 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
5260 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5261 if (statusTracker != 0) {
5262 statusTracker->markComponentActive(mStatusId);
5263 }
5264 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005265 mPaused = false;
5266
5267 // Check if we've reconfigured since last time, and reset the preview
5268 // request if so. Can't use 'NULL request == repeat' across configure calls.
5269 if (mReconfigured) {
5270 mPrevRequest.clear();
5271 mReconfigured = false;
5272 }
5273
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005274 if (nextRequest != NULL) {
5275 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005276 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
5277 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005278
5279 // Since RequestThread::clear() removes buffers from the input stream,
5280 // get the right buffer here before unlocking mRequestLock
5281 if (nextRequest->mInputStream != NULL) {
5282 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
5283 if (res != OK) {
5284 // Can't get input buffer from gralloc queue - this could be due to
5285 // disconnected queue or other producer misbehavior, so not a fatal
5286 // error
5287 ALOGE("%s: Can't get input buffer, skipping request:"
5288 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005289
5290 sp<NotificationListener> listener = mListener.promote();
5291 if (listener != NULL) {
5292 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005293 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005294 nextRequest->mResultExtras);
5295 }
5296 return NULL;
5297 }
5298 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005299 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07005300
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005301 return nextRequest;
5302}
5303
5304bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005305 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005306 status_t res;
5307 Mutex::Autolock l(mPauseLock);
5308 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005309 if (mPaused == false) {
5310 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005311 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
5312 // Let the tracker know
5313 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5314 if (statusTracker != 0) {
5315 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5316 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005317 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005318
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005319 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005320 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005321 return true;
5322 }
5323 }
5324 // We don't set mPaused to false here, because waitForNextRequest needs
5325 // to further manage the paused state in case of starvation.
5326 return false;
5327}
5328
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005329void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005330 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005331 // With work to do, mark thread as unpaused.
5332 // If paused by request (setPaused), don't resume, to avoid
5333 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005334 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005335 Mutex::Autolock p(mPauseLock);
5336 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005337 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
5338 if (mPaused) {
5339 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5340 if (statusTracker != 0) {
5341 statusTracker->markComponentActive(mStatusId);
5342 }
5343 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005344 mPaused = false;
5345 }
5346}
5347
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07005348void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
5349 sp<Camera3Device> parent = mParent.promote();
5350 if (parent != NULL) {
5351 va_list args;
5352 va_start(args, fmt);
5353
5354 parent->setErrorStateV(fmt, args);
5355
5356 va_end(args);
5357 }
5358}
5359
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005360status_t Camera3Device::RequestThread::insertTriggers(
5361 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005362 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005363 Mutex::Autolock al(mTriggerMutex);
5364
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005365 sp<Camera3Device> parent = mParent.promote();
5366 if (parent == NULL) {
5367 CLOGE("RequestThread: Parent is gone");
5368 return DEAD_OBJECT;
5369 }
5370
Emilian Peevaebbe412018-01-15 13:53:24 +00005371 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005372 size_t count = mTriggerMap.size();
5373
5374 for (size_t i = 0; i < count; ++i) {
5375 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005376 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005377
5378 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
5379 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
5380 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005381 if (isAeTrigger) {
5382 request->mResultExtras.precaptureTriggerId = triggerId;
5383 mCurrentPreCaptureTriggerId = triggerId;
5384 } else {
5385 request->mResultExtras.afTriggerId = triggerId;
5386 mCurrentAfTriggerId = triggerId;
5387 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01005388 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07005389 }
5390
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005391 camera_metadata_entry entry = metadata.find(tag);
5392
5393 if (entry.count > 0) {
5394 /**
5395 * Already has an entry for this trigger in the request.
5396 * Rewrite it with our requested trigger value.
5397 */
5398 RequestTrigger oldTrigger = trigger;
5399
5400 oldTrigger.entryValue = entry.data.u8[0];
5401
5402 mTriggerReplacedMap.add(tag, oldTrigger);
5403 } else {
5404 /**
5405 * More typical, no trigger entry, so we just add it
5406 */
5407 mTriggerRemovedMap.add(tag, trigger);
5408 }
5409
5410 status_t res;
5411
5412 switch (trigger.getTagType()) {
5413 case TYPE_BYTE: {
5414 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5415 res = metadata.update(tag,
5416 &entryValue,
5417 /*count*/1);
5418 break;
5419 }
5420 case TYPE_INT32:
5421 res = metadata.update(tag,
5422 &trigger.entryValue,
5423 /*count*/1);
5424 break;
5425 default:
5426 ALOGE("%s: Type not supported: 0x%x",
5427 __FUNCTION__,
5428 trigger.getTagType());
5429 return INVALID_OPERATION;
5430 }
5431
5432 if (res != OK) {
5433 ALOGE("%s: Failed to update request metadata with trigger tag %s"
5434 ", value %d", __FUNCTION__, trigger.getTagName(),
5435 trigger.entryValue);
5436 return res;
5437 }
5438
5439 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
5440 trigger.getTagName(),
5441 trigger.entryValue);
5442 }
5443
5444 mTriggerMap.clear();
5445
5446 return count;
5447}
5448
5449status_t Camera3Device::RequestThread::removeTriggers(
5450 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005451 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005452 Mutex::Autolock al(mTriggerMutex);
5453
Emilian Peevaebbe412018-01-15 13:53:24 +00005454 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005455
5456 /**
5457 * Replace all old entries with their old values.
5458 */
5459 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
5460 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
5461
5462 status_t res;
5463
5464 uint32_t tag = trigger.metadataTag;
5465 switch (trigger.getTagType()) {
5466 case TYPE_BYTE: {
5467 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
5468 res = metadata.update(tag,
5469 &entryValue,
5470 /*count*/1);
5471 break;
5472 }
5473 case TYPE_INT32:
5474 res = metadata.update(tag,
5475 &trigger.entryValue,
5476 /*count*/1);
5477 break;
5478 default:
5479 ALOGE("%s: Type not supported: 0x%x",
5480 __FUNCTION__,
5481 trigger.getTagType());
5482 return INVALID_OPERATION;
5483 }
5484
5485 if (res != OK) {
5486 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
5487 ", trigger value %d", __FUNCTION__,
5488 trigger.getTagName(), trigger.entryValue);
5489 return res;
5490 }
5491 }
5492 mTriggerReplacedMap.clear();
5493
5494 /**
5495 * Remove all new entries.
5496 */
5497 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
5498 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
5499 status_t res = metadata.erase(trigger.metadataTag);
5500
5501 if (res != OK) {
5502 ALOGE("%s: Failed to erase metadata with trigger tag %s"
5503 ", trigger value %d", __FUNCTION__,
5504 trigger.getTagName(), trigger.entryValue);
5505 return res;
5506 }
5507 }
5508 mTriggerRemovedMap.clear();
5509
5510 return OK;
5511}
5512
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005513status_t Camera3Device::RequestThread::addDummyTriggerIds(
5514 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005515 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005516 static const int32_t dummyTriggerId = 1;
5517 status_t res;
5518
Emilian Peevaebbe412018-01-15 13:53:24 +00005519 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07005520
5521 // If AF trigger is active, insert a dummy AF trigger ID if none already
5522 // exists
5523 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
5524 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
5525 if (afTrigger.count > 0 &&
5526 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
5527 afId.count == 0) {
5528 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
5529 if (res != OK) return res;
5530 }
5531
5532 // If AE precapture trigger is active, insert a dummy precapture trigger ID
5533 // if none already exists
5534 camera_metadata_entry pcTrigger =
5535 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
5536 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
5537 if (pcTrigger.count > 0 &&
5538 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
5539 pcId.count == 0) {
5540 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
5541 &dummyTriggerId, 1);
5542 if (res != OK) return res;
5543 }
5544
5545 return OK;
5546}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005547
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005548/**
5549 * PreparerThread inner class methods
5550 */
5551
5552Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005553 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005554 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005555}
5556
5557Camera3Device::PreparerThread::~PreparerThread() {
5558 Thread::requestExitAndWait();
5559 if (mCurrentStream != nullptr) {
5560 mCurrentStream->cancelPrepare();
5561 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5562 mCurrentStream.clear();
5563 }
5564 clear();
5565}
5566
Ruben Brunkc78ac262015-08-13 17:58:46 -07005567status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005568 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005569 status_t res;
5570
5571 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005572 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005573
Ruben Brunkc78ac262015-08-13 17:58:46 -07005574 res = stream->startPrepare(maxCount);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005575 if (res == OK) {
5576 // No preparation needed, fire listener right off
5577 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005578 if (listener != NULL) {
5579 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005580 }
5581 return OK;
5582 } else if (res != NOT_ENOUGH_DATA) {
5583 return res;
5584 }
5585
5586 // Need to prepare, start up thread if necessary
5587 if (!mActive) {
5588 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
5589 // isn't running
5590 Thread::requestExitAndWait();
5591 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5592 if (res != OK) {
5593 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005594 if (listener != NULL) {
5595 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005596 }
5597 return res;
5598 }
5599 mCancelNow = false;
5600 mActive = true;
5601 ALOGV("%s: Preparer stream started", __FUNCTION__);
5602 }
5603
5604 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005605 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005606 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
5607
5608 return OK;
5609}
5610
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005611void Camera3Device::PreparerThread::pause() {
5612 ATRACE_CALL();
5613
5614 Mutex::Autolock l(mLock);
5615
5616 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
5617 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
5618 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
5619 int currentMaxCount = mCurrentMaxCount;
5620 mPendingStreams.clear();
5621 mCancelNow = true;
5622 while (mActive) {
5623 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
5624 if (res == TIMED_OUT) {
5625 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
5626 return;
5627 } else if (res != OK) {
5628 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
5629 return;
5630 }
5631 }
5632
5633 //Check whether the prepare thread was able to complete the current
5634 //stream. In case work is still pending emplace it along with the rest
5635 //of the streams in the pending list.
5636 if (currentStream != nullptr) {
5637 if (!mCurrentPrepareComplete) {
5638 pendingStreams.emplace(currentMaxCount, currentStream);
5639 }
5640 }
5641
5642 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
5643 for (const auto& it : mPendingStreams) {
5644 it.second->cancelPrepare();
5645 }
5646}
5647
5648status_t Camera3Device::PreparerThread::resume() {
5649 ATRACE_CALL();
5650 status_t res;
5651
5652 Mutex::Autolock l(mLock);
5653 sp<NotificationListener> listener = mListener.promote();
5654
5655 if (mActive) {
5656 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
5657 return NO_INIT;
5658 }
5659
5660 auto it = mPendingStreams.begin();
5661 for (; it != mPendingStreams.end();) {
5662 res = it->second->startPrepare(it->first);
5663 if (res == OK) {
5664 if (listener != NULL) {
5665 listener->notifyPrepared(it->second->getId());
5666 }
5667 it = mPendingStreams.erase(it);
5668 } else if (res != NOT_ENOUGH_DATA) {
5669 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
5670 res, strerror(-res));
5671 it = mPendingStreams.erase(it);
5672 } else {
5673 it++;
5674 }
5675 }
5676
5677 if (mPendingStreams.empty()) {
5678 return OK;
5679 }
5680
5681 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
5682 if (res != OK) {
5683 ALOGE("%s: Unable to start preparer stream: %d (%s)",
5684 __FUNCTION__, res, strerror(-res));
5685 return res;
5686 }
5687 mCancelNow = false;
5688 mActive = true;
5689 ALOGV("%s: Preparer stream started", __FUNCTION__);
5690
5691 return OK;
5692}
5693
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005694status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005695 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005696 Mutex::Autolock l(mLock);
5697
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005698 for (const auto& it : mPendingStreams) {
5699 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005700 }
5701 mPendingStreams.clear();
5702 mCancelNow = true;
5703
5704 return OK;
5705}
5706
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005707void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005708 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005709 Mutex::Autolock l(mLock);
5710 mListener = listener;
5711}
5712
5713bool Camera3Device::PreparerThread::threadLoop() {
5714 status_t res;
5715 {
5716 Mutex::Autolock l(mLock);
5717 if (mCurrentStream == nullptr) {
5718 // End thread if done with work
5719 if (mPendingStreams.empty()) {
5720 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
5721 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
5722 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
5723 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005724 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005725 return false;
5726 }
5727
5728 // Get next stream to prepare
5729 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005730 mCurrentStream = it->second;
5731 mCurrentMaxCount = it->first;
5732 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005733 mPendingStreams.erase(it);
5734 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
5735 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
5736 } else if (mCancelNow) {
5737 mCurrentStream->cancelPrepare();
5738 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5739 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
5740 mCurrentStream.clear();
5741 mCancelNow = false;
5742 return true;
5743 }
5744 }
5745
5746 res = mCurrentStream->prepareNextBuffer();
5747 if (res == NOT_ENOUGH_DATA) return true;
5748 if (res != OK) {
5749 // Something bad happened; try to recover by cancelling prepare and
5750 // signalling listener anyway
5751 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
5752 mCurrentStream->getId(), res, strerror(-res));
5753 mCurrentStream->cancelPrepare();
5754 }
5755
5756 // This stream has finished, notify listener
5757 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005758 sp<NotificationListener> listener = mListener.promote();
5759 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005760 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
5761 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005762 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005763 }
5764
5765 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
5766 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005767 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005768
5769 return true;
5770}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005771
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005772/**
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005773 * Static callback forwarding methods from HAL to instance
5774 */
5775
5776void Camera3Device::sProcessCaptureResult(const camera3_callback_ops *cb,
5777 const camera3_capture_result *result) {
5778 Camera3Device *d =
5779 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
Chien-Yu Chend196d612015-06-22 19:49:01 -07005780
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08005781 d->processCaptureResult(result);
5782}
5783
5784void Camera3Device::sNotify(const camera3_callback_ops *cb,
5785 const camera3_notify_msg *msg) {
5786 Camera3Device *d =
5787 const_cast<Camera3Device*>(static_cast<const Camera3Device*>(cb));
5788 d->notify(msg);
5789}
5790
5791}; // namespace android