blob: 7ff4f18a24da78425dc74e00521a417bd9ea3dfd [file] [log] [blame]
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001/*
Shuzhen Wangc28189a2017-11-27 23:05:10 -08002 * Copyright (C) 2013-2018 The Android Open Source Project
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#define LOG_TAG "Camera3-Device"
18#define ATRACE_TAG ATRACE_TAG_CAMERA
19//#define LOG_NDEBUG 0
20//#define LOG_NNDEBUG 0 // Per-frame verbose logging
21
22#ifdef LOG_NNDEBUG
23#define ALOGVV(...) ALOGV(__VA_ARGS__)
24#else
25#define ALOGVV(...) ((void)0)
26#endif
27
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070028// Convenience macro for transient errors
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080029#define CLOGE(fmt, ...) ALOGE("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070030 ##__VA_ARGS__)
31
32// Convenience macros for transitioning to the error state
33#define SET_ERR(fmt, ...) setErrorState( \
34 "%s: " fmt, __FUNCTION__, \
35 ##__VA_ARGS__)
36#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39
Colin Crosse5729fa2014-03-21 15:04:25 -070040#include <inttypes.h>
41
Shuzhen Wang5c22c152017-12-31 17:12:25 -080042#include <utility>
43
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080044#include <utils/Log.h>
45#include <utils/Trace.h>
46#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070047#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070048
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080049#include <android/hardware/camera2/ICameraDeviceUser.h>
50
Igor Murashkinff3e31d2013-10-23 16:40:06 -070051#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070052#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070053#include "device3/Camera3Device.h"
54#include "device3/Camera3OutputStream.h"
55#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070056#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070057#include "device3/Camera3SharedOutputStream.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070058#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070059#include "utils/CameraThreadState.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080060
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080061#include <tuple>
62
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080063using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080064using namespace android::hardware::camera;
65using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080066
67namespace android {
68
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080069Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080070 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080071 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070072 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070073 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070074 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070075 mUsePartialResult(false),
76 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080077 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070078 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070079 mNextReprocessResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070080 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070081 mNextReprocessShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000082 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010083 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070084 mLastTemplateId(-1),
85 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080086{
87 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080088 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080089}
90
91Camera3Device::~Camera3Device()
92{
93 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080094 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -070095 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080096}
97
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080098const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -080099 return mId;
100}
101
Emilian Peevbd8c5032018-02-14 23:05:40 +0000102status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800103 ATRACE_CALL();
104 Mutex::Autolock il(mInterfaceLock);
105 Mutex::Autolock l(mLock);
106
107 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
108 if (mStatus != STATUS_UNINITIALIZED) {
109 CLOGE("Already initialized!");
110 return INVALID_OPERATION;
111 }
112 if (manager == nullptr) return INVALID_OPERATION;
113
114 sp<ICameraDeviceSession> session;
115 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800116 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800117 /*out*/ &session);
118 ATRACE_END();
119 if (res != OK) {
120 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
121 return res;
122 }
123
Steven Moreland5ff9c912017-03-09 23:13:00 -0800124 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800125 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700126 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800127 session->close();
128 return res;
129 }
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800130
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700131 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700132 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700133 if (isLogical) {
134 for (auto& physicalId : physicalCameraIds) {
135 res = manager->getCameraCharacteristics(physicalId, &mPhysicalDeviceInfoMap[physicalId]);
136 if (res != OK) {
137 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
138 physicalId.c_str(), strerror(-res), res);
139 session->close();
140 return res;
141 }
142 }
143 }
144
Yifan Hongf79b5542017-04-11 14:44:25 -0700145 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700146 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
147 [&queue](const auto& descriptor) {
148 queue = std::make_shared<RequestMetadataQueue>(descriptor);
149 if (!queue->isValid() || queue->availableToWrite() <= 0) {
150 ALOGE("HAL returns empty request metadata fmq, not use it");
151 queue = nullptr;
152 // don't use the queue onwards.
153 }
154 });
155 if (!requestQueueRet.isOk()) {
156 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
157 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700158 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700159 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700160
161 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700162 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700163 [&resQueue](const auto& descriptor) {
164 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
165 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700166 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700167 resQueue = nullptr;
168 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700169 }
170 });
171 if (!resultQueueRet.isOk()) {
172 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
173 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700174 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700175 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700176 IF_ALOGV() {
177 session->interfaceChain([](
178 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
179 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800180 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700181 ALOGV(" %s", iface.c_str());
182 }
183 });
184 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700185
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800186 camera_metadata_entry bufMgrMode =
187 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
188 if (bufMgrMode.count > 0) {
189 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
190 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
191 }
192
193 mInterface = new HalInterface(session, queue, mUseHalBufManager);
Emilian Peev71c73a22017-03-21 16:35:51 +0000194 std::string providerType;
195 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000196 mTagMonitor.initialize(mVendorTagId);
197 if (!monitorTags.isEmpty()) {
198 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
199 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800200
Shuzhen Wang268a1362018-10-16 16:32:59 -0700201 // Metadata tags needs fixup for monochrome camera device version less
202 // than 3.5.
203 hardware::hidl_version maxVersion{0,0};
204 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
205 if (res != OK) {
206 ALOGE("%s: Error in getting camera device version id: %s (%d)",
207 __FUNCTION__, strerror(-res), res);
208 return res;
209 }
210 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
211 maxVersion.get_major(), maxVersion.get_minor());
212
213 bool isMonochrome = false;
214 camera_metadata_entry_t entry = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
215 for (size_t i = 0; i < entry.count; i++) {
216 uint8_t capability = entry.data.u8[i];
217 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
218 isMonochrome = true;
219 }
220 }
221 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
222
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800223 return initializeCommonLocked();
224}
225
226status_t Camera3Device::initializeCommonLocked() {
227
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700228 /** Start up status tracker thread */
229 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800230 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700231 if (res != OK) {
232 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
233 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800234 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700235 mStatusTracker.clear();
236 return res;
237 }
238
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700239 /** Register in-flight map to the status tracker */
240 mInFlightStatusId = mStatusTracker->addComponent();
241
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700242 if (mUseHalBufManager) {
243 res = mRequestBufferSM.initialize(mStatusTracker);
244 if (res != OK) {
245 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
246 strerror(-res), res);
247 mInterface->close();
248 mStatusTracker.clear();
249 return res;
250 }
251 }
252
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800253 /** Create buffer manager */
254 mBufferManager = new Camera3BufferManager();
255
256 Vector<int32_t> sessionParamKeys;
257 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
258 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
259 if (sessionKeysEntry.count > 0) {
260 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
261 }
262
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700263 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700264 mRequestThread = new RequestThread(
265 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800266 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800267 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700268 SET_ERR_L("Unable to start request queue thread: %s (%d)",
269 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800270 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800271 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800272 return res;
273 }
274
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700275 mPreparerThread = new PreparerThread();
276
Ruben Brunk183f0562015-08-12 12:55:02 -0700277 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800278 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700279 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700280 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700281 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800282
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800283 // Measure the clock domain offset between camera and video/hw_composer
284 camera_metadata_entry timestampSource =
285 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
286 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
287 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
288 mTimestampOffset = getMonoToBoottimeOffset();
289 }
290
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700291 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100292 camera_metadata_entry partialResultsCount =
293 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
294 if (partialResultsCount.count > 0) {
295 mNumPartialResults = partialResultsCount.data.i32[0];
296 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700297 }
298
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700299 camera_metadata_entry configs =
300 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
301 for (uint32_t i = 0; i < configs.count; i += 4) {
302 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
303 configs.data.i32[i + 3] ==
304 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
305 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
306 configs.data.i32[i + 2]));
307 }
308 }
309
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700310 if (DistortionMapper::isDistortionSupported(mDeviceInfo)) {
311 res = mDistortionMapper.setupStaticInfo(mDeviceInfo);
312 if (res != OK) {
313 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
314 return res;
315 }
316 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800317 return OK;
318}
319
320status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700321 return disconnectImpl();
322}
323
324status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800325 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700326 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800327
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700328 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800329
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700330 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700331 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700332 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700333 {
334 Mutex::Autolock l(mLock);
335 if (mStatus == STATUS_UNINITIALIZED) return res;
336
337 if (mStatus == STATUS_ACTIVE ||
338 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
339 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700340 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700341 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700342 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700343 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700344 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700345 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700346 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
347 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700348 // Continue to close device even in case of error
349 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700350 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800351 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800352
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700353 if (mStatus == STATUS_ERROR) {
354 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700355 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700356
357 if (mStatusTracker != NULL) {
358 mStatusTracker->requestExit();
359 }
360
361 if (mRequestThread != NULL) {
362 mRequestThread->requestExit();
363 }
364
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700365 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
366 for (size_t i = 0; i < mOutputStreams.size(); i++) {
367 streams.push_back(mOutputStreams[i]);
368 }
369 if (mInputStream != nullptr) {
370 streams.push_back(mInputStream);
371 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700372 }
373
374 // Joining done without holding mLock, otherwise deadlocks may ensue
375 // as the threads try to access parent state
376 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
377 // HAL may be in a bad state, so waiting for request thread
378 // (which may be stuck in the HAL processCaptureRequest call)
379 // could be dangerous.
380 mRequestThread->join();
381 }
382
383 if (mStatusTracker != NULL) {
384 mStatusTracker->join();
385 }
386
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800387 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700388 {
389 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800390 mRequestThread.clear();
Emilian Peev2843c362018-09-26 08:49:40 +0100391 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700392 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800393 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700394 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800395
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700396 // Call close without internal mutex held, as the HAL close may need to
397 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800398 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700399
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700400 flushInflightRequests();
401
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700402 {
403 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800404 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700405 mOutputStreams.clear();
406 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700407 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700408 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700409 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700410 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800411
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700412 for (auto& weakStream : streams) {
413 sp<Camera3StreamInterface> stream = weakStream.promote();
414 if (stream != nullptr) {
415 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
416 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
417 }
418 }
419
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700420 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700421 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800422}
423
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700424// For dumping/debugging only -
425// try to acquire a lock a few times, eventually give up to proceed with
426// debug/dump operations
427bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
428 bool gotLock = false;
429 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
430 if (lock.tryLock() == NO_ERROR) {
431 gotLock = true;
432 break;
433 } else {
434 usleep(kDumpSleepDuration);
435 }
436 }
437 return gotLock;
438}
439
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700440Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
441 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100442 const int STREAM_CONFIGURATION_SIZE = 4;
443 const int STREAM_FORMAT_OFFSET = 0;
444 const int STREAM_WIDTH_OFFSET = 1;
445 const int STREAM_HEIGHT_OFFSET = 2;
446 const int STREAM_IS_INPUT_OFFSET = 3;
447 camera_metadata_ro_entry_t availableStreamConfigs =
448 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
449 if (availableStreamConfigs.count == 0 ||
450 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
451 return Size(0, 0);
452 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700453
Emilian Peev08dd2452017-04-06 16:55:14 +0100454 // Get max jpeg size (area-wise).
455 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
456 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
457 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
458 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
459 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
460 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
461 && format == HAL_PIXEL_FORMAT_BLOB &&
462 (width * height > maxJpegWidth * maxJpegHeight)) {
463 maxJpegWidth = width;
464 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700465 }
466 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100467
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700468 return Size(maxJpegWidth, maxJpegHeight);
469}
470
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800471nsecs_t Camera3Device::getMonoToBoottimeOffset() {
472 // try three times to get the clock offset, choose the one
473 // with the minimum gap in measurements.
474 const int tries = 3;
475 nsecs_t bestGap, measured;
476 for (int i = 0; i < tries; ++i) {
477 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
478 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
479 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
480 const nsecs_t gap = tmono2 - tmono;
481 if (i == 0 || gap < bestGap) {
482 bestGap = gap;
483 measured = tbase - ((tmono + tmono2) >> 1);
484 }
485 }
486 return measured;
487}
488
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800489hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
490 int frameworkFormat) {
491 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
492}
493
494DataspaceFlags Camera3Device::mapToHidlDataspace(
495 android_dataspace dataSpace) {
496 return dataSpace;
497}
498
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700499BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100500 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700501 return usage;
502}
503
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800504StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
505 switch (rotation) {
506 case CAMERA3_STREAM_ROTATION_0:
507 return StreamRotation::ROTATION_0;
508 case CAMERA3_STREAM_ROTATION_90:
509 return StreamRotation::ROTATION_90;
510 case CAMERA3_STREAM_ROTATION_180:
511 return StreamRotation::ROTATION_180;
512 case CAMERA3_STREAM_ROTATION_270:
513 return StreamRotation::ROTATION_270;
514 }
515 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
516 return StreamRotation::ROTATION_0;
517}
518
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800519status_t Camera3Device::mapToStreamConfigurationMode(
520 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
521 if (mode == nullptr) return BAD_VALUE;
522 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
523 switch(operationMode) {
524 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
525 *mode = StreamConfigurationMode::NORMAL_MODE;
526 break;
527 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
528 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
529 break;
530 default:
531 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
532 return BAD_VALUE;
533 }
534 } else {
535 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800536 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800537 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800538}
539
540camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
541 switch (status) {
542 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
543 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
544 }
545 return CAMERA3_BUFFER_STATUS_ERROR;
546}
547
548int Camera3Device::mapToFrameworkFormat(
549 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
550 return static_cast<uint32_t>(pixelFormat);
551}
552
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700553android_dataspace Camera3Device::mapToFrameworkDataspace(
554 DataspaceFlags dataSpace) {
555 return static_cast<android_dataspace>(dataSpace);
556}
557
Emilian Peev050f5dc2017-05-18 14:43:56 +0100558uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700559 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700560 return usage;
561}
562
Emilian Peev050f5dc2017-05-18 14:43:56 +0100563uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700564 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700565 return usage;
566}
567
Zhijun Hef7da0962014-04-24 13:27:56 -0700568ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700569 // Get max jpeg size (area-wise).
570 Size maxJpegResolution = getMaxJpegResolution();
571 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800572 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
573 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700574 return BAD_VALUE;
575 }
576
Zhijun Hef7da0962014-04-24 13:27:56 -0700577 // Get max jpeg buffer size
578 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700579 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
580 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800581 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
582 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700583 return BAD_VALUE;
584 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700585 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800586 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700587
588 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700589 float scaleFactor = ((float) (width * height)) /
590 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800591 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
592 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700593 if (jpegBufferSize > maxJpegBufferSize) {
594 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700595 }
596
597 return jpegBufferSize;
598}
599
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700600ssize_t Camera3Device::getPointCloudBufferSize() const {
601 const int FLOATS_PER_POINT=4;
602 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
603 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800604 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
605 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700606 return BAD_VALUE;
607 }
608 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
609 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
610 return maxBytesForPointCloud;
611}
612
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800613ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800614 const int PER_CONFIGURATION_SIZE = 3;
615 const int WIDTH_OFFSET = 0;
616 const int HEIGHT_OFFSET = 1;
617 const int SIZE_OFFSET = 2;
618 camera_metadata_ro_entry rawOpaqueSizes =
619 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800620 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800621 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800622 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
623 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800624 return BAD_VALUE;
625 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700626
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800627 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
628 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
629 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
630 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
631 }
632 }
633
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800634 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
635 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800636 return BAD_VALUE;
637}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700638
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800639status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
640 ATRACE_CALL();
641 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700642
643 // Try to lock, but continue in case of failure (to avoid blocking in
644 // deadlocks)
645 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
646 bool gotLock = tryLockSpinRightRound(mLock);
647
648 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800649 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
650 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700651 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800652 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
653 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700654
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800655 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700656
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800657 String16 templatesOption("-t");
658 int n = args.size();
659 for (int i = 0; i < n; i++) {
660 if (args[i] == templatesOption) {
661 dumpTemplates = true;
662 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000663 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700664 if (i + 1 < n) {
665 String8 monitorTags = String8(args[i + 1]);
666 if (monitorTags == "off") {
667 mTagMonitor.disableMonitoring();
668 } else {
669 mTagMonitor.parseTagsToMonitor(monitorTags);
670 }
671 } else {
672 mTagMonitor.disableMonitoring();
673 }
674 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800675 }
676
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800677 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800678
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800679 const char *status =
680 mStatus == STATUS_ERROR ? "ERROR" :
681 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700682 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
683 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800684 mStatus == STATUS_ACTIVE ? "ACTIVE" :
685 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700686
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800687 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700688 if (mStatus == STATUS_ERROR) {
689 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
690 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800691 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800692 const char *mode =
693 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
694 mOperatingMode == static_cast<int>(
695 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
696 "CUSTOM";
697 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800698
699 if (mInputStream != NULL) {
700 write(fd, lines.string(), lines.size());
701 mInputStream->dump(fd, args);
702 } else {
703 lines.appendFormat(" No input stream.\n");
704 write(fd, lines.string(), lines.size());
705 }
706 for (size_t i = 0; i < mOutputStreams.size(); i++) {
707 mOutputStreams[i]->dump(fd,args);
708 }
709
Zhijun He431503c2016-03-07 17:30:16 -0800710 if (mBufferManager != NULL) {
711 lines = String8(" Camera3 Buffer Manager:\n");
712 write(fd, lines.string(), lines.size());
713 mBufferManager->dump(fd, args);
714 }
Zhijun He125684a2015-12-26 15:07:30 -0800715
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700716 lines = String8(" In-flight requests:\n");
717 if (mInFlightMap.size() == 0) {
718 lines.append(" None\n");
719 } else {
720 for (size_t i = 0; i < mInFlightMap.size(); i++) {
721 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700722 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700723 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800724 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700725 r.numBuffersLeft);
726 }
727 }
728 write(fd, lines.string(), lines.size());
729
Shuzhen Wang686f6442017-06-20 16:16:04 -0700730 if (mRequestThread != NULL) {
731 mRequestThread->dumpCaptureRequestLatency(fd,
732 " ProcessCaptureRequest latency histogram:");
733 }
734
Igor Murashkin1e479c02013-09-06 16:55:14 -0700735 {
736 lines = String8(" Last request sent:\n");
737 write(fd, lines.string(), lines.size());
738
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700739 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700740 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
741 }
742
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800743 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800744 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800745 "TEMPLATE_PREVIEW",
746 "TEMPLATE_STILL_CAPTURE",
747 "TEMPLATE_VIDEO_RECORD",
748 "TEMPLATE_VIDEO_SNAPSHOT",
749 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800750 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800751 };
752
753 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800754 camera_metadata_t *templateRequest = nullptr;
755 mInterface->constructDefaultRequestSettings(
756 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800757 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800758 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800759 lines.append(" Not supported\n");
760 write(fd, lines.string(), lines.size());
761 } else {
762 write(fd, lines.string(), lines.size());
763 dump_indented_camera_metadata(templateRequest,
764 fd, /*verbosity*/2, /*indentation*/8);
765 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800766 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800767 }
768 }
769
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700770 mTagMonitor.dumpMonitoredMetadata(fd);
771
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800772 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800773 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800774 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800775 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800776 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800777
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700778 if (gotLock) mLock.unlock();
779 if (gotInterfaceLock) mInterfaceLock.unlock();
780
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800781 return OK;
782}
783
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700784const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800785 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800786 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
787 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700788 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800789 mStatus == STATUS_ERROR ?
790 "when in error state" : "before init");
791 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700792 if (physicalId.isEmpty()) {
793 return mDeviceInfo;
794 } else {
795 std::string id(physicalId.c_str());
796 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
797 return mPhysicalDeviceInfoMap.at(id);
798 } else {
799 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
800 return mDeviceInfo;
801 }
802 }
803}
804
805const CameraMetadata& Camera3Device::info() const {
806 String8 emptyId;
807 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800808}
809
Jianing Wei90e59c92014-03-12 18:29:36 -0700810status_t Camera3Device::checkStatusOkToCaptureLocked() {
811 switch (mStatus) {
812 case STATUS_ERROR:
813 CLOGE("Device has encountered a serious error");
814 return INVALID_OPERATION;
815 case STATUS_UNINITIALIZED:
816 CLOGE("Device not initialized");
817 return INVALID_OPERATION;
818 case STATUS_UNCONFIGURED:
819 case STATUS_CONFIGURED:
820 case STATUS_ACTIVE:
821 // OK
822 break;
823 default:
824 SET_ERR_L("Unexpected status: %d", mStatus);
825 return INVALID_OPERATION;
826 }
827 return OK;
828}
829
830status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000831 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700832 const std::list<const SurfaceMap> &surfaceMaps,
833 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700834 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700835 if (requestList == NULL) {
836 CLOGE("requestList cannot be NULL.");
837 return BAD_VALUE;
838 }
839
Jianing Weicb0652e2014-03-12 18:29:36 -0700840 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000841 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700842 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
843 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
844 ++metadataIt, ++surfaceMapIt) {
845 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700846 if (newRequest == 0) {
847 CLOGE("Can't create capture request");
848 return BAD_VALUE;
849 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700850
Shuzhen Wang9d066012016-09-30 11:30:20 -0700851 newRequest->mRepeating = repeating;
852
Jianing Weicb0652e2014-03-12 18:29:36 -0700853 // Setup burst Id and request Id
854 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000855 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
856 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700857 CLOGE("RequestID entry exists; but must not be empty in metadata");
858 return BAD_VALUE;
859 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000860 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
861 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700862 } else {
863 CLOGE("RequestID does not exist in metadata");
864 return BAD_VALUE;
865 }
866
Jianing Wei90e59c92014-03-12 18:29:36 -0700867 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700868
869 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700870 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700871 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
872 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
873 return BAD_VALUE;
874 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700875
876 // Setup batch size if this is a high speed video recording request.
877 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
878 auto firstRequest = requestList->begin();
879 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
880 if (outputStream->isVideoStream()) {
881 (*firstRequest)->mBatchSize = requestList->size();
882 break;
883 }
884 }
885 }
886
Jianing Wei90e59c92014-03-12 18:29:36 -0700887 return OK;
888}
889
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800890status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800891 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800892
Emilian Peevaebbe412018-01-15 13:53:24 +0000893 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700894 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000895 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700896
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800897 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700898}
899
Emilian Peevaebbe412018-01-15 13:53:24 +0000900void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700901 std::list<const SurfaceMap>& surfaceMaps,
902 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000903 PhysicalCameraSettingsList requestList;
904 requestList.push_back({std::string(getId().string()), request});
905 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700906
907 SurfaceMap surfaceMap;
908 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
909 // With no surface list passed in, stream and surface will have 1-to-1
910 // mapping. So the surface index is 0 for each stream in the surfaceMap.
911 for (size_t i = 0; i < streams.count; i++) {
912 surfaceMap[streams.data.i32[i]].push_back(0);
913 }
914 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800915}
916
Jianing Wei90e59c92014-03-12 18:29:36 -0700917status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000918 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700919 const std::list<const SurfaceMap> &surfaceMaps,
920 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700921 /*out*/
922 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700923 ATRACE_CALL();
924 Mutex::Autolock il(mInterfaceLock);
925 Mutex::Autolock l(mLock);
926
927 status_t res = checkStatusOkToCaptureLocked();
928 if (res != OK) {
929 // error logged by previous call
930 return res;
931 }
932
933 RequestList requestList;
934
Shuzhen Wang0129d522016-10-30 22:43:41 -0700935 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
936 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700937 if (res != OK) {
938 // error logged by previous call
939 return res;
940 }
941
942 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700943 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700944 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700945 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700946 }
947
948 if (res == OK) {
949 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
950 if (res != OK) {
951 SET_ERR_L("Can't transition to active in %f seconds!",
952 kActiveTimeout/1e9);
953 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800954 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700955 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700956 } else {
957 CLOGE("Cannot queue request. Impossible.");
958 return BAD_VALUE;
959 }
960
961 return res;
962}
963
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700964hardware::Return<void> Camera3Device::requestStreamBuffers(
965 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
966 requestStreamBuffers_cb _hidl_cb) {
967 using hardware::camera::device::V3_5::BufferRequestStatus;
968 using hardware::camera::device::V3_5::StreamBufferRet;
969 using hardware::camera::device::V3_5::StreamBufferRequestError;
970
971 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
972
973 hardware::hidl_vec<StreamBufferRet> bufRets;
974 if (!mUseHalBufManager) {
975 ALOGE("%s: Camera %s does not support HAL buffer management",
976 __FUNCTION__, mId.string());
977 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
978 return hardware::Void();
979 }
980
981 SortedVector<int32_t> streamIds;
982 ssize_t sz = streamIds.setCapacity(bufReqs.size());
983 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
984 ALOGE("%s: failed to allocate memory for %zu buffer requests",
985 __FUNCTION__, bufReqs.size());
986 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
987 return hardware::Void();
988 }
989
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700990 if (bufReqs.size() > mOutputStreams.size()) {
991 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
992 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
993 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
994 return hardware::Void();
995 }
996
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700997 // Check for repeated streamId
998 for (const auto& bufReq : bufReqs) {
999 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
1000 ALOGE("%s: Stream %d appear multiple times in buffer requests",
1001 __FUNCTION__, bufReq.streamId);
1002 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1003 return hardware::Void();
1004 }
1005 streamIds.add(bufReq.streamId);
1006 }
1007
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001008 if (!mRequestBufferSM.startRequestBuffer()) {
1009 ALOGE("%s: request buffer disallowed while camera service is configuring",
1010 __FUNCTION__);
1011 _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001012 return hardware::Void();
1013 }
1014
1015 bufRets.resize(bufReqs.size());
1016
1017 bool allReqsSucceeds = true;
1018 bool oneReqSucceeds = false;
1019 for (size_t i = 0; i < bufReqs.size(); i++) {
1020 const auto& bufReq = bufReqs[i];
1021 auto& bufRet = bufRets[i];
1022 int32_t streamId = bufReq.streamId;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001023 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
1024 if (outputStream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001025 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
1026 hardware::hidl_vec<StreamBufferRet> emptyBufRets;
1027 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001028 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001029 return hardware::Void();
1030 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001031
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001032 if (outputStream->isAbandoned()) {
1033 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1034 allReqsSucceeds = false;
1035 continue;
1036 }
1037
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001038 bufRet.streamId = streamId;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001039 size_t handOutBufferCount = outputStream->getOutstandingBuffersCount();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001040 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001041 size_t totalHandout = handOutBufferCount + numBuffersRequested;
1042 uint32_t maxBuffers = outputStream->asHalStream()->max_buffers;
1043 if (totalHandout > maxBuffers) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001044 // Not able to allocate enough buffer. Exit early for this stream
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001045 ALOGE("%s: request too much buffers for stream %d: at HAL: %zu + requesting: %d"
1046 " > max: %d", __FUNCTION__, streamId, handOutBufferCount,
1047 numBuffersRequested, maxBuffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001048 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1049 allReqsSucceeds = false;
1050 continue;
1051 }
1052
1053 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1054 bool currentReqSucceeds = true;
1055 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1056 size_t numAllocatedBuffers = 0;
1057 size_t numPushedInflightBuffers = 0;
1058 for (size_t b = 0; b < numBuffersRequested; b++) {
1059 camera3_stream_buffer_t& sb = streamBuffers[b];
1060 // Since this method can run concurrently with request thread
1061 // We need to update the wait duration everytime we call getbuffer
1062 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1063 status_t res = outputStream->getBuffer(&sb, waitDuration);
1064 if (res != OK) {
1065 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1066 __FUNCTION__, streamId, strerror(-res), res);
1067 if (res == NO_INIT || res == DEAD_OBJECT) {
1068 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1069 } else if (res == TIMED_OUT || res == NO_MEMORY) {
1070 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1071 } else {
1072 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1073 }
1074 currentReqSucceeds = false;
1075 break;
1076 }
1077 numAllocatedBuffers++;
1078
1079 buffer_handle_t *buffer = sb.buffer;
1080 auto pair = mInterface->getBufferId(*buffer, streamId);
1081 bool isNewBuffer = pair.first;
1082 uint64_t bufferId = pair.second;
1083 StreamBuffer& hBuf = tmpRetBuffers[b];
1084
1085 hBuf.streamId = streamId;
1086 hBuf.bufferId = bufferId;
1087 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1088 hBuf.status = BufferStatus::OK;
1089 hBuf.releaseFence = nullptr;
1090
1091 native_handle_t *acquireFence = nullptr;
1092 if (sb.acquire_fence != -1) {
1093 acquireFence = native_handle_create(1,0);
1094 acquireFence->data[0] = sb.acquire_fence;
1095 }
1096 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1097 hBuf.releaseFence = nullptr;
1098
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08001099 res = mInterface->pushInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001100 if (res != OK) {
1101 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1102 __FUNCTION__, streamId, strerror(-res), res);
1103 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1104 currentReqSucceeds = false;
1105 break;
1106 }
1107 numPushedInflightBuffers++;
1108 }
1109 if (currentReqSucceeds) {
1110 bufRet.val.buffers(std::move(tmpRetBuffers));
1111 oneReqSucceeds = true;
1112 } else {
1113 allReqsSucceeds = false;
1114 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1115 StreamBuffer& hBuf = tmpRetBuffers[b];
1116 buffer_handle_t* buffer;
1117 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1118 if (res != OK) {
1119 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1120 __FUNCTION__, streamId, strerror(-res), res);
1121 }
1122 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001123 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1124 camera3_stream_buffer_t& sb = streamBuffers[b];
1125 sb.acquire_fence = -1;
1126 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1127 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001128 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1129 }
1130 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001131
1132 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1133 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1134 BufferRequestStatus::FAILED_UNKNOWN,
1135 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001136 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001137 return hardware::Void();
1138}
1139
1140hardware::Return<void> Camera3Device::returnStreamBuffers(
1141 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1142 if (!mUseHalBufManager) {
1143 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1144 __FUNCTION__, mId.string());
1145 return hardware::Void();
1146 }
1147
1148 for (const auto& buf : buffers) {
1149 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1150 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1151 continue;
1152 }
1153
1154 buffer_handle_t* buffer;
1155 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1156
1157 if (res != OK) {
1158 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1159 __FUNCTION__, buf.bufferId, buf.streamId);
1160 continue;
1161 }
1162
1163 camera3_stream_buffer_t streamBuffer;
1164 streamBuffer.buffer = buffer;
1165 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1166 streamBuffer.acquire_fence = -1;
1167 streamBuffer.release_fence = -1;
1168
1169 if (buf.releaseFence == nullptr) {
1170 streamBuffer.release_fence = -1;
1171 } else if (buf.releaseFence->numFds == 1) {
1172 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1173 } else {
1174 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1175 __FUNCTION__, buf.releaseFence->numFds);
1176 continue;
1177 }
1178
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001179 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1180 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001181 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1182 continue;
1183 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001184 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001185 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1186 }
1187 return hardware::Void();
1188}
1189
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001190hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001191 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001192 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001193 // Ideally we should grab mLock, but that can lead to deadlock, and
1194 // it's not super important to get up to date value of mStatus for this
1195 // warning print, hence skipping the lock here
1196 if (mStatus == STATUS_ERROR) {
1197 // Per API contract, HAL should act as closed after device error
1198 // But mStatus can be set to error by framework as well, so just log
1199 // a warning here.
1200 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001201 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001202
1203 if (mProcessCaptureResultLock.tryLock() != OK) {
1204 // This should never happen; it indicates a wrong client implementation
1205 // that doesn't follow the contract. But, we can be tolerant here.
1206 ALOGE("%s: callback overlapped! waiting 1s...",
1207 __FUNCTION__);
1208 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1209 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1210 __FUNCTION__);
1211 // really don't know what to do, so bail out.
1212 return hardware::Void();
1213 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001214 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001215 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001216 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001217 }
1218 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001219 return hardware::Void();
1220}
1221
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001222// Only one processCaptureResult should be called at a time, so
1223// the locks won't block. The locks are present here simply to enforce this.
1224hardware::Return<void> Camera3Device::processCaptureResult(
1225 const hardware::hidl_vec<
1226 hardware::camera::device::V3_2::CaptureResult>& results) {
1227 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1228
1229 // Ideally we should grab mLock, but that can lead to deadlock, and
1230 // it's not super important to get up to date value of mStatus for this
1231 // warning print, hence skipping the lock here
1232 if (mStatus == STATUS_ERROR) {
1233 // Per API contract, HAL should act as closed after device error
1234 // But mStatus can be set to error by framework as well, so just log
1235 // a warning here.
1236 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1237 }
1238
1239 if (mProcessCaptureResultLock.tryLock() != OK) {
1240 // This should never happen; it indicates a wrong client implementation
1241 // that doesn't follow the contract. But, we can be tolerant here.
1242 ALOGE("%s: callback overlapped! waiting 1s...",
1243 __FUNCTION__);
1244 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1245 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1246 __FUNCTION__);
1247 // really don't know what to do, so bail out.
1248 return hardware::Void();
1249 }
1250 }
1251 for (const auto& result : results) {
1252 processOneCaptureResultLocked(result, noPhysMetadata);
1253 }
1254 mProcessCaptureResultLock.unlock();
1255 return hardware::Void();
1256}
1257
1258status_t Camera3Device::readOneCameraMetadataLocked(
1259 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1260 const hardware::camera::device::V3_2::CameraMetadata& result) {
1261 if (fmqResultSize > 0) {
1262 resultMetadata.resize(fmqResultSize);
1263 if (mResultMetadataQueue == nullptr) {
1264 return NO_MEMORY; // logged in initialize()
1265 }
1266 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1267 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1268 __FUNCTION__, fmqResultSize);
1269 return INVALID_OPERATION;
1270 }
1271 } else {
1272 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1273 result.size());
1274 }
1275
1276 if (resultMetadata.size() != 0) {
1277 status_t res;
1278 const camera_metadata_t* metadata =
1279 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1280 size_t expected_metadata_size = resultMetadata.size();
1281 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1282 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1283 __FUNCTION__, strerror(-res), res);
1284 return INVALID_OPERATION;
1285 }
1286 }
1287
1288 return OK;
1289}
1290
Yifan Honga640c5a2017-04-12 16:30:31 -07001291void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001292 const hardware::camera::device::V3_2::CaptureResult& result,
1293 const hardware::hidl_vec<
1294 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001295 camera3_capture_result r;
1296 status_t res;
1297 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001298
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001299 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001300 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001301 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1302 if (res != OK) {
1303 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1304 __FUNCTION__, result.frameNumber);
1305 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001306 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001307 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001308
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001309 // Read and validate physical camera metadata
1310 size_t physResultCount = physicalCameraMetadatas.size();
1311 std::vector<const char*> physCamIds(physResultCount);
1312 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1313 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1314 physResultMetadata.resize(physResultCount);
1315 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1316 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1317 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1318 if (res != OK) {
1319 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1320 __FUNCTION__, result.frameNumber,
1321 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001322 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001323 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001324 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1325 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1326 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001327 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001328 r.num_physcam_metadata = physResultCount;
1329 r.physcam_ids = physCamIds.data();
1330 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001331
1332 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1333 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1334 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1335 auto& bDst = outputBuffers[i];
1336 const StreamBuffer &bSrc = result.outputBuffers[i];
1337
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001338 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1339 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001340 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1341 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001342 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001343 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001344 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001345
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001346 bool noBufferReturned = false;
1347 buffer_handle_t *buffer = nullptr;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001348 if (mUseHalBufManager) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001349 // This is suspicious most of the time but can be correct during flush where HAL
1350 // has to return capture result before a buffer is requested
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001351 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001352 if (bSrc.status == BufferStatus::OK) {
1353 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1354 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1355 // Still proceeds so other buffers can be returned
1356 }
1357 noBufferReturned = true;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001358 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001359 if (noBufferReturned) {
1360 res = OK;
1361 } else {
1362 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1363 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001364 } else {
1365 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1366 }
1367
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001368 if (res != OK) {
1369 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1370 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001371 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001372 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001373
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001374 bDst.buffer = buffer;
1375 bDst.status = mapHidlBufferStatus(bSrc.status);
1376 bDst.acquire_fence = -1;
1377 if (bSrc.releaseFence == nullptr) {
1378 bDst.release_fence = -1;
1379 } else if (bSrc.releaseFence->numFds == 1) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001380 if (noBufferReturned) {
1381 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
1382 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001383 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1384 } else {
1385 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1386 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001387 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001388 }
1389 }
1390 r.num_output_buffers = outputBuffers.size();
1391 r.output_buffers = outputBuffers.data();
1392
1393 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001394 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001395 r.input_buffer = nullptr;
1396 } else {
1397 if (mInputStream->getId() != result.inputBuffer.streamId) {
1398 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1399 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001400 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001401 }
1402 inputBuffer.stream = mInputStream->asHalStream();
1403 buffer_handle_t *buffer;
1404 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1405 &buffer);
1406 if (res != OK) {
1407 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1408 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001409 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001410 }
1411 inputBuffer.buffer = buffer;
1412 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1413 inputBuffer.acquire_fence = -1;
1414 if (result.inputBuffer.releaseFence == nullptr) {
1415 inputBuffer.release_fence = -1;
1416 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1417 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1418 } else {
1419 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1420 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001421 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001422 }
1423 r.input_buffer = &inputBuffer;
1424 }
1425
1426 r.partial_result = result.partialResult;
1427
1428 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001429}
1430
1431hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001432 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001433 // Ideally we should grab mLock, but that can lead to deadlock, and
1434 // it's not super important to get up to date value of mStatus for this
1435 // warning print, hence skipping the lock here
1436 if (mStatus == STATUS_ERROR) {
1437 // Per API contract, HAL should act as closed after device error
1438 // But mStatus can be set to error by framework as well, so just log
1439 // a warning here.
1440 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001441 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001442
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001443 for (const auto& msg : msgs) {
1444 notify(msg);
1445 }
1446 return hardware::Void();
1447}
1448
1449void Camera3Device::notify(
1450 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1451
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001452 camera3_notify_msg m;
1453 switch (msg.type) {
1454 case MsgType::ERROR:
1455 m.type = CAMERA3_MSG_ERROR;
1456 m.message.error.frame_number = msg.msg.error.frameNumber;
1457 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001458 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1459 if (stream == nullptr) {
1460 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1461 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001462 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001463 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001464 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001465 } else {
1466 m.message.error.error_stream = nullptr;
1467 }
1468 switch (msg.msg.error.errorCode) {
1469 case ErrorCode::ERROR_DEVICE:
1470 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1471 break;
1472 case ErrorCode::ERROR_REQUEST:
1473 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1474 break;
1475 case ErrorCode::ERROR_RESULT:
1476 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1477 break;
1478 case ErrorCode::ERROR_BUFFER:
1479 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1480 break;
1481 }
1482 break;
1483 case MsgType::SHUTTER:
1484 m.type = CAMERA3_MSG_SHUTTER;
1485 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1486 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1487 break;
1488 }
1489 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001490}
1491
Emilian Peevaebbe412018-01-15 13:53:24 +00001492status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001493 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001494 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001495 ATRACE_CALL();
1496
Emilian Peevaebbe412018-01-15 13:53:24 +00001497 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001498}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001499
Jianing Weicb0652e2014-03-12 18:29:36 -07001500status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1501 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001502 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001503
Emilian Peevaebbe412018-01-15 13:53:24 +00001504 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001505 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001506 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001507
Emilian Peevaebbe412018-01-15 13:53:24 +00001508 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001509 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001510}
1511
Emilian Peevaebbe412018-01-15 13:53:24 +00001512status_t Camera3Device::setStreamingRequestList(
1513 const List<const PhysicalCameraSettingsList> &requestsList,
1514 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001515 ATRACE_CALL();
1516
Emilian Peevaebbe412018-01-15 13:53:24 +00001517 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001518}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001519
1520sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001521 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001522 status_t res;
1523
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001524 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001525 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1526 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001527 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1528 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001529 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001530 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001531 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001532 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001533 } else if (mStatus == STATUS_UNCONFIGURED) {
1534 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001535 CLOGE("No streams configured");
1536 return NULL;
1537 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001538 }
1539
Shuzhen Wang0129d522016-10-30 22:43:41 -07001540 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001541 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001542}
1543
Jianing Weicb0652e2014-03-12 18:29:36 -07001544status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001545 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001546 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001547 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001548
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001549 switch (mStatus) {
1550 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001551 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001552 return INVALID_OPERATION;
1553 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001554 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001555 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001556 case STATUS_UNCONFIGURED:
1557 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001558 case STATUS_ACTIVE:
1559 // OK
1560 break;
1561 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001562 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001563 return INVALID_OPERATION;
1564 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001565 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001566
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001567 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001568}
1569
1570status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1571 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001572 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001573
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001574 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001575}
1576
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001577status_t Camera3Device::createInputStream(
1578 uint32_t width, uint32_t height, int format, int *id) {
1579 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001580 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001581 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001582 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001583 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1584 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001585
1586 status_t res;
1587 bool wasActive = false;
1588
1589 switch (mStatus) {
1590 case STATUS_ERROR:
1591 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1592 return INVALID_OPERATION;
1593 case STATUS_UNINITIALIZED:
1594 ALOGE("%s: Device not initialized", __FUNCTION__);
1595 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001596 case STATUS_UNCONFIGURED:
1597 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001598 // OK
1599 break;
1600 case STATUS_ACTIVE:
1601 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001602 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001603 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001604 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001605 return res;
1606 }
1607 wasActive = true;
1608 break;
1609 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001610 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001611 return INVALID_OPERATION;
1612 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001613 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001614
1615 if (mInputStream != 0) {
1616 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1617 return INVALID_OPERATION;
1618 }
1619
1620 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1621 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001622 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001623
1624 mInputStream = newStream;
1625
1626 *id = mNextStreamId++;
1627
1628 // Continue captures if active at start
1629 if (wasActive) {
1630 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001631 // Reuse current operating mode and session parameters for new stream config
1632 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001633 if (res != OK) {
1634 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1635 __FUNCTION__, mNextStreamId, strerror(-res), res);
1636 return res;
1637 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001638 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001639 }
1640
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001641 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001642 return OK;
1643}
1644
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001645status_t Camera3Device::StreamSet::add(
1646 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1647 if (stream == nullptr) {
1648 ALOGE("%s: cannot add null stream", __FUNCTION__);
1649 return BAD_VALUE;
1650 }
1651 std::lock_guard<std::mutex> lock(mLock);
1652 return mData.add(streamId, stream);
1653}
1654
1655ssize_t Camera3Device::StreamSet::remove(int streamId) {
1656 std::lock_guard<std::mutex> lock(mLock);
1657 return mData.removeItem(streamId);
1658}
1659
1660sp<camera3::Camera3OutputStreamInterface>
1661Camera3Device::StreamSet::get(int streamId) {
1662 std::lock_guard<std::mutex> lock(mLock);
1663 ssize_t idx = mData.indexOfKey(streamId);
1664 if (idx == NAME_NOT_FOUND) {
1665 return nullptr;
1666 }
1667 return mData.editValueAt(idx);
1668}
1669
1670sp<camera3::Camera3OutputStreamInterface>
1671Camera3Device::StreamSet::operator[] (size_t index) {
1672 std::lock_guard<std::mutex> lock(mLock);
1673 return mData.editValueAt(index);
1674}
1675
1676size_t Camera3Device::StreamSet::size() const {
1677 std::lock_guard<std::mutex> lock(mLock);
1678 return mData.size();
1679}
1680
1681void Camera3Device::StreamSet::clear() {
1682 std::lock_guard<std::mutex> lock(mLock);
1683 return mData.clear();
1684}
1685
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001686std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1687 std::lock_guard<std::mutex> lock(mLock);
1688 std::vector<int> streamIds(mData.size());
1689 for (size_t i = 0; i < mData.size(); i++) {
1690 streamIds[i] = mData.keyAt(i);
1691 }
1692 return streamIds;
1693}
1694
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001695status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001696 uint32_t width, uint32_t height, int format,
1697 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001698 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001699 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001700 ATRACE_CALL();
1701
1702 if (consumer == nullptr) {
1703 ALOGE("%s: consumer must not be null", __FUNCTION__);
1704 return BAD_VALUE;
1705 }
1706
1707 std::vector<sp<Surface>> consumers;
1708 consumers.push_back(consumer);
1709
1710 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001711 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1712 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001713}
1714
1715status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1716 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1717 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001718 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001719 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001720 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001721
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001722 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001723 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001724 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001725 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001726 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1727 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1728 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001729
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001730 status_t res;
1731 bool wasActive = false;
1732
1733 switch (mStatus) {
1734 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001735 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001736 return INVALID_OPERATION;
1737 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001738 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001739 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001740 case STATUS_UNCONFIGURED:
1741 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001742 // OK
1743 break;
1744 case STATUS_ACTIVE:
1745 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001746 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001747 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001748 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001749 return res;
1750 }
1751 wasActive = true;
1752 break;
1753 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001754 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001755 return INVALID_OPERATION;
1756 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001757 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001758
1759 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001760
Shuzhen Wang0129d522016-10-30 22:43:41 -07001761 if (consumers.size() == 0 && !hasDeferredConsumer) {
1762 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1763 return BAD_VALUE;
1764 }
Zhijun He5d677d12016-05-29 16:52:39 -07001765
Shuzhen Wang0129d522016-10-30 22:43:41 -07001766 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001767 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1768 return BAD_VALUE;
1769 }
1770
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001771 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001772 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001773 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001774 blobBufferSize = getPointCloudBufferSize();
1775 if (blobBufferSize <= 0) {
1776 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1777 return BAD_VALUE;
1778 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001779 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1780 blobBufferSize = width * height;
1781 } else {
1782 blobBufferSize = getJpegBufferSize(width, height);
1783 if (blobBufferSize <= 0) {
1784 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1785 return BAD_VALUE;
1786 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001787 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001788 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001789 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001790 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001791 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1792 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1793 if (rawOpaqueBufferSize <= 0) {
1794 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1795 return BAD_VALUE;
1796 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001797 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001798 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001799 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001800 } else if (isShared) {
1801 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1802 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001803 mTimestampOffset, physicalCameraId, streamSetId,
1804 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001805 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001806 newStream = new Camera3OutputStream(mNextStreamId,
1807 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001808 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001809 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001810 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001811 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001812 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001813 }
Emilian Peev40ead602017-09-26 15:46:36 +01001814
1815 size_t consumerCount = consumers.size();
1816 for (size_t i = 0; i < consumerCount; i++) {
1817 int id = newStream->getSurfaceId(consumers[i]);
1818 if (id < 0) {
1819 SET_ERR_L("Invalid surface id");
1820 return BAD_VALUE;
1821 }
1822 if (surfaceIds != nullptr) {
1823 surfaceIds->push_back(id);
1824 }
1825 }
1826
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001827 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001828
Emilian Peev08dd2452017-04-06 16:55:14 +01001829 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001830
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001831 res = mOutputStreams.add(mNextStreamId, newStream);
1832 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001833 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001834 return res;
1835 }
1836
1837 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001838 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001839
1840 // Continue captures if active at start
1841 if (wasActive) {
1842 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001843 // Reuse current operating mode and session parameters for new stream config
1844 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001845 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001846 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1847 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001848 return res;
1849 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001850 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001851 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001852 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001853 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001854}
1855
Emilian Peev710c1422017-08-30 11:19:38 +01001856status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001857 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001858 if (nullptr == streamInfo) {
1859 return BAD_VALUE;
1860 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001861 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001862 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001863
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001864 switch (mStatus) {
1865 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001866 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001867 return INVALID_OPERATION;
1868 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001869 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001870 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001871 case STATUS_UNCONFIGURED:
1872 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001873 case STATUS_ACTIVE:
1874 // OK
1875 break;
1876 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001877 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001878 return INVALID_OPERATION;
1879 }
1880
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001881 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1882 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001883 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001884 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001885 }
1886
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001887 streamInfo->width = stream->getWidth();
1888 streamInfo->height = stream->getHeight();
1889 streamInfo->format = stream->getFormat();
1890 streamInfo->dataSpace = stream->getDataSpace();
1891 streamInfo->formatOverridden = stream->isFormatOverridden();
1892 streamInfo->originalFormat = stream->getOriginalFormat();
1893 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1894 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001895 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001896}
1897
1898status_t Camera3Device::setStreamTransform(int id,
1899 int transform) {
1900 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001901 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001902 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001903
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001904 switch (mStatus) {
1905 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001906 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001907 return INVALID_OPERATION;
1908 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001909 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001910 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001911 case STATUS_UNCONFIGURED:
1912 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001913 case STATUS_ACTIVE:
1914 // OK
1915 break;
1916 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001917 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001918 return INVALID_OPERATION;
1919 }
1920
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001921 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1922 if (stream == nullptr) {
1923 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001924 return BAD_VALUE;
1925 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001926 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001927}
1928
1929status_t Camera3Device::deleteStream(int id) {
1930 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001931 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001932 Mutex::Autolock l(mLock);
1933 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001934
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001935 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001936
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001937 // CameraDevice semantics require device to already be idle before
1938 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001939 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001940 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001941 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001942 }
1943
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001944 if (mStatus == STATUS_ERROR) {
1945 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1946 __FUNCTION__, mId.string());
1947 return -EBUSY;
1948 }
1949
Igor Murashkin2fba5842013-04-22 14:03:54 -07001950 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001951 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001952 if (mInputStream != NULL && id == mInputStream->getId()) {
1953 deletedStream = mInputStream;
1954 mInputStream.clear();
1955 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001956 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001957 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001958 return BAD_VALUE;
1959 }
Zhijun He5f446352014-01-22 09:49:33 -08001960 }
1961
1962 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001963 if (stream != nullptr) {
1964 deletedStream = stream;
1965 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001966 }
1967
1968 // Free up the stream endpoint so that it can be used by some other stream
1969 res = deletedStream->disconnect();
1970 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001971 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001972 // fall through since we want to still list the stream as deleted.
1973 }
1974 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001975 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001976
1977 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001978}
1979
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001980status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001981 ATRACE_CALL();
1982 ALOGV("%s: E", __FUNCTION__);
1983
1984 Mutex::Autolock il(mInterfaceLock);
1985 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001986
Emilian Peev811d2952018-05-25 11:08:40 +01001987 // In case the client doesn't include any session parameter, try a
1988 // speculative configuration using the values from the last cached
1989 // default request.
1990 if (sessionParams.isEmpty() &&
1991 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1992 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1993 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1994 mLastTemplateId);
1995 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
1996 operatingMode);
1997 }
1998
Emilian Peevac3ce6c2017-12-12 15:27:02 +00001999 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
2000}
2001
2002status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
2003 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002004 //Filter out any incoming session parameters
2005 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002006 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
2007 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002008 CameraMetadata filteredParams(availableSessionKeys.count);
2009 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2010 filteredParams.getAndLock());
2011 set_camera_metadata_vendor_id(meta, mVendorTagId);
2012 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002013 if (availableSessionKeys.count > 0) {
2014 for (size_t i = 0; i < availableSessionKeys.count; i++) {
2015 camera_metadata_ro_entry entry = params.find(
2016 availableSessionKeys.data.i32[i]);
2017 if (entry.count > 0) {
2018 filteredParams.update(entry);
2019 }
2020 }
2021 }
2022
2023 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07002024}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002025
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002026status_t Camera3Device::getInputBufferProducer(
2027 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002028 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002029 Mutex::Autolock il(mInterfaceLock);
2030 Mutex::Autolock l(mLock);
2031
2032 if (producer == NULL) {
2033 return BAD_VALUE;
2034 } else if (mInputStream == NULL) {
2035 return INVALID_OPERATION;
2036 }
2037
2038 return mInputStream->getInputBufferProducer(producer);
2039}
2040
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002041status_t Camera3Device::createDefaultRequest(int templateId,
2042 CameraMetadata *request) {
2043 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002044 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002045
2046 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2047 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002048 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002049 return BAD_VALUE;
2050 }
2051
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002052 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002053
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002054 {
2055 Mutex::Autolock l(mLock);
2056 switch (mStatus) {
2057 case STATUS_ERROR:
2058 CLOGE("Device has encountered a serious error");
2059 return INVALID_OPERATION;
2060 case STATUS_UNINITIALIZED:
2061 CLOGE("Device is not initialized!");
2062 return INVALID_OPERATION;
2063 case STATUS_UNCONFIGURED:
2064 case STATUS_CONFIGURED:
2065 case STATUS_ACTIVE:
2066 // OK
2067 break;
2068 default:
2069 SET_ERR_L("Unexpected status: %d", mStatus);
2070 return INVALID_OPERATION;
2071 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002072
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002073 if (!mRequestTemplateCache[templateId].isEmpty()) {
2074 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002075 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002076 return OK;
2077 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002078 }
2079
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002080 camera_metadata_t *rawRequest;
2081 status_t res = mInterface->constructDefaultRequestSettings(
2082 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002083
2084 {
2085 Mutex::Autolock l(mLock);
2086 if (res == BAD_VALUE) {
2087 ALOGI("%s: template %d is not supported on this camera device",
2088 __FUNCTION__, templateId);
2089 return res;
2090 } else if (res != OK) {
2091 CLOGE("Unable to construct request template %d: %s (%d)",
2092 templateId, strerror(-res), res);
2093 return res;
2094 }
2095
2096 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2097 mRequestTemplateCache[templateId].acquire(rawRequest);
2098
2099 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002100 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002101 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002102 return OK;
2103}
2104
2105status_t Camera3Device::waitUntilDrained() {
2106 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002107 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002108 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002109 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002110
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002111 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002112}
2113
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002114status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002115 switch (mStatus) {
2116 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002117 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002118 ALOGV("%s: Already idle", __FUNCTION__);
2119 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002120 case STATUS_CONFIGURED:
2121 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002122 case STATUS_ERROR:
2123 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002124 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002125 break;
2126 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002127 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002128 return INVALID_OPERATION;
2129 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002130 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2131 maxExpectedDuration);
2132 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002133 if (res != OK) {
2134 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2135 res);
2136 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002137 return res;
2138}
2139
Ruben Brunk183f0562015-08-12 12:55:02 -07002140
2141void Camera3Device::internalUpdateStatusLocked(Status status) {
2142 mStatus = status;
2143 mRecentStatusUpdates.add(mStatus);
2144 mStatusChanged.broadcast();
2145}
2146
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002147void Camera3Device::pauseStateNotify(bool enable) {
2148 Mutex::Autolock il(mInterfaceLock);
2149 Mutex::Autolock l(mLock);
2150
2151 mPauseStateNotify = enable;
2152}
2153
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002154// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002155status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08002156 if (mRequestThread.get() != nullptr) {
2157 mRequestThread->setPaused(true);
2158 } else {
2159 return NO_INIT;
2160 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002161
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002162 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2163 maxExpectedDuration);
2164 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002165 if (res != OK) {
2166 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002167 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002168 }
2169
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002170 return res;
2171}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002172
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002173// Resume after internalPauseAndWaitLocked
2174status_t Camera3Device::internalResumeLocked() {
2175 status_t res;
2176
2177 mRequestThread->setPaused(false);
2178
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002179 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2180 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002181 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2182 if (res != OK) {
2183 SET_ERR_L("Can't transition to active in %f seconds!",
2184 kActiveTimeout/1e9);
2185 }
2186 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002187 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002188}
2189
Ruben Brunk183f0562015-08-12 12:55:02 -07002190status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002191 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002192
2193 size_t startIndex = 0;
2194 if (mStatusWaiters == 0) {
2195 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2196 // this status list
2197 mRecentStatusUpdates.clear();
2198 } else {
2199 // If other threads are waiting on updates to this status list, set the position of the
2200 // first element that this list will check rather than clearing the list.
2201 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002202 }
2203
Ruben Brunk183f0562015-08-12 12:55:02 -07002204 mStatusWaiters++;
2205
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002206 if (!active && mUseHalBufManager) {
2207 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08002208 if (mStatus == STATUS_ACTIVE) {
2209 mRequestThread->signalPipelineDrain(streamIds);
2210 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002211 mRequestBufferSM.onWaitUntilIdle();
2212 }
2213
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002214 bool stateSeen = false;
2215 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002216 if (active == (mStatus == STATUS_ACTIVE)) {
2217 // Desired state is current
2218 break;
2219 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002220
2221 res = mStatusChanged.waitRelative(mLock, timeout);
2222 if (res != OK) break;
2223
Ruben Brunk183f0562015-08-12 12:55:02 -07002224 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2225 // transitions.
2226 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2227 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2228 __FUNCTION__);
2229
2230 // Encountered desired state since we began waiting
2231 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002232 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2233 stateSeen = true;
2234 break;
2235 }
2236 }
2237 } while (!stateSeen);
2238
Ruben Brunk183f0562015-08-12 12:55:02 -07002239 mStatusWaiters--;
2240
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002241 return res;
2242}
2243
2244
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002245status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002246 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002247 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002248
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002249 if (listener != NULL && mListener != NULL) {
2250 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2251 }
2252 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002253 mRequestThread->setNotificationListener(listener);
2254 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002255
2256 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002257}
2258
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002259bool Camera3Device::willNotify3A() {
2260 return false;
2261}
2262
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002263status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002264 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002265 status_t res;
2266 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002267
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002268 while (mResultQueue.empty()) {
2269 res = mResultSignal.waitRelative(mOutputLock, timeout);
2270 if (res == TIMED_OUT) {
2271 return res;
2272 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002273 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2274 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002275 return res;
2276 }
2277 }
2278 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002279}
2280
Jianing Weicb0652e2014-03-12 18:29:36 -07002281status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002282 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002283 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002284
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002285 if (mResultQueue.empty()) {
2286 return NOT_ENOUGH_DATA;
2287 }
2288
Jianing Weicb0652e2014-03-12 18:29:36 -07002289 if (frame == NULL) {
2290 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2291 return BAD_VALUE;
2292 }
2293
2294 CaptureResult &result = *(mResultQueue.begin());
2295 frame->mResultExtras = result.mResultExtras;
2296 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002297 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002298 mResultQueue.erase(mResultQueue.begin());
2299
2300 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002301}
2302
2303status_t Camera3Device::triggerAutofocus(uint32_t id) {
2304 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002305 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002306
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002307 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2308 // Mix-in this trigger into the next request and only the next request.
2309 RequestTrigger trigger[] = {
2310 {
2311 ANDROID_CONTROL_AF_TRIGGER,
2312 ANDROID_CONTROL_AF_TRIGGER_START
2313 },
2314 {
2315 ANDROID_CONTROL_AF_TRIGGER_ID,
2316 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002317 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002318 };
2319
2320 return mRequestThread->queueTrigger(trigger,
2321 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002322}
2323
2324status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2325 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002326 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002327
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002328 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2329 // Mix-in this trigger into the next request and only the next request.
2330 RequestTrigger trigger[] = {
2331 {
2332 ANDROID_CONTROL_AF_TRIGGER,
2333 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2334 },
2335 {
2336 ANDROID_CONTROL_AF_TRIGGER_ID,
2337 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002338 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002339 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002340
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002341 return mRequestThread->queueTrigger(trigger,
2342 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002343}
2344
2345status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2346 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002347 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002348
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002349 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2350 // Mix-in this trigger into the next request and only the next request.
2351 RequestTrigger trigger[] = {
2352 {
2353 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2354 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2355 },
2356 {
2357 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2358 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002359 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002360 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002361
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002362 return mRequestThread->queueTrigger(trigger,
2363 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002364}
2365
Jianing Weicb0652e2014-03-12 18:29:36 -07002366status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002367 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002368 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002369 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002370
Zhijun He7ef20392014-04-21 16:04:17 -07002371 {
2372 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002373
2374 // b/116514106 "disconnect()" can get called twice for the same device. The
2375 // camera device will not be initialized during the second run.
2376 if (mStatus == STATUS_UNINITIALIZED) {
2377 return OK;
2378 }
2379
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002380 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002381 }
2382
Emilian Peev08dd2452017-04-06 16:55:14 +01002383 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002384}
2385
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002386status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002387 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2388}
2389
2390status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002391 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002392 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002393 Mutex::Autolock il(mInterfaceLock);
2394 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002395
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002396 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2397 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002398 CLOGE("Stream %d does not exist", streamId);
2399 return BAD_VALUE;
2400 }
2401
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002402 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002403 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002404 return BAD_VALUE;
2405 }
2406
2407 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002408 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002409 return BAD_VALUE;
2410 }
2411
Ruben Brunkc78ac262015-08-13 17:58:46 -07002412 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002413}
2414
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002415status_t Camera3Device::tearDown(int streamId) {
2416 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002417 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002418 Mutex::Autolock il(mInterfaceLock);
2419 Mutex::Autolock l(mLock);
2420
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002421 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2422 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002423 CLOGE("Stream %d does not exist", streamId);
2424 return BAD_VALUE;
2425 }
2426
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002427 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2428 CLOGE("Stream %d is a target of a in-progress request", streamId);
2429 return BAD_VALUE;
2430 }
2431
2432 return stream->tearDown();
2433}
2434
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002435status_t Camera3Device::addBufferListenerForStream(int streamId,
2436 wp<Camera3StreamBufferListener> listener) {
2437 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002438 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002439 Mutex::Autolock il(mInterfaceLock);
2440 Mutex::Autolock l(mLock);
2441
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002442 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2443 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002444 CLOGE("Stream %d does not exist", streamId);
2445 return BAD_VALUE;
2446 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002447 stream->addBufferListener(listener);
2448
2449 return OK;
2450}
2451
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002452/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002453 * Methods called by subclasses
2454 */
2455
2456void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002457 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002458 {
2459 // Need mLock to safely update state and synchronize to current
2460 // state of methods in flight.
2461 Mutex::Autolock l(mLock);
2462 // We can get various system-idle notices from the status tracker
2463 // while starting up. Only care about them if we've actually sent
2464 // in some requests recently.
2465 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2466 return;
2467 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002468 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2469 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002470 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002471
2472 // Skip notifying listener if we're doing some user-transparent
2473 // state changes
2474 if (mPauseStateNotify) return;
2475 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002476
2477 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002478 {
2479 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002480 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002481 }
2482 if (idle && listener != NULL) {
2483 listener->notifyIdle();
2484 }
2485}
2486
Shuzhen Wang758c2152017-01-10 18:26:18 -08002487status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002488 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002489 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002490 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2491 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002492
2493 if (surfaceIds == nullptr) {
2494 return BAD_VALUE;
2495 }
2496
Zhijun He5d677d12016-05-29 16:52:39 -07002497 Mutex::Autolock il(mInterfaceLock);
2498 Mutex::Autolock l(mLock);
2499
Shuzhen Wang758c2152017-01-10 18:26:18 -08002500 if (consumers.size() == 0) {
2501 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002502 return BAD_VALUE;
2503 }
2504
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002505 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2506 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002507 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002508 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002509 }
Shuzhen Wang758c2152017-01-10 18:26:18 -08002510 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002511 if (res != OK) {
2512 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2513 return res;
2514 }
2515
Emilian Peev40ead602017-09-26 15:46:36 +01002516 for (auto &consumer : consumers) {
2517 int id = stream->getSurfaceId(consumer);
2518 if (id < 0) {
2519 CLOGE("Invalid surface id!");
2520 return BAD_VALUE;
2521 }
2522 surfaceIds->push_back(id);
2523 }
2524
Shuzhen Wang0129d522016-10-30 22:43:41 -07002525 if (stream->isConsumerConfigurationDeferred()) {
2526 if (!stream->isConfiguring()) {
2527 CLOGE("Stream %d was already fully configured.", streamId);
2528 return INVALID_OPERATION;
2529 }
Zhijun He5d677d12016-05-29 16:52:39 -07002530
Shuzhen Wang0129d522016-10-30 22:43:41 -07002531 res = stream->finishConfiguration();
2532 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002533 // If finishConfiguration fails due to abandoned surface, do not set
2534 // device to error state.
2535 bool isSurfaceAbandoned =
2536 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2537 if (!isSurfaceAbandoned) {
2538 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2539 stream->getId(), strerror(-res), res);
2540 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002541 return res;
2542 }
Zhijun He5d677d12016-05-29 16:52:39 -07002543 }
2544
2545 return OK;
2546}
2547
Emilian Peev40ead602017-09-26 15:46:36 +01002548status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2549 const std::vector<OutputStreamInfo> &outputInfo,
2550 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2551 Mutex::Autolock il(mInterfaceLock);
2552 Mutex::Autolock l(mLock);
2553
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002554 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2555 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002556 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002557 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002558 }
2559
2560 for (const auto &it : removedSurfaceIds) {
2561 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2562 CLOGE("Shared surface still part of a pending request!");
2563 return -EBUSY;
2564 }
2565 }
2566
Emilian Peev40ead602017-09-26 15:46:36 +01002567 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2568 if (res != OK) {
2569 CLOGE("Stream %d failed to update stream (error %d %s) ",
2570 streamId, res, strerror(-res));
2571 if (res == UNKNOWN_ERROR) {
2572 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2573 __FUNCTION__);
2574 }
2575 return res;
2576 }
2577
2578 return res;
2579}
2580
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002581status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2582 Mutex::Autolock il(mInterfaceLock);
2583 Mutex::Autolock l(mLock);
2584
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002585 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2586 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002587 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2588 return BAD_VALUE;
2589 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002590 return stream->dropBuffers(dropping);
2591}
2592
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002593/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002594 * Camera3Device private methods
2595 */
2596
2597sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002598 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002599 ATRACE_CALL();
2600 status_t res;
2601
2602 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002603 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002604
2605 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002606 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002607 if (inputStreams.count > 0) {
2608 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002609 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002610 CLOGE("Request references unknown input stream %d",
2611 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002612 return NULL;
2613 }
2614 // Lazy completion of stream configuration (allocation/registration)
2615 // on first use
2616 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002617 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002618 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002619 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002620 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002621 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002622 return NULL;
2623 }
2624 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002625 // Check if stream prepare is blocking requests.
2626 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002627 CLOGE("Request references an input stream that's being prepared!");
2628 return NULL;
2629 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002630
2631 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002632 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002633 }
2634
2635 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002636 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002637 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002638 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002639 return NULL;
2640 }
2641
2642 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002643 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2644 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002645 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002646 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002647 return NULL;
2648 }
Zhijun He5d677d12016-05-29 16:52:39 -07002649 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002650 auto iter = surfaceMap.find(streams.data.i32[i]);
2651 if (iter != surfaceMap.end()) {
2652 const std::vector<size_t>& surfaces = iter->second;
2653 for (const auto& surface : surfaces) {
2654 if (stream->isConsumerConfigurationDeferred(surface)) {
2655 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2656 "due to deferred consumer", stream->getId(), surface);
2657 return NULL;
2658 }
2659 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002660 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002661 }
2662
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002663 // Lazy completion of stream configuration (allocation/registration)
2664 // on first use
2665 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002666 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002667 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002668 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2669 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002670 return NULL;
2671 }
2672 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002673 // Check if stream prepare is blocking requests.
2674 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002675 CLOGE("Request references an output stream that's being prepared!");
2676 return NULL;
2677 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002678
2679 newRequest->mOutputStreams.push(stream);
2680 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002681 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002682 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002683
2684 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002685}
2686
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002687bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2688 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2689 Size size = mSupportedOpaqueInputSizes[i];
2690 if (size.width == width && size.height == height) {
2691 return true;
2692 }
2693 }
2694
2695 return false;
2696}
2697
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002698void Camera3Device::cancelStreamsConfigurationLocked() {
2699 int res = OK;
2700 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2701 res = mInputStream->cancelConfiguration();
2702 if (res != OK) {
2703 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2704 mInputStream->getId(), strerror(-res), res);
2705 }
2706 }
2707
2708 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002709 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002710 if (outputStream->isConfiguring()) {
2711 res = outputStream->cancelConfiguration();
2712 if (res != OK) {
2713 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2714 outputStream->getId(), strerror(-res), res);
2715 }
2716 }
2717 }
2718
2719 // Return state to that at start of call, so that future configures
2720 // properly clean things up
2721 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2722 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002723
2724 res = mPreparerThread->resume();
2725 if (res != OK) {
2726 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2727 }
2728}
2729
2730bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2731 ATRACE_CALL();
2732 bool ret = false;
2733
2734 Mutex::Autolock il(mInterfaceLock);
2735 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2736
2737 Mutex::Autolock l(mLock);
2738 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2739 if (rc == NO_ERROR) {
2740 mNeedConfig = true;
2741 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2742 if (rc == NO_ERROR) {
2743 ret = true;
2744 mPauseStateNotify = false;
2745 //Moving to active state while holding 'mLock' is important.
2746 //There could be pending calls to 'create-/deleteStream' which
2747 //will trigger another stream configuration while the already
2748 //present streams end up with outstanding buffers that will
2749 //not get drained.
2750 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002751 } else if (rc == DEAD_OBJECT) {
2752 // DEAD_OBJECT can be returned if either the consumer surface is
2753 // abandoned, or the HAL has died.
2754 // - If the HAL has died, configureStreamsLocked call will set
2755 // device to error state,
2756 // - If surface is abandoned, we should not set device to error
2757 // state.
2758 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002759 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002760 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002761 }
2762 } else {
2763 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2764 }
2765
2766 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002767}
2768
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002769status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002770 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002771 ATRACE_CALL();
2772 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002773
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002774 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002775 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002776 return INVALID_OPERATION;
2777 }
2778
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002779 if (operatingMode < 0) {
2780 CLOGE("Invalid operating mode: %d", operatingMode);
2781 return BAD_VALUE;
2782 }
2783
2784 bool isConstrainedHighSpeed =
2785 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2786 operatingMode;
2787
2788 if (mOperatingMode != operatingMode) {
2789 mNeedConfig = true;
2790 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2791 mOperatingMode = operatingMode;
2792 }
2793
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002794 if (!mNeedConfig) {
2795 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2796 return OK;
2797 }
2798
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002799 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2800 // adding a dummy stream instead.
2801 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2802 if (mOutputStreams.size() == 0) {
2803 addDummyStreamLocked();
2804 } else {
2805 tryRemoveDummyStreamLocked();
2806 }
2807
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002808 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002809 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002810
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002811 mPreparerThread->pause();
2812
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002813 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002814 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002815 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2816
2817 Vector<camera3_stream_t*> streams;
2818 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002819 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002820
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002821
2822 if (mInputStream != NULL) {
2823 camera3_stream_t *inputStream;
2824 inputStream = mInputStream->startConfiguration();
2825 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002826 CLOGE("Can't start input stream configuration");
2827 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002828 return INVALID_OPERATION;
2829 }
2830 streams.add(inputStream);
2831 }
2832
2833 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002834
2835 // Don't configure bidi streams twice, nor add them twice to the list
2836 if (mOutputStreams[i].get() ==
2837 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2838
2839 config.num_streams--;
2840 continue;
2841 }
2842
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002843 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002844 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002845 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002846 CLOGE("Can't start output stream configuration");
2847 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002848 return INVALID_OPERATION;
2849 }
2850 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002851
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002852 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002853 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2854 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002855 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2856 bufferSizes[k] = static_cast<uint32_t>(
2857 getJpegBufferSize(outputStream->width, outputStream->height));
2858 } else if (outputStream->data_space ==
2859 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2860 bufferSizes[k] = outputStream->width * outputStream->height;
2861 } else {
2862 ALOGW("%s: Blob dataSpace %d not supported",
2863 __FUNCTION__, outputStream->data_space);
2864 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002865 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002866 }
2867
2868 config.streams = streams.editArray();
2869
2870 // Do the HAL configuration; will potentially touch stream
2871 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002872
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002873 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002874 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002875 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002876
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002877 if (res == BAD_VALUE) {
2878 // HAL rejected this set of streams as unsupported, clean up config
2879 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002880 CLOGE("Set of requested inputs/outputs not supported by HAL");
2881 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002882 return BAD_VALUE;
2883 } else if (res != OK) {
2884 // Some other kind of error from configure_streams - this is not
2885 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002886 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2887 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002888 return res;
2889 }
2890
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002891 // Finish all stream configuration immediately.
2892 // TODO: Try to relax this later back to lazy completion, which should be
2893 // faster
2894
Igor Murashkin073f8572013-05-02 14:59:28 -07002895 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002896 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002897 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002898 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002899 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002900 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002901 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2902 return DEAD_OBJECT;
2903 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002904 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002905 }
2906 }
2907
2908 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002909 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002910 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002911 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002912 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002913 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002914 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002915 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002916 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2917 return DEAD_OBJECT;
2918 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002919 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002920 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002921 }
2922 }
2923
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002924 // Request thread needs to know to avoid using repeat-last-settings protocol
2925 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002926 if (notifyRequestThread) {
2927 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2928 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002929
Zhijun He90f7c372016-08-16 16:19:43 -07002930 char value[PROPERTY_VALUE_MAX];
2931 property_get("camera.fifo.disable", value, "0");
2932 int32_t disableFifo = atoi(value);
2933 if (disableFifo != 1) {
2934 // Boost priority of request thread to SCHED_FIFO.
2935 pid_t requestThreadTid = mRequestThread->getTid();
2936 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002937 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002938 if (res != OK) {
2939 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2940 strerror(-res), res);
2941 } else {
2942 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2943 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002944 }
2945
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002946 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002947 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2948 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2949 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2950 sessionParams.unlock(newSessionParams);
2951 mSessionParams.unlock(currentSessionParams);
2952 if (updateSessionParams) {
2953 mSessionParams = sessionParams;
2954 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002955
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002956 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002957
Ruben Brunk183f0562015-08-12 12:55:02 -07002958 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2959 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002960
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002961 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002962
Zhijun He0a210512014-07-24 13:45:15 -07002963 // tear down the deleted streams after configure streams.
2964 mDeletedStreams.clear();
2965
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002966 auto rc = mPreparerThread->resume();
2967 if (rc != OK) {
2968 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2969 return rc;
2970 }
2971
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002972 if (mDummyStreamId == NO_STREAM) {
2973 mRequestBufferSM.onStreamsConfigured();
2974 }
2975
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002976 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002977}
2978
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002979status_t Camera3Device::addDummyStreamLocked() {
2980 ATRACE_CALL();
2981 status_t res;
2982
2983 if (mDummyStreamId != NO_STREAM) {
2984 // Should never be adding a second dummy stream when one is already
2985 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002986 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2987 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002988 return INVALID_OPERATION;
2989 }
2990
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002991 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002992
2993 sp<Camera3OutputStreamInterface> dummyStream =
2994 new Camera3DummyStream(mNextStreamId);
2995
2996 res = mOutputStreams.add(mNextStreamId, dummyStream);
2997 if (res < 0) {
2998 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
2999 return res;
3000 }
3001
3002 mDummyStreamId = mNextStreamId;
3003 mNextStreamId++;
3004
3005 return OK;
3006}
3007
3008status_t Camera3Device::tryRemoveDummyStreamLocked() {
3009 ATRACE_CALL();
3010 status_t res;
3011
3012 if (mDummyStreamId == NO_STREAM) return OK;
3013 if (mOutputStreams.size() == 1) return OK;
3014
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003015 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003016
3017 // Ok, have a dummy stream and there's at least one other output stream,
3018 // so remove the dummy
3019
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003020 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
3021 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003022 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3023 return INVALID_OPERATION;
3024 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003025 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003026
3027 // Free up the stream endpoint so that it can be used by some other stream
3028 res = deletedStream->disconnect();
3029 if (res != OK) {
3030 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3031 // fall through since we want to still list the stream as deleted.
3032 }
3033 mDeletedStreams.add(deletedStream);
3034 mDummyStreamId = NO_STREAM;
3035
3036 return res;
3037}
3038
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003039void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003040 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003041 Mutex::Autolock l(mLock);
3042 va_list args;
3043 va_start(args, fmt);
3044
3045 setErrorStateLockedV(fmt, args);
3046
3047 va_end(args);
3048}
3049
3050void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003051 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003052 Mutex::Autolock l(mLock);
3053 setErrorStateLockedV(fmt, args);
3054}
3055
3056void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3057 va_list args;
3058 va_start(args, fmt);
3059
3060 setErrorStateLockedV(fmt, args);
3061
3062 va_end(args);
3063}
3064
3065void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003066 // Print out all error messages to log
3067 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003068 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003069
3070 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003071 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003072
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003073 mErrorCause = errorCause;
3074
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003075 if (mRequestThread != nullptr) {
3076 mRequestThread->setPaused(true);
3077 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003078 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003079
3080 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003081 sp<NotificationListener> listener = mListener.promote();
3082 if (listener != NULL) {
3083 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003084 CaptureResultExtras());
3085 }
3086
3087 // Save stack trace. View by dumping it later.
3088 CameraTraces::saveTrace();
3089 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003090}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003091
3092/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003093 * In-flight request management
3094 */
3095
Jianing Weicb0652e2014-03-12 18:29:36 -07003096status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003097 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003098 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003099 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003100 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003101 ATRACE_CALL();
3102 Mutex::Autolock l(mInFlightLock);
3103
3104 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003105 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003106 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3107 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003108 if (res < 0) return res;
3109
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003110 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003111 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3112 // avoid a deadlock during reprocess requests.
3113 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003114 if (mStatusTracker != nullptr) {
3115 mStatusTracker->markComponentActive(mInFlightStatusId);
3116 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003117 }
3118
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003119 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003120 return OK;
3121}
3122
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003123void Camera3Device::returnOutputBuffers(
3124 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003125 nsecs_t timestamp, bool timestampIncreasing,
3126 const SurfaceMap& outputSurfaces,
3127 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003128
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003129 for (size_t i = 0; i < numBuffers; i++)
3130 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003131 if (outputBuffers[i].buffer == nullptr) {
3132 if (!mUseHalBufManager) {
3133 // With HAL buffer management API, HAL sometimes will have to return buffers that
3134 // has not got a output buffer handle filled yet. This is though illegal if HAL
3135 // buffer management API is not being used.
3136 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3137 }
3138 continue;
3139 }
3140
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003141 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3142 int streamId = stream->getId();
3143 const auto& it = outputSurfaces.find(streamId);
3144 status_t res = OK;
3145 if (it != outputSurfaces.end()) {
3146 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003147 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3148 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003149 } else {
3150 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003151 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3152 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003153 }
3154
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003155 // Note: stream may be deallocated at this point, if this buffer was
3156 // the last reference to it.
3157 if (res != OK) {
3158 ALOGE("Can't return buffer to its stream: %s (%d)",
3159 strerror(-res), res);
3160 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003161
3162 // Long processing consumers can cause returnBuffer timeout for shared stream
3163 // If that happens, cancel the buffer and send a buffer error to client
3164 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3165 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3166 // cancel the buffer
3167 camera3_stream_buffer_t sb = outputBuffers[i];
3168 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003169 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3170 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003171
3172 // notify client buffer error
3173 sp<NotificationListener> listener;
3174 {
3175 Mutex::Autolock l(mOutputLock);
3176 listener = mListener.promote();
3177 }
3178
3179 if (listener != nullptr) {
3180 CaptureResultExtras extras = inResultExtras;
3181 extras.errorStreamId = streamId;
3182 listener->notifyError(
3183 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3184 extras);
3185 }
3186 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003187 }
3188}
3189
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003190void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003191 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003192 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003193 mInFlightMap.removeItemsAt(idx, 1);
3194
3195 // Indicate idle inFlightMap to the status tracker
3196 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003197 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003198 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3199 // avoid a deadlock during reprocess requests.
3200 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003201 if (mStatusTracker != nullptr) {
3202 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3203 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003204 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003205 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003206}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003207
3208void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3209
3210 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3211 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3212
3213 nsecs_t sensorTimestamp = request.sensorTimestamp;
3214 nsecs_t shutterTimestamp = request.shutterTimestamp;
3215
3216 // Check if it's okay to remove the request from InFlightMap:
3217 // In the case of a successful request:
3218 // all input and output buffers, all result metadata, shutter callback
3219 // arrived.
3220 // In the case of a unsuccessful request:
3221 // all input and output buffers arrived.
3222 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003223 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003224 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003225 if (request.stillCapture) {
3226 ATRACE_ASYNC_END("still capture", frameNumber);
3227 }
3228
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003229 ATRACE_ASYNC_END("frame capture", frameNumber);
3230
Shuzhen Wang403044a2017-02-26 23:29:04 -08003231 // Sanity check - if sensor timestamp matches shutter timestamp in the
3232 // case of request having callback.
3233 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003234 sensorTimestamp != shutterTimestamp) {
3235 SET_ERR("sensor timestamp (%" PRId64
3236 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3237 sensorTimestamp, frameNumber, shutterTimestamp);
3238 }
3239
3240 // for an unsuccessful request, it may have pending output buffers to
3241 // return.
3242 assert(request.requestStatus != OK ||
3243 request.pendingOutputBuffers.size() == 0);
3244 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003245 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3246 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003247
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003248 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003249 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3250 }
3251
3252 // Sanity check - if we have too many in-flight frames, something has
3253 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003254 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003255 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003256 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3257 kInFlightWarnLimitHighSpeed) {
3258 CLOGE("In-flight list too large for high speed configuration: %zu",
3259 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003260 }
3261}
3262
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003263void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003264 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003265 { // First return buffers cached in mInFlightMap
3266 Mutex::Autolock l(mInFlightLock);
3267 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3268 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3269 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003270 request.pendingOutputBuffers.size(), 0,
3271 /*timestampIncreasing*/true, request.outputSurfaces,
3272 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003273 }
3274 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003275 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003276 }
3277
3278 // Then return all inflight buffers not returned by HAL
3279 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3280 mInterface->getInflightBufferKeys(&inflightKeys);
3281
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003282 // Inflight buffers for HAL buffer manager
3283 std::vector<uint64_t> inflightRequestBufferKeys;
3284 mInterface->getInflightRequestBufferKeys(&inflightRequestBufferKeys);
3285
3286 // (streamId, frameNumber, buffer_handle_t*) tuple for all inflight buffers.
3287 // frameNumber will be -1 for buffers from HAL buffer manager
3288 std::vector<std::tuple<int32_t, int32_t, buffer_handle_t*>> inflightBuffers;
3289 inflightBuffers.reserve(inflightKeys.size() + inflightRequestBufferKeys.size());
3290
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003291 for (auto& pair : inflightKeys) {
3292 int32_t frameNumber = pair.first;
3293 int32_t streamId = pair.second;
3294 buffer_handle_t* buffer;
3295 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3296 if (res != OK) {
3297 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3298 __FUNCTION__, frameNumber, streamId);
3299 continue;
3300 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003301 inflightBuffers.push_back(std::make_tuple(streamId, frameNumber, buffer));
3302 }
3303
3304 for (auto& bufferId : inflightRequestBufferKeys) {
3305 int32_t streamId = -1;
3306 buffer_handle_t* buffer = nullptr;
3307 status_t res = mInterface->popInflightRequestBuffer(bufferId, &buffer, &streamId);
3308 if (res != OK) {
3309 ALOGE("%s: cannot find in-flight buffer %" PRIu64, __FUNCTION__, bufferId);
3310 continue;
3311 }
3312 inflightBuffers.push_back(std::make_tuple(streamId, /*frameNumber*/-1, buffer));
3313 }
3314
3315 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3316 for (auto& tuple : inflightBuffers) {
3317 status_t res = OK;
3318 int32_t streamId = std::get<0>(tuple);
3319 int32_t frameNumber = std::get<1>(tuple);
3320 buffer_handle_t* buffer = std::get<2>(tuple);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003321
3322 camera3_stream_buffer_t streamBuffer;
3323 streamBuffer.buffer = buffer;
3324 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3325 streamBuffer.acquire_fence = -1;
3326 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003327
3328 // First check if the buffer belongs to deleted stream
3329 bool streamDeleted = false;
3330 for (auto& stream : mDeletedStreams) {
3331 if (streamId == stream->getId()) {
3332 streamDeleted = true;
3333 // Return buffer to deleted stream
3334 camera3_stream* halStream = stream->asHalStream();
3335 streamBuffer.stream = halStream;
3336 switch (halStream->stream_type) {
3337 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003338 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3339 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003340 if (res != OK) {
3341 ALOGE("%s: Can't return output buffer for frame %d to"
3342 " stream %d: %s (%d)", __FUNCTION__,
3343 frameNumber, streamId, strerror(-res), res);
3344 }
3345 break;
3346 case CAMERA3_STREAM_INPUT:
3347 res = stream->returnInputBuffer(streamBuffer);
3348 if (res != OK) {
3349 ALOGE("%s: Can't return input buffer for frame %d to"
3350 " stream %d: %s (%d)", __FUNCTION__,
3351 frameNumber, streamId, strerror(-res), res);
3352 }
3353 break;
3354 default: // Bi-direcitonal stream is deprecated
3355 ALOGE("%s: stream %d has unknown stream type %d",
3356 __FUNCTION__, streamId, halStream->stream_type);
3357 break;
3358 }
3359 break;
3360 }
3361 }
3362 if (streamDeleted) {
3363 continue;
3364 }
3365
3366 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003367 if (streamId == inputStreamId) {
3368 streamBuffer.stream = mInputStream->asHalStream();
3369 res = mInputStream->returnInputBuffer(streamBuffer);
3370 if (res != OK) {
3371 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003372 " stream %d: %s (%d)", __FUNCTION__,
3373 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003374 }
3375 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003376 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3377 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003378 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3379 continue;
3380 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003381 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003382 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3383 }
3384 }
3385}
3386
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003387void Camera3Device::insertResultLocked(CaptureResult *result,
3388 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003389 if (result == nullptr) return;
3390
Emilian Peev71c73a22017-03-21 16:35:51 +00003391 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3392 result->mMetadata.getAndLock());
3393 set_camera_metadata_vendor_id(meta, mVendorTagId);
3394 result->mMetadata.unlock(meta);
3395
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003396 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3397 (int32_t*)&frameNumber, 1) != OK) {
3398 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3399 return;
3400 }
3401
3402 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3403 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3404 return;
3405 }
3406
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003407 // Valid result, insert into queue
3408 List<CaptureResult>::iterator queuedResult =
3409 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3410 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3411 ", burstId = %" PRId32, __FUNCTION__,
3412 queuedResult->mResultExtras.requestId,
3413 queuedResult->mResultExtras.frameNumber,
3414 queuedResult->mResultExtras.burstId);
3415
3416 mResultSignal.signal();
3417}
3418
3419
3420void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003421 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003422 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003423 Mutex::Autolock l(mOutputLock);
3424
3425 CaptureResult captureResult;
3426 captureResult.mResultExtras = resultExtras;
3427 captureResult.mMetadata = partialResult;
3428
Shuzhen Wang268a1362018-10-16 16:32:59 -07003429 // Fix up result metadata for monochrome camera.
3430 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3431 if (res != OK) {
3432 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3433 return;
3434 }
3435
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003436 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003437}
3438
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003439
3440void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3441 CaptureResultExtras &resultExtras,
3442 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003443 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003444 bool reprocess,
3445 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003446 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003447 if (pendingMetadata.isEmpty())
3448 return;
3449
3450 Mutex::Autolock l(mOutputLock);
3451
3452 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003453 if (reprocess) {
3454 if (frameNumber < mNextReprocessResultFrameNumber) {
3455 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003456 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003457 frameNumber, mNextReprocessResultFrameNumber);
3458 return;
3459 }
3460 mNextReprocessResultFrameNumber = frameNumber + 1;
3461 } else {
3462 if (frameNumber < mNextResultFrameNumber) {
3463 SET_ERR("Out-of-order capture result metadata submitted! "
3464 "(got frame number %d, expecting %d)",
3465 frameNumber, mNextResultFrameNumber);
3466 return;
3467 }
3468 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003469 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003470
3471 CaptureResult captureResult;
3472 captureResult.mResultExtras = resultExtras;
3473 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003474 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003475
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003476 // Append any previous partials to form a complete result
3477 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3478 captureResult.mMetadata.append(collectedPartialResult);
3479 }
3480
3481 captureResult.mMetadata.sort();
3482
3483 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003484 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3485 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003486 SET_ERR("No timestamp provided by HAL for frame %d!",
3487 frameNumber);
3488 return;
3489 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003490 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3491 camera_metadata_entry timestamp =
3492 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3493 if (timestamp.count == 0) {
3494 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3495 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3496 return;
3497 }
3498 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003499
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003500 // Fix up some result metadata to account for HAL-level distortion correction
3501 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3502 if (res != OK) {
3503 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3504 frameNumber, strerror(res), res);
3505 return;
3506 }
Shuzhen Wang268a1362018-10-16 16:32:59 -07003507 // Fix up result metadata for monochrome camera.
3508 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3509 if (res != OK) {
3510 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3511 return;
3512 }
3513 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3514 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3515 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3516 physicalMetadata.mPhysicalCameraMetadata);
3517 if (res != OK) {
3518 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3519 return;
3520 }
3521 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003522
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003523 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3524 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3525
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003526 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003527}
3528
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003529/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003530 * Camera HAL device callback methods
3531 */
3532
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003533void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003534 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003535
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003536 status_t res;
3537
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003538 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003539 if (result->result == NULL && result->num_output_buffers == 0 &&
3540 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003541 SET_ERR("No result data provided by HAL for frame %d",
3542 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003543 return;
3544 }
Zhijun He204e3292014-07-14 17:09:23 -07003545
Zhijun He204e3292014-07-14 17:09:23 -07003546 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003547 result->result != NULL &&
3548 result->partial_result != 1) {
3549 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3550 " if partial result is not supported",
3551 frameNumber, result->partial_result);
3552 return;
3553 }
3554
3555 bool isPartialResult = false;
3556 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003557 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003558
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003559 // Get shutter timestamp and resultExtras from list of in-flight requests,
3560 // where it was added by the shutter notification for this frame. If the
3561 // shutter timestamp isn't received yet, append the output buffers to the
3562 // in-flight request and they will be returned when the shutter timestamp
3563 // arrives. Update the in-flight status and remove the in-flight entry if
3564 // all result data and shutter timestamp have been received.
3565 nsecs_t shutterTimestamp = 0;
3566
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003567 {
3568 Mutex::Autolock l(mInFlightLock);
3569 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3570 if (idx == NAME_NOT_FOUND) {
3571 SET_ERR("Unknown frame number for capture result: %d",
3572 frameNumber);
3573 return;
3574 }
3575 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003576 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3577 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003578 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003579 __FUNCTION__, request.resultExtras.requestId,
3580 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003581 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003582 // Always update the partial count to the latest one if it's not 0
3583 // (buffers only). When framework aggregates adjacent partial results
3584 // into one, the latest partial count will be used.
3585 if (result->partial_result != 0)
3586 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003587
3588 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003589 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003590 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3591 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3592 " the range of [1, %d] when metadata is included in the result",
3593 frameNumber, result->partial_result, mNumPartialResults);
3594 return;
3595 }
3596 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003597 if (isPartialResult && result->num_physcam_metadata) {
3598 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3599 " physical camera result", frameNumber);
3600 return;
3601 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003602 if (isPartialResult) {
3603 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003604 }
3605
Shuzhen Wang4a472662017-02-26 23:29:04 -08003606 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003607 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003608 sendPartialCaptureResult(result->result, request.resultExtras,
3609 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003610 }
3611 }
3612
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003613 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003614 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003615
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003616 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003617 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003618 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3619 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3620 request.physicalCameraIds.size(), result->num_physcam_metadata);
3621 return;
3622 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003623 if (request.haveResultMetadata) {
3624 SET_ERR("Called multiple times with metadata for frame %d",
3625 frameNumber);
3626 return;
3627 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003628 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3629 String8 physicalId(result->physcam_ids[i]);
3630 std::set<String8>::iterator cameraIdIter =
3631 request.physicalCameraIds.find(physicalId);
3632 if (cameraIdIter != request.physicalCameraIds.end()) {
3633 request.physicalCameraIds.erase(cameraIdIter);
3634 } else {
3635 SET_ERR("Total result for frame %d has already returned for camera %s",
3636 frameNumber, physicalId.c_str());
3637 return;
3638 }
3639 }
Zhijun He204e3292014-07-14 17:09:23 -07003640 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003641 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003642 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003643 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003644 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003645 request.haveResultMetadata = true;
3646 }
3647
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003648 uint32_t numBuffersReturned = result->num_output_buffers;
3649 if (result->input_buffer != NULL) {
3650 if (hasInputBufferInRequest) {
3651 numBuffersReturned += 1;
3652 } else {
3653 ALOGW("%s: Input buffer should be NULL if there is no input"
3654 " buffer sent in the request",
3655 __FUNCTION__);
3656 }
3657 }
3658 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003659 if (request.numBuffersLeft < 0) {
3660 SET_ERR("Too many buffers returned for frame %d",
3661 frameNumber);
3662 return;
3663 }
3664
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003665 camera_metadata_ro_entry_t entry;
3666 res = find_camera_metadata_ro_entry(result->result,
3667 ANDROID_SENSOR_TIMESTAMP, &entry);
3668 if (res == OK && entry.count == 1) {
3669 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003670 }
3671
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003672 // If shutter event isn't received yet, append the output buffers to
3673 // the in-flight request. Otherwise, return the output buffers to
3674 // streams.
3675 if (shutterTimestamp == 0) {
3676 request.pendingOutputBuffers.appendArray(result->output_buffers,
3677 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003678 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003679 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003680 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003681 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3682 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003683 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003684
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003685 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003686 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3687 CameraMetadata physicalMetadata;
3688 physicalMetadata.append(result->physcam_metadata[i]);
3689 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3690 physicalMetadata});
3691 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003692 if (shutterTimestamp == 0) {
3693 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003694 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003695 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003696 CameraMetadata metadata;
3697 metadata = result->result;
3698 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003699 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003700 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003701 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003702 }
3703
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003704 removeInFlightRequestIfReadyLocked(idx);
3705 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003706
Zhijun Hef0d962a2014-06-30 10:24:11 -07003707 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003708 if (hasInputBufferInRequest) {
3709 Camera3Stream *stream =
3710 Camera3Stream::cast(result->input_buffer->stream);
3711 res = stream->returnInputBuffer(*(result->input_buffer));
3712 // Note: stream may be deallocated at this point, if this buffer was the
3713 // last reference to it.
3714 if (res != OK) {
3715 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3716 " its stream:%s (%d)", __FUNCTION__,
3717 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003718 }
3719 } else {
3720 ALOGW("%s: Input buffer should be NULL if there is no input"
3721 " buffer sent in the request, skipping input buffer return.",
3722 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003723 }
3724 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003725}
3726
3727void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003728 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003729 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003730 {
3731 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003732 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003733 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003734
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003735 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003736 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003737 return;
3738 }
3739
3740 switch (msg->type) {
3741 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003742 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003743 break;
3744 }
3745 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003746 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003747 break;
3748 }
3749 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003750 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003751 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003752 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003753}
3754
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003755void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003756 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003757 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003758 // Map camera HAL error codes to ICameraDeviceCallback error codes
3759 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003760 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003761 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003762 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003763 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003764 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003765 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003766 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003767 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003768 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003769 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003770 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003771 };
3772
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003773 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003774 ((msg.error_code >= 0) &&
3775 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3776 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003777 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003778
3779 int streamId = 0;
Emilian Peevedec62d2019-03-19 17:59:24 -07003780 String16 physicalCameraId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003781 if (msg.error_stream != NULL) {
3782 Camera3Stream *stream =
3783 Camera3Stream::cast(msg.error_stream);
3784 streamId = stream->getId();
Emilian Peevedec62d2019-03-19 17:59:24 -07003785 physicalCameraId = String16(stream->physicalCameraId());
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003786 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003787 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3788 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003789 streamId, msg.error_code);
3790
3791 CaptureResultExtras resultExtras;
3792 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003793 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003794 // SET_ERR calls notifyError
3795 SET_ERR("Camera HAL reported serious device error");
3796 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003797 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3798 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3799 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003800 {
3801 Mutex::Autolock l(mInFlightLock);
3802 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3803 if (idx >= 0) {
3804 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3805 r.requestStatus = msg.error_code;
3806 resultExtras = r.resultExtras;
Emilian Peevedec62d2019-03-19 17:59:24 -07003807 bool logicalDeviceResultError = false;
3808 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3809 errorCode) {
3810 if (physicalCameraId.size() > 0) {
3811 String8 cameraId(physicalCameraId);
3812 if (r.physicalCameraIds.find(cameraId) == r.physicalCameraIds.end()) {
3813 ALOGE("%s: Reported result failure for physical camera device: %s "
3814 " which is not part of the respective request!",
3815 __FUNCTION__, cameraId.string());
3816 break;
3817 }
3818 resultExtras.errorPhysicalCameraId = physicalCameraId;
3819 } else {
3820 logicalDeviceResultError = true;
3821 }
3822 }
3823
3824 if (logicalDeviceResultError
Shuzhen Wang20f57342017-08-24 15:39:05 -07003825 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3826 errorCode) {
3827 r.skipResultMetadata = true;
3828 }
Emilian Peevedec62d2019-03-19 17:59:24 -07003829 if (logicalDeviceResultError) {
Emilian Peevba0fac32017-03-30 09:05:34 +01003830 // In case of missing result check whether the buffers
3831 // returned. If they returned, then remove inflight
3832 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003833 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3834 // otherwise we are depending on HAL to send the buffers back after
3835 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003836 removeInFlightRequestIfReadyLocked(idx);
3837 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003838 } else {
3839 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003840 ALOGE("Camera %s: %s: cannot find in-flight request on "
3841 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003842 resultExtras.frameNumber);
3843 }
3844 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003845 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003846 if (listener != NULL) {
3847 listener->notifyError(errorCode, resultExtras);
3848 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003849 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003850 }
3851 break;
3852 default:
3853 // SET_ERR calls notifyError
3854 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3855 break;
3856 }
3857}
3858
3859void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003860 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003861 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003862 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003863
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003864 // Set timestamp for the request in the in-flight tracking
3865 // and get the request ID to send upstream
3866 {
3867 Mutex::Autolock l(mInFlightLock);
3868 idx = mInFlightMap.indexOfKey(msg.frame_number);
3869 if (idx >= 0) {
3870 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003871
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003872 // Verify ordering of shutter notifications
3873 {
3874 Mutex::Autolock l(mOutputLock);
3875 // TODO: need to track errors for tighter bounds on expected frame number.
3876 if (r.hasInputBuffer) {
3877 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3878 SET_ERR("Shutter notification out-of-order. Expected "
3879 "notification for frame %d, got frame %d",
3880 mNextReprocessShutterFrameNumber, msg.frame_number);
3881 return;
3882 }
3883 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3884 } else {
3885 if (msg.frame_number < mNextShutterFrameNumber) {
3886 SET_ERR("Shutter notification out-of-order. Expected "
3887 "notification for frame %d, got frame %d",
3888 mNextShutterFrameNumber, msg.frame_number);
3889 return;
3890 }
3891 mNextShutterFrameNumber = msg.frame_number + 1;
3892 }
3893 }
3894
Shuzhen Wang4a472662017-02-26 23:29:04 -08003895 r.shutterTimestamp = msg.timestamp;
3896 if (r.hasCallback) {
3897 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003898 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003899 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003900 // Call listener, if any
3901 if (listener != NULL) {
3902 listener->notifyShutter(r.resultExtras, msg.timestamp);
3903 }
3904 // send pending result and buffers
3905 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3906 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003907 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003908 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003909 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003910 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003911 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3912 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003913 r.pendingOutputBuffers.clear();
3914
3915 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003916 }
3917 }
3918 if (idx < 0) {
3919 SET_ERR("Shutter notification for non-existent frame number %d",
3920 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003921 }
3922}
3923
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003924CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003925 ALOGV("%s", __FUNCTION__);
3926
Igor Murashkin1e479c02013-09-06 16:55:14 -07003927 CameraMetadata retVal;
3928
3929 if (mRequestThread != NULL) {
3930 retVal = mRequestThread->getLatestRequest();
3931 }
3932
Igor Murashkin1e479c02013-09-06 16:55:14 -07003933 return retVal;
3934}
3935
Jianing Weicb0652e2014-03-12 18:29:36 -07003936
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003937void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3938 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3939 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3940}
3941
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003942/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003943 * HalInterface inner class methods
3944 */
3945
Yifan Hongf79b5542017-04-11 14:44:25 -07003946Camera3Device::HalInterface::HalInterface(
3947 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003948 std::shared_ptr<RequestMetadataQueue> queue,
3949 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003950 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003951 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003952 mUseHalBufManager(useHalBufManager),
3953 mIsReconfigurationQuerySupported(true) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003954 // Check with hardware service manager if we can downcast these interfaces
3955 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003956 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3957 if (castResult_3_5.isOk()) {
3958 mHidlSession_3_5 = castResult_3_5;
3959 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003960 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3961 if (castResult_3_4.isOk()) {
3962 mHidlSession_3_4 = castResult_3_4;
3963 }
3964 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3965 if (castResult_3_3.isOk()) {
3966 mHidlSession_3_3 = castResult_3_3;
3967 }
3968}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003969
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003970Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003971
3972Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003973 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003974 mRequestMetadataQueue(other.mRequestMetadataQueue),
3975 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003976
3977bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003978 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003979}
3980
3981void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00003982 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003983 mHidlSession_3_4.clear();
3984 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003985 mHidlSession.clear();
3986}
3987
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003988bool Camera3Device::HalInterface::supportBatchRequest() {
3989 return mHidlSession != nullptr;
3990}
3991
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003992status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3993 camera3_request_template_t templateId,
3994 /*out*/ camera_metadata_t **requestTemplate) {
3995 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3996 if (!valid()) return INVALID_OPERATION;
3997 status_t res = OK;
3998
Emilian Peev31abd0a2017-05-11 18:37:46 +01003999 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004000
4001 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01004002 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004003 status = s;
4004 if (status == common::V1_0::Status::OK) {
4005 const camera_metadata *r =
4006 reinterpret_cast<const camera_metadata_t*>(request.data());
4007 size_t expectedSize = request.size();
4008 int ret = validate_camera_metadata_structure(r, &expectedSize);
4009 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
4010 *requestTemplate = clone_camera_metadata(r);
4011 if (*requestTemplate == nullptr) {
4012 ALOGE("%s: Unable to clone camera metadata received from HAL",
4013 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004014 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004015 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004016 } else {
4017 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
4018 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004019 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004020 }
4021 };
4022 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004023 RequestTemplate id;
4024 switch (templateId) {
4025 case CAMERA3_TEMPLATE_PREVIEW:
4026 id = RequestTemplate::PREVIEW;
4027 break;
4028 case CAMERA3_TEMPLATE_STILL_CAPTURE:
4029 id = RequestTemplate::STILL_CAPTURE;
4030 break;
4031 case CAMERA3_TEMPLATE_VIDEO_RECORD:
4032 id = RequestTemplate::VIDEO_RECORD;
4033 break;
4034 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
4035 id = RequestTemplate::VIDEO_SNAPSHOT;
4036 break;
4037 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
4038 id = RequestTemplate::ZERO_SHUTTER_LAG;
4039 break;
4040 case CAMERA3_TEMPLATE_MANUAL:
4041 id = RequestTemplate::MANUAL;
4042 break;
4043 default:
4044 // Unknown template ID, or this HAL is too old to support it
4045 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004046 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004047 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004048
Emilian Peev31abd0a2017-05-11 18:37:46 +01004049 if (!err.isOk()) {
4050 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4051 res = DEAD_OBJECT;
4052 } else {
4053 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004054 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004055
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004056 return res;
4057}
4058
Emilian Peev4ec17882019-01-24 17:16:58 -08004059bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4060 CameraMetadata& newSessionParams) {
4061 // We do reconfiguration by default;
4062 bool ret = true;
4063 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4064 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4065 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4066 oldSessionParams.getAndLock());
4067 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4068 newSessionParams.getAndLock());
4069 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4070 get_camera_metadata_size(oldSessioMeta));
4071 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4072 get_camera_metadata_size(newSessioMeta));
4073 hardware::camera::common::V1_0::Status callStatus;
4074 bool required;
4075 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4076 bool requiredFlag) {
4077 callStatus = s;
4078 required = requiredFlag;
4079 };
4080 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4081 oldSessionParams.unlock(oldSessioMeta);
4082 newSessionParams.unlock(newSessioMeta);
4083 if (err.isOk()) {
4084 switch (callStatus) {
4085 case hardware::camera::common::V1_0::Status::OK:
4086 ret = required;
4087 break;
4088 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4089 mIsReconfigurationQuerySupported = false;
4090 ret = true;
4091 break;
4092 default:
4093 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4094 ret = true;
4095 }
4096 } else {
4097 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4098 ret = true;
4099 }
4100 }
4101
4102 return ret;
4103}
4104
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004105status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004106 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004107 ATRACE_NAME("CameraHal::configureStreams");
4108 if (!valid()) return INVALID_OPERATION;
4109 status_t res = OK;
4110
Emilian Peev31abd0a2017-05-11 18:37:46 +01004111 // Convert stream config to HIDL
4112 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004113 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4114 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4115 requestedConfiguration3_2.streams.resize(config->num_streams);
4116 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004117 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004118 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4119 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004120 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004121
Emilian Peev31abd0a2017-05-11 18:37:46 +01004122 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4123 cam3stream->setBufferFreedListener(this);
4124 int streamId = cam3stream->getId();
4125 StreamType streamType;
4126 switch (src->stream_type) {
4127 case CAMERA3_STREAM_OUTPUT:
4128 streamType = StreamType::OUTPUT;
4129 break;
4130 case CAMERA3_STREAM_INPUT:
4131 streamType = StreamType::INPUT;
4132 break;
4133 default:
4134 ALOGE("%s: Stream %d: Unsupported stream type %d",
4135 __FUNCTION__, streamId, config->streams[i]->stream_type);
4136 return BAD_VALUE;
4137 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004138 dst3_2.id = streamId;
4139 dst3_2.streamType = streamType;
4140 dst3_2.width = src->width;
4141 dst3_2.height = src->height;
4142 dst3_2.format = mapToPixelFormat(src->format);
4143 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
4144 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4145 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
4146 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004147 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004148 if (src->physical_camera_id != nullptr) {
4149 dst3_4.physicalCameraId = src->physical_camera_id;
4150 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004151
4152 activeStreams.insert(streamId);
4153 // Create Buffer ID map if necessary
4154 if (mBufferIdMaps.count(streamId) == 0) {
4155 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4156 }
4157 }
4158 // remove BufferIdMap for deleted streams
4159 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4160 int streamId = it->first;
4161 bool active = activeStreams.count(streamId) > 0;
4162 if (!active) {
4163 it = mBufferIdMaps.erase(it);
4164 } else {
4165 ++it;
4166 }
4167 }
4168
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004169 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004170 res = mapToStreamConfigurationMode(
4171 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004172 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004173 if (res != OK) {
4174 return res;
4175 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004176 requestedConfiguration3_2.operationMode = operationMode;
4177 requestedConfiguration3_4.operationMode = operationMode;
4178 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004179 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4180 get_camera_metadata_size(sessionParams));
4181
Emilian Peev31abd0a2017-05-11 18:37:46 +01004182 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004183 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004184 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004185 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004186
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004187 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004188 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4189 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004190 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004191 };
4192
4193 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4194 (hardware::Return<void>& err) -> status_t {
4195 if (!err.isOk()) {
4196 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4197 return DEAD_OBJECT;
4198 }
4199 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4200 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4201 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4202 }
4203 return OK;
4204 };
4205
4206 // See if we have v3.4 or v3.3 HAL
4207 if (mHidlSession_3_5 != nullptr) {
4208 ALOGV("%s: v3.5 device found", __FUNCTION__);
4209 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4210 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4211 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4212 auto err = mHidlSession_3_5->configureStreams_3_5(
4213 requestedConfiguration3_5, configStream34Cb);
4214 res = postprocConfigStream34(err);
4215 if (res != OK) {
4216 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004217 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004218 } else if (mHidlSession_3_4 != nullptr) {
4219 // We do; use v3.4 for the call
4220 ALOGV("%s: v3.4 device found", __FUNCTION__);
4221 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
4222 auto err = mHidlSession_3_4->configureStreams_3_4(
4223 requestedConfiguration3_4, configStream34Cb);
4224 res = postprocConfigStream34(err);
4225 if (res != OK) {
4226 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004227 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004228 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004229 // We do; use v3.3 for the call
4230 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004231 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004232 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004233 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004234 finalConfiguration = halConfiguration;
4235 status = s;
4236 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004237 if (!err.isOk()) {
4238 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4239 return DEAD_OBJECT;
4240 }
4241 } else {
4242 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4243 ALOGV("%s: v3.2 device found", __FUNCTION__);
4244 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004245 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004246 [&status, &finalConfiguration_3_2]
4247 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4248 finalConfiguration_3_2 = halConfiguration;
4249 status = s;
4250 });
4251 if (!err.isOk()) {
4252 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4253 return DEAD_OBJECT;
4254 }
4255 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4256 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4257 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4258 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004259 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004260 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004261 }
4262
4263 if (status != common::V1_0::Status::OK ) {
4264 return CameraProviderManager::mapToStatusT(status);
4265 }
4266
4267 // And convert output stream configuration from HIDL
4268
4269 for (size_t i = 0; i < config->num_streams; i++) {
4270 camera3_stream_t *dst = config->streams[i];
4271 int streamId = Camera3Stream::cast(dst)->getId();
4272
4273 // Start scan at i, with the assumption that the stream order matches
4274 size_t realIdx = i;
4275 bool found = false;
4276 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004277 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004278 found = true;
4279 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004280 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004281 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4282 }
4283 if (!found) {
4284 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4285 __FUNCTION__, streamId);
4286 return INVALID_OPERATION;
4287 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004288 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004289
Emilian Peev710c1422017-08-30 11:19:38 +01004290 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4291 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004292 dstStream->setDataSpaceOverride(false);
4293 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4294 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4295
Emilian Peev31abd0a2017-05-11 18:37:46 +01004296 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4297 if (dst->format != overrideFormat) {
4298 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4299 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004300 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004301 if (dst->data_space != overrideDataSpace) {
4302 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4303 streamId, dst->format);
4304 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004305 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004306 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004307 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4308
Emilian Peev31abd0a2017-05-11 18:37:46 +01004309 // Override allowed with IMPLEMENTATION_DEFINED
4310 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004311 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004312 }
4313
Emilian Peev31abd0a2017-05-11 18:37:46 +01004314 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004315 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004316 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004317 __FUNCTION__, streamId);
4318 return INVALID_OPERATION;
4319 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004320 dstStream->setUsage(
4321 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004322 } else {
4323 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004324 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004325 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4326 __FUNCTION__, streamId);
4327 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004328 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004329 dstStream->setUsage(
4330 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004331 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004332 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004333 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004334
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004335 return res;
4336}
4337
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004338status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004339 /*out*/device::V3_2::CaptureRequest* captureRequest,
4340 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004341 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004342 if (captureRequest == nullptr || handlesCreated == nullptr) {
4343 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4344 __FUNCTION__, captureRequest, handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004345 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004346 }
4347
4348 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004349
4350 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004351
4352 {
4353 std::lock_guard<std::mutex> lock(mInflightLock);
4354 if (request->input_buffer != nullptr) {
4355 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4356 buffer_handle_t buf = *(request->input_buffer->buffer);
4357 auto pair = getBufferId(buf, streamId);
4358 bool isNewBuffer = pair.first;
4359 uint64_t bufferId = pair.second;
4360 captureRequest->inputBuffer.streamId = streamId;
4361 captureRequest->inputBuffer.bufferId = bufferId;
4362 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4363 captureRequest->inputBuffer.status = BufferStatus::OK;
4364 native_handle_t *acquireFence = nullptr;
4365 if (request->input_buffer->acquire_fence != -1) {
4366 acquireFence = native_handle_create(1,0);
4367 acquireFence->data[0] = request->input_buffer->acquire_fence;
4368 handlesCreated->push_back(acquireFence);
4369 }
4370 captureRequest->inputBuffer.acquireFence = acquireFence;
4371 captureRequest->inputBuffer.releaseFence = nullptr;
4372
4373 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4374 request->input_buffer->buffer,
4375 request->input_buffer->acquire_fence);
4376 } else {
4377 captureRequest->inputBuffer.streamId = -1;
4378 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4379 }
4380
4381 captureRequest->outputBuffers.resize(request->num_output_buffers);
4382 for (size_t i = 0; i < request->num_output_buffers; i++) {
4383 const camera3_stream_buffer_t *src = request->output_buffers + i;
4384 StreamBuffer &dst = captureRequest->outputBuffers[i];
4385 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004386 if (src->buffer != nullptr) {
4387 buffer_handle_t buf = *(src->buffer);
4388 auto pair = getBufferId(buf, streamId);
4389 bool isNewBuffer = pair.first;
4390 dst.bufferId = pair.second;
4391 dst.buffer = isNewBuffer ? buf : nullptr;
4392 native_handle_t *acquireFence = nullptr;
4393 if (src->acquire_fence != -1) {
4394 acquireFence = native_handle_create(1,0);
4395 acquireFence->data[0] = src->acquire_fence;
4396 handlesCreated->push_back(acquireFence);
4397 }
4398 dst.acquireFence = acquireFence;
4399 } else if (mUseHalBufManager) {
4400 // HAL buffer management path
4401 dst.bufferId = BUFFER_ID_NO_BUFFER;
4402 dst.buffer = nullptr;
4403 dst.acquireFence = nullptr;
4404 } else {
4405 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4406 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004407 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004408 dst.streamId = streamId;
4409 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004410 dst.releaseFence = nullptr;
4411
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004412 // Output buffers are empty when using HAL buffer manager
4413 if (!mUseHalBufManager) {
4414 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4415 src->buffer, src->acquire_fence);
4416 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004417 }
4418 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004419 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004420}
4421
4422status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4423 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4424 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4425 if (!valid()) return INVALID_OPERATION;
4426
Emilian Peevaebbe412018-01-15 13:53:24 +00004427 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4428 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4429 if (castResult_3_4.isOk()) {
4430 hidlSession_3_4 = castResult_3_4;
4431 }
4432
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004433 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004434 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004435 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004436 if (hidlSession_3_4 != nullptr) {
4437 captureRequests_3_4.resize(batchSize);
4438 } else {
4439 captureRequests.resize(batchSize);
4440 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004441 std::vector<native_handle_t*> handlesCreated;
4442
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004443 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004444 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004445 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004446 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Emilian Peevaebbe412018-01-15 13:53:24 +00004447 /*out*/&handlesCreated);
4448 } else {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004449 res = wrapAsHidlRequest(requests[i],
4450 /*out*/&captureRequests[i], /*out*/&handlesCreated);
4451 }
4452 if (res != OK) {
4453 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004454 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004455 }
4456
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004457 std::vector<device::V3_2::BufferCache> cachesToRemove;
4458 {
4459 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4460 for (auto& pair : mFreedBuffers) {
4461 // The stream might have been removed since onBufferFreed
4462 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4463 cachesToRemove.push_back({pair.first, pair.second});
4464 }
4465 }
4466 mFreedBuffers.clear();
4467 }
4468
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004469 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4470 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004471
4472 // Write metadata to FMQ.
4473 for (size_t i = 0; i < batchSize; i++) {
4474 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004475 device::V3_2::CaptureRequest* captureRequest;
4476 if (hidlSession_3_4 != nullptr) {
4477 captureRequest = &captureRequests_3_4[i].v3_2;
4478 } else {
4479 captureRequest = &captureRequests[i];
4480 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004481
4482 if (request->settings != nullptr) {
4483 size_t settingsSize = get_camera_metadata_size(request->settings);
4484 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4485 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4486 captureRequest->settings.resize(0);
4487 captureRequest->fmqSettingsSize = settingsSize;
4488 } else {
4489 if (mRequestMetadataQueue != nullptr) {
4490 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4491 }
4492 captureRequest->settings.setToExternal(
4493 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4494 get_camera_metadata_size(request->settings));
4495 captureRequest->fmqSettingsSize = 0u;
4496 }
4497 } else {
4498 // A null request settings maps to a size-0 CameraMetadata
4499 captureRequest->settings.resize(0);
4500 captureRequest->fmqSettingsSize = 0u;
4501 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004502
4503 if (hidlSession_3_4 != nullptr) {
4504 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4505 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004506 if (request->physcam_settings != nullptr) {
4507 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4508 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4509 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4510 settingsSize)) {
4511 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4512 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4513 settingsSize;
4514 } else {
4515 if (mRequestMetadataQueue != nullptr) {
4516 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4517 }
4518 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4519 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4520 request->physcam_settings[j])),
4521 get_camera_metadata_size(request->physcam_settings[j]));
4522 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004523 }
Emilian Peev00420d22018-02-05 21:33:13 +00004524 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004525 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004526 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004527 }
4528 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4529 request->physcam_id[j];
4530 }
4531 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004532 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004533
4534 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004535 auto resultCallback =
4536 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4537 status = s;
4538 *numRequestProcessed = n;
4539 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004540 if (hidlSession_3_4 != nullptr) {
4541 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004542 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004543 } else {
4544 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004545 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004546 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004547 if (!err.isOk()) {
4548 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4549 return DEAD_OBJECT;
4550 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004551 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4552 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4553 __FUNCTION__, *numRequestProcessed, batchSize);
4554 status = common::V1_0::Status::INTERNAL_ERROR;
4555 }
4556
4557 for (auto& handle : handlesCreated) {
4558 native_handle_delete(handle);
4559 }
4560 return CameraProviderManager::mapToStatusT(status);
4561}
4562
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004563status_t Camera3Device::HalInterface::processCaptureRequest(
4564 camera3_capture_request_t *request) {
4565 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004566 if (!valid()) return INVALID_OPERATION;
4567 status_t res = OK;
4568
Emilian Peev31abd0a2017-05-11 18:37:46 +01004569 uint32_t numRequestProcessed = 0;
4570 std::vector<camera3_capture_request_t*> requests(1);
4571 requests[0] = request;
4572 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4573
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004574 return res;
4575}
4576
4577status_t Camera3Device::HalInterface::flush() {
4578 ATRACE_NAME("CameraHal::flush");
4579 if (!valid()) return INVALID_OPERATION;
4580 status_t res = OK;
4581
Emilian Peev31abd0a2017-05-11 18:37:46 +01004582 auto err = mHidlSession->flush();
4583 if (!err.isOk()) {
4584 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4585 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004586 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004587 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004588 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004589
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004590 return res;
4591}
4592
Emilian Peev31abd0a2017-05-11 18:37:46 +01004593status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004594 ATRACE_NAME("CameraHal::dump");
4595 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004596
Emilian Peev31abd0a2017-05-11 18:37:46 +01004597 // Handled by CameraProviderManager::dump
4598
4599 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004600}
4601
4602status_t Camera3Device::HalInterface::close() {
4603 ATRACE_NAME("CameraHal::close()");
4604 if (!valid()) return INVALID_OPERATION;
4605 status_t res = OK;
4606
Emilian Peev31abd0a2017-05-11 18:37:46 +01004607 auto err = mHidlSession->close();
4608 // Interface will be dead shortly anyway, so don't log errors
4609 if (!err.isOk()) {
4610 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004611 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004612
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004613 return res;
4614}
4615
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004616void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4617 ATRACE_NAME("CameraHal::signalPipelineDrain");
4618 if (!valid() || mHidlSession_3_5 == nullptr) {
4619 ALOGE("%s called on invalid camera!", __FUNCTION__);
4620 return;
4621 }
4622
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004623 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004624 if (!err.isOk()) {
4625 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4626 return;
4627 }
4628}
4629
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004630void Camera3Device::HalInterface::getInflightBufferKeys(
4631 std::vector<std::pair<int32_t, int32_t>>* out) {
4632 std::lock_guard<std::mutex> lock(mInflightLock);
4633 out->clear();
4634 out->reserve(mInflightBufferMap.size());
4635 for (auto& pair : mInflightBufferMap) {
4636 uint64_t key = pair.first;
4637 int32_t streamId = key & 0xFFFFFFFF;
4638 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4639 out->push_back(std::make_pair(frameNumber, streamId));
4640 }
4641 return;
4642}
4643
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004644void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4645 std::vector<uint64_t>* out) {
4646 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4647 out->clear();
4648 out->reserve(mRequestedBuffers.size());
4649 for (auto& pair : mRequestedBuffers) {
4650 out->push_back(pair.first);
4651 }
4652 return;
4653}
4654
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004655status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004656 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004657 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004658 auto pair = std::make_pair(buffer, acquireFence);
4659 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004660 return OK;
4661}
4662
4663status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004664 int32_t frameNumber, int32_t streamId,
4665 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004666 std::lock_guard<std::mutex> lock(mInflightLock);
4667
4668 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4669 auto it = mInflightBufferMap.find(key);
4670 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004671 auto pair = it->second;
4672 *buffer = pair.first;
4673 int acquireFence = pair.second;
4674 if (acquireFence > 0) {
4675 ::close(acquireFence);
4676 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004677 mInflightBufferMap.erase(it);
4678 return OK;
4679}
4680
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004681status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004682 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004683 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004684 auto pair = mRequestedBuffers.insert({bufferId, {streamId, buf}});
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004685 if (!pair.second) {
4686 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4687 __FUNCTION__, bufferId);
4688 return BAD_VALUE;
4689 }
4690 return OK;
4691}
4692
4693// Find and pop a buffer_handle_t based on bufferId
4694status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004695 uint64_t bufferId,
4696 /*out*/ buffer_handle_t** buffer,
4697 /*optional out*/ int32_t* streamId) {
4698 if (buffer == nullptr) {
4699 ALOGE("%s: buffer (%p) must not be null", __FUNCTION__, buffer);
4700 return BAD_VALUE;
4701 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004702 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4703 auto it = mRequestedBuffers.find(bufferId);
4704 if (it == mRequestedBuffers.end()) {
4705 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4706 __FUNCTION__, bufferId);
4707 return BAD_VALUE;
4708 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004709 *buffer = it->second.second;
4710 if (streamId != nullptr) {
4711 *streamId = it->second.first;
4712 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004713 mRequestedBuffers.erase(it);
4714 return OK;
4715}
4716
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004717std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4718 const buffer_handle_t& buf, int streamId) {
4719 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4720
4721 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4722 auto it = bIdMap.find(buf);
4723 if (it == bIdMap.end()) {
4724 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004725 ALOGV("stream %d now have %zu buffer caches, buf %p",
4726 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004727 return std::make_pair(true, mNextBufferId - 1);
4728 } else {
4729 return std::make_pair(false, it->second);
4730 }
4731}
4732
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004733void Camera3Device::HalInterface::onBufferFreed(
4734 int streamId, const native_handle_t* handle) {
4735 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4736 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4737 auto mapIt = mBufferIdMaps.find(streamId);
4738 if (mapIt == mBufferIdMaps.end()) {
4739 // streamId might be from a deleted stream here
4740 ALOGI("%s: stream %d has been removed",
4741 __FUNCTION__, streamId);
4742 return;
4743 }
4744 BufferIdMap& bIdMap = mapIt->second;
4745 auto it = bIdMap.find(handle);
4746 if (it == bIdMap.end()) {
4747 ALOGW("%s: cannot find buffer %p in stream %d",
4748 __FUNCTION__, handle, streamId);
4749 return;
4750 } else {
4751 bufferId = it->second;
4752 bIdMap.erase(it);
4753 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4754 __FUNCTION__, streamId, bIdMap.size(), handle);
4755 }
4756 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4757}
4758
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004759/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004760 * RequestThread inner class methods
4761 */
4762
4763Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004764 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004765 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4766 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004767 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004768 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004769 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004770 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004771 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004772 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004773 mReconfigured(false),
4774 mDoPause(false),
4775 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004776 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004777 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004778 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004779 mCurrentAfTriggerId(0),
4780 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004781 mRepeatingLastFrameNumber(
4782 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004783 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004784 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004785 mRequestLatency(kRequestLatencyBinSize),
4786 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004787 mLatestSessionParams(sessionParamKeys.size()),
4788 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004789 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004790}
4791
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004792Camera3Device::RequestThread::~RequestThread() {}
4793
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004794void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004795 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004796 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004797 Mutex::Autolock l(mRequestLock);
4798 mListener = listener;
4799}
4800
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004801void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4802 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004803 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004804 Mutex::Autolock l(mRequestLock);
4805 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004806 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004807 // Prepare video stream for high speed recording.
4808 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004809 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004810}
4811
Jianing Wei90e59c92014-03-12 18:29:36 -07004812status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004813 List<sp<CaptureRequest> > &requests,
4814 /*out*/
4815 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004816 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004817 Mutex::Autolock l(mRequestLock);
4818 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4819 ++it) {
4820 mRequestQueue.push_back(*it);
4821 }
4822
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004823 if (lastFrameNumber != NULL) {
4824 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4825 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4826 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4827 *lastFrameNumber);
4828 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004829
Jianing Wei90e59c92014-03-12 18:29:36 -07004830 unpauseForNewRequests();
4831
4832 return OK;
4833}
4834
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004835
4836status_t Camera3Device::RequestThread::queueTrigger(
4837 RequestTrigger trigger[],
4838 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004839 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004840 Mutex::Autolock l(mTriggerMutex);
4841 status_t ret;
4842
4843 for (size_t i = 0; i < count; ++i) {
4844 ret = queueTriggerLocked(trigger[i]);
4845
4846 if (ret != OK) {
4847 return ret;
4848 }
4849 }
4850
4851 return OK;
4852}
4853
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004854const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4855 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004856 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004857 if (d != nullptr) return d->mId;
4858 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004859}
4860
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004861status_t Camera3Device::RequestThread::queueTriggerLocked(
4862 RequestTrigger trigger) {
4863
4864 uint32_t tag = trigger.metadataTag;
4865 ssize_t index = mTriggerMap.indexOfKey(tag);
4866
4867 switch (trigger.getTagType()) {
4868 case TYPE_BYTE:
4869 // fall-through
4870 case TYPE_INT32:
4871 break;
4872 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004873 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4874 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004875 return INVALID_OPERATION;
4876 }
4877
4878 /**
4879 * Collect only the latest trigger, since we only have 1 field
4880 * in the request settings per trigger tag, and can't send more than 1
4881 * trigger per request.
4882 */
4883 if (index != NAME_NOT_FOUND) {
4884 mTriggerMap.editValueAt(index) = trigger;
4885 } else {
4886 mTriggerMap.add(tag, trigger);
4887 }
4888
4889 return OK;
4890}
4891
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004892status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004893 const RequestList &requests,
4894 /*out*/
4895 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004896 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004897 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004898 if (lastFrameNumber != NULL) {
4899 *lastFrameNumber = mRepeatingLastFrameNumber;
4900 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004901 mRepeatingRequests.clear();
4902 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4903 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004904
4905 unpauseForNewRequests();
4906
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004907 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004908 return OK;
4909}
4910
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004911bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004912 if (mRepeatingRequests.empty()) {
4913 return false;
4914 }
4915 int32_t requestId = requestIn->mResultExtras.requestId;
4916 const RequestList &repeatRequests = mRepeatingRequests;
4917 // All repeating requests are guaranteed to have same id so only check first quest
4918 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4919 return (firstRequest->mResultExtras.requestId == requestId);
4920}
4921
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004922status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004923 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004924 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004925 return clearRepeatingRequestsLocked(lastFrameNumber);
4926
4927}
4928
4929status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004930 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004931 if (lastFrameNumber != NULL) {
4932 *lastFrameNumber = mRepeatingLastFrameNumber;
4933 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004934 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004935 return OK;
4936}
4937
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004938status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004939 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004940 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004941 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004942 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004943
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004944 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004945
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004946 // Send errors for all requests pending in the request queue, including
4947 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004948 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004949 if (listener != NULL) {
4950 for (RequestList::iterator it = mRequestQueue.begin();
4951 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004952 // Abort the input buffers for reprocess requests.
4953 if ((*it)->mInputStream != NULL) {
4954 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004955 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4956 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004957 if (res != OK) {
4958 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4959 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4960 } else {
4961 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4962 if (res != OK) {
4963 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4964 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4965 }
4966 }
4967 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004968 // Set the frame number this request would have had, if it
4969 // had been submitted; this frame number will not be reused.
4970 // The requestId and burstId fields were set when the request was
4971 // submitted originally (in convertMetadataListToRequestListLocked)
4972 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004973 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004974 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004975 }
4976 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004977 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004978
4979 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004980 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004981 if (lastFrameNumber != NULL) {
4982 *lastFrameNumber = mRepeatingLastFrameNumber;
4983 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004984 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004985 return OK;
4986}
4987
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004988status_t Camera3Device::RequestThread::flush() {
4989 ATRACE_CALL();
4990 Mutex::Autolock l(mFlushLock);
4991
Emilian Peev08dd2452017-04-06 16:55:14 +01004992 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004993}
4994
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004995void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004996 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004997 Mutex::Autolock l(mPauseLock);
4998 mDoPause = paused;
4999 mDoPauseSignal.signal();
5000}
5001
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005002status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
5003 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005004 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005005 Mutex::Autolock l(mLatestRequestMutex);
5006 status_t res;
5007 while (mLatestRequestId != requestId) {
5008 nsecs_t startTime = systemTime();
5009
5010 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
5011 if (res != OK) return res;
5012
5013 timeout -= (systemTime() - startTime);
5014 }
5015
5016 return OK;
5017}
5018
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005019void Camera3Device::RequestThread::requestExit() {
5020 // Call parent to set up shutdown
5021 Thread::requestExit();
5022 // The exit from any possible waits
5023 mDoPauseSignal.signal();
5024 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07005025
5026 mRequestLatency.log("ProcessCaptureRequest latency histogram");
5027 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005028}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005029
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005030void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005031 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005032 bool surfaceAbandoned = false;
5033 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005034 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005035 {
5036 Mutex::Autolock l(mRequestLock);
5037 // Check all streams needed by repeating requests are still valid. Otherwise, stop
5038 // repeating requests.
5039 for (const auto& request : mRepeatingRequests) {
5040 for (const auto& s : request->mOutputStreams) {
5041 if (s->isAbandoned()) {
5042 surfaceAbandoned = true;
5043 clearRepeatingRequestsLocked(&lastFrameNumber);
5044 break;
5045 }
5046 }
5047 if (surfaceAbandoned) {
5048 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005049 }
5050 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005051 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005052 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005053
5054 if (listener != NULL && surfaceAbandoned) {
5055 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005056 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005057}
5058
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005059bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005060 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005061 status_t res;
5062 size_t batchSize = mNextRequests.size();
5063 std::vector<camera3_capture_request_t*> requests(batchSize);
5064 uint32_t numRequestProcessed = 0;
5065 for (size_t i = 0; i < batchSize; i++) {
5066 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07005067 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005068 }
5069
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005070 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
5071
5072 bool triggerRemoveFailed = false;
5073 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
5074 for (size_t i = 0; i < numRequestProcessed; i++) {
5075 NextRequest& nextRequest = mNextRequests.editItemAt(i);
5076 nextRequest.submitted = true;
5077
5078
5079 // Update the latest request sent to HAL
5080 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5081 Mutex::Autolock al(mLatestRequestMutex);
5082
5083 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5084 mLatestRequest.acquire(cloned);
5085
5086 sp<Camera3Device> parent = mParent.promote();
5087 if (parent != NULL) {
5088 parent->monitorMetadata(TagMonitor::REQUEST,
5089 nextRequest.halRequest.frame_number,
5090 0, mLatestRequest);
5091 }
5092 }
5093
5094 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005095 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5096 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005097 }
5098
Emilian Peevaebbe412018-01-15 13:53:24 +00005099 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5100
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005101 if (!triggerRemoveFailed) {
5102 // Remove any previously queued triggers (after unlock)
5103 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5104 if (removeTriggerRes != OK) {
5105 triggerRemoveFailed = true;
5106 triggerFailedRequest = nextRequest;
5107 }
5108 }
5109 }
5110
5111 if (triggerRemoveFailed) {
5112 SET_ERR("RequestThread: Unable to remove triggers "
5113 "(capture request %d, HAL device: %s (%d)",
5114 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5115 cleanUpFailedRequests(/*sendRequestError*/ false);
5116 return false;
5117 }
5118
5119 if (res != OK) {
5120 // Should only get a failure here for malformed requests or device-level
5121 // errors, so consider all errors fatal. Bad metadata failures should
5122 // come through notify.
5123 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5124 mNextRequests[numRequestProcessed].halRequest.frame_number,
5125 strerror(-res), res);
5126 cleanUpFailedRequests(/*sendRequestError*/ false);
5127 return false;
5128 }
5129 return true;
5130}
5131
5132bool Camera3Device::RequestThread::sendRequestsOneByOne() {
5133 status_t res;
5134
5135 for (auto& nextRequest : mNextRequests) {
5136 // Submit request and block until ready for next one
5137 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
5138 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
5139
5140 if (res != OK) {
5141 // Should only get a failure here for malformed requests or device-level
5142 // errors, so consider all errors fatal. Bad metadata failures should
5143 // come through notify.
5144 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
5145 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
5146 res);
5147 cleanUpFailedRequests(/*sendRequestError*/ false);
5148 return false;
5149 }
5150
5151 // Mark that the request has be submitted successfully.
5152 nextRequest.submitted = true;
5153
5154 // Update the latest request sent to HAL
5155 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5156 Mutex::Autolock al(mLatestRequestMutex);
5157
5158 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5159 mLatestRequest.acquire(cloned);
5160
5161 sp<Camera3Device> parent = mParent.promote();
5162 if (parent != NULL) {
5163 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
5164 0, mLatestRequest);
5165 }
5166 }
5167
5168 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005169 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5170 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005171 }
5172
Emilian Peevaebbe412018-01-15 13:53:24 +00005173 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5174
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005175 // Remove any previously queued triggers (after unlock)
5176 res = removeTriggers(mPrevRequest);
5177 if (res != OK) {
5178 SET_ERR("RequestThread: Unable to remove triggers "
5179 "(capture request %d, HAL device: %s (%d)",
5180 nextRequest.halRequest.frame_number, strerror(-res), res);
5181 cleanUpFailedRequests(/*sendRequestError*/ false);
5182 return false;
5183 }
5184 }
5185 return true;
5186}
5187
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005188nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5189 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5190 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5191 find_camera_metadata_ro_entry(request,
5192 ANDROID_CONTROL_AE_MODE,
5193 &e);
5194 if (e.count == 0) return maxExpectedDuration;
5195
5196 switch (e.data.u8[0]) {
5197 case ANDROID_CONTROL_AE_MODE_OFF:
5198 find_camera_metadata_ro_entry(request,
5199 ANDROID_SENSOR_EXPOSURE_TIME,
5200 &e);
5201 if (e.count > 0) {
5202 maxExpectedDuration = e.data.i64[0];
5203 }
5204 find_camera_metadata_ro_entry(request,
5205 ANDROID_SENSOR_FRAME_DURATION,
5206 &e);
5207 if (e.count > 0) {
5208 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5209 }
5210 break;
5211 default:
5212 find_camera_metadata_ro_entry(request,
5213 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5214 &e);
5215 if (e.count > 1) {
5216 maxExpectedDuration = 1e9 / e.data.u8[0];
5217 }
5218 break;
5219 }
5220
5221 return maxExpectedDuration;
5222}
5223
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005224bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5225 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5226 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5227 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5228 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5229 return true;
5230 }
5231
5232 return false;
5233}
5234
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005235bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5236 ATRACE_CALL();
5237 bool updatesDetected = false;
5238
Emilian Peev4ec17882019-01-24 17:16:58 -08005239 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005240 for (auto tag : mSessionParamKeys) {
5241 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005242 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005243
5244 if (entry.count > 0) {
5245 bool isDifferent = false;
5246 if (lastEntry.count > 0) {
5247 // Have a last value, compare to see if changed
5248 if (lastEntry.type == entry.type &&
5249 lastEntry.count == entry.count) {
5250 // Same type and count, compare values
5251 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5252 size_t entryBytes = bytesPerValue * lastEntry.count;
5253 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5254 if (cmp != 0) {
5255 isDifferent = true;
5256 }
5257 } else {
5258 // Count or type has changed
5259 isDifferent = true;
5260 }
5261 } else {
5262 // No last entry, so always consider to be different
5263 isDifferent = true;
5264 }
5265
5266 if (isDifferent) {
5267 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005268 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5269 updatesDetected = true;
5270 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005271 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005272 }
5273 } else if (lastEntry.count > 0) {
5274 // Value has been removed
5275 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005276 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005277 updatesDetected = true;
5278 }
5279 }
5280
Emilian Peev4ec17882019-01-24 17:16:58 -08005281 bool reconfigureRequired;
5282 if (updatesDetected) {
5283 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5284 updatedParams);
5285 mLatestSessionParams = updatedParams;
5286 } else {
5287 reconfigureRequired = false;
5288 }
5289
5290 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005291}
5292
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005293bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005294 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005295 status_t res;
5296
5297 // Handle paused state.
5298 if (waitIfPaused()) {
5299 return true;
5300 }
5301
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005302 // Wait for the next batch of requests.
5303 waitForNextRequestBatch();
5304 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005305 return true;
5306 }
5307
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005308 // Get the latest request ID, if any
5309 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005310 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005311 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005312 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005313 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005314 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005315 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5316 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005317 }
5318
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005319 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5320 // or a single request from streaming or burst. In either case the first element
5321 // should contain the latest camera settings that we need to check for any session
5322 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005323 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005324 res = OK;
5325
5326 //Input stream buffers are already acquired at this point so an input stream
5327 //will not be able to move to idle state unless we force it.
5328 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5329 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5330 if (res != OK) {
5331 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5332 cleanUpFailedRequests(/*sendRequestError*/ false);
5333 return false;
5334 }
5335 }
5336
5337 if (res == OK) {
5338 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5339 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005340 sp<Camera3Device> parent = mParent.promote();
5341 if (parent != nullptr) {
5342 parent->pauseStateNotify(true);
5343 }
5344
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005345 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5346
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005347 if (parent != nullptr) {
5348 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5349 }
5350
5351 statusTracker->markComponentActive(mStatusId);
5352 setPaused(false);
5353 }
5354
5355 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5356 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5357 if (res != OK) {
5358 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5359 cleanUpFailedRequests(/*sendRequestError*/ false);
5360 return false;
5361 }
5362 }
5363 }
5364 }
5365
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005366 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005367 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005368 if (res == TIMED_OUT) {
5369 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005370 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005371 // Check if any stream is abandoned.
5372 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005373 return true;
5374 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005375 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005376 return false;
5377 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005378
Zhijun Hecc27e112013-10-03 16:12:43 -07005379 // Inform waitUntilRequestProcessed thread of a new request ID
5380 {
5381 Mutex::Autolock al(mLatestRequestMutex);
5382
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005383 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005384 mLatestRequestSignal.signal();
5385 }
5386
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005387 // Submit a batch of requests to HAL.
5388 // Use flush lock only when submitting multilple requests in a batch.
5389 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5390 // which may take a long time to finish so synchronizing flush() and
5391 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5392 // For now, only synchronize for high speed recording and we should figure something out for
5393 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005394 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005395
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005396 if (useFlushLock) {
5397 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005398 }
5399
Zhijun Hef0645c12016-08-02 00:58:11 -07005400 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005401 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005402
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005403 sp<Camera3Device> parent = mParent.promote();
5404 if (parent != nullptr) {
5405 parent->mRequestBufferSM.onSubmittingRequest();
5406 }
5407
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005408 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005409 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005410 if (mInterface->supportBatchRequest()) {
5411 submitRequestSuccess = sendRequestsBatch();
5412 } else {
5413 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005414 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005415 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5416 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005417
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005418 if (useFlushLock) {
5419 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005420 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005421
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005422 // Unset as current request
5423 {
5424 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005425 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005426 }
5427
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005428 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005429}
5430
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005431status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005432 ATRACE_CALL();
5433
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005434 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005435 for (size_t i = 0; i < mNextRequests.size(); i++) {
5436 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005437 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5438 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5439 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5440
5441 // Prepare a request to HAL
5442 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5443
5444 // Insert any queued triggers (before metadata is locked)
5445 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005446 if (res < 0) {
5447 SET_ERR("RequestThread: Unable to insert triggers "
5448 "(capture request %d, HAL device: %s (%d)",
5449 halRequest->frame_number, strerror(-res), res);
5450 return INVALID_OPERATION;
5451 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005452
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005453 int triggerCount = res;
5454 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5455 mPrevTriggers = triggerCount;
5456
5457 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005458 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5459 // Request settings are all the same within one batch, so only treat the first
5460 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005461 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005462 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005463 /**
5464 * HAL workaround:
5465 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5466 */
5467 res = addDummyTriggerIds(captureRequest);
5468 if (res != OK) {
5469 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5470 "(capture request %d, HAL device: %s (%d)",
5471 halRequest->frame_number, strerror(-res), res);
5472 return INVALID_OPERATION;
5473 }
5474
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005475 {
5476 // Correct metadata regions for distortion correction if enabled
5477 sp<Camera3Device> parent = mParent.promote();
5478 if (parent != nullptr) {
5479 res = parent->mDistortionMapper.correctCaptureRequest(
5480 &(captureRequest->mSettingsList.begin()->metadata));
5481 if (res != OK) {
5482 SET_ERR("RequestThread: Unable to correct capture requests "
5483 "for lens distortion for request %d: %s (%d)",
5484 halRequest->frame_number, strerror(-res), res);
5485 return INVALID_OPERATION;
5486 }
5487 }
5488 }
5489
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005490 /**
5491 * The request should be presorted so accesses in HAL
5492 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5493 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005494 captureRequest->mSettingsList.begin()->metadata.sort();
5495 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005496 mPrevRequest = captureRequest;
5497 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5498
5499 IF_ALOGV() {
5500 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5501 find_camera_metadata_ro_entry(
5502 halRequest->settings,
5503 ANDROID_CONTROL_AF_TRIGGER,
5504 &e
5505 );
5506 if (e.count > 0) {
5507 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5508 __FUNCTION__,
5509 halRequest->frame_number,
5510 e.data.u8[0]);
5511 }
5512 }
5513 } else {
5514 // leave request.settings NULL to indicate 'reuse latest given'
5515 ALOGVV("%s: Request settings are REUSED",
5516 __FUNCTION__);
5517 }
5518
Emilian Peevaebbe412018-01-15 13:53:24 +00005519 if (captureRequest->mSettingsList.size() > 1) {
5520 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5521 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005522 if (newRequest) {
5523 halRequest->physcam_settings =
5524 new const camera_metadata* [halRequest->num_physcam_settings];
5525 } else {
5526 halRequest->physcam_settings = nullptr;
5527 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005528 auto it = ++captureRequest->mSettingsList.begin();
5529 size_t i = 0;
5530 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5531 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005532 if (newRequest) {
5533 it->metadata.sort();
5534 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5535 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005536 }
5537 }
5538
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005539 uint32_t totalNumBuffers = 0;
5540
5541 // Fill in buffers
5542 if (captureRequest->mInputStream != NULL) {
5543 halRequest->input_buffer = &captureRequest->mInputBuffer;
5544 totalNumBuffers += 1;
5545 } else {
5546 halRequest->input_buffer = NULL;
5547 }
5548
5549 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5550 captureRequest->mOutputStreams.size());
5551 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005552 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005553
5554 sp<Camera3Device> parent = mParent.promote();
5555 if (parent == NULL) {
5556 // Should not happen, and nowhere to send errors to, so just log it
5557 CLOGE("RequestThread: Parent is gone");
5558 return INVALID_OPERATION;
5559 }
5560 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5561
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005562 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005563 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005564 sp<Camera3OutputStreamInterface> outputStream =
5565 captureRequest->mOutputStreams.editItemAt(j);
5566 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005567
5568 // Prepare video buffers for high speed recording on the first video request.
5569 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5570 // Only try to prepare video stream on the first video request.
5571 mPrepareVideoStream = false;
5572
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005573 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5574 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005575 while (res == NOT_ENOUGH_DATA) {
5576 res = outputStream->prepareNextBuffer();
5577 }
5578 if (res != OK) {
5579 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5580 __FUNCTION__, strerror(-res), res);
5581 outputStream->cancelPrepare();
5582 }
5583 }
5584
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005585 std::vector<size_t> uniqueSurfaceIds;
5586 res = outputStream->getUniqueSurfaceIds(
5587 captureRequest->mOutputSurfaces[streamId],
5588 &uniqueSurfaceIds);
5589 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5590 if (res != OK && res != INVALID_OPERATION) {
5591 ALOGE("%s: failed to query stream %d unique surface IDs",
5592 __FUNCTION__, streamId);
5593 return res;
5594 }
5595 if (res == OK) {
5596 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5597 }
5598
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005599 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005600 if (outputStream->isAbandoned()) {
5601 ALOGE("%s: stream %d is abandoned.", __FUNCTION__, streamId);
5602 return TIMED_OUT;
5603 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005604 // HAL will request buffer through requestStreamBuffer API
5605 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5606 buffer.stream = outputStream->asHalStream();
5607 buffer.buffer = nullptr;
5608 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5609 buffer.acquire_fence = -1;
5610 buffer.release_fence = -1;
5611 } else {
5612 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5613 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005614 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005615 if (res != OK) {
5616 // Can't get output buffer from gralloc queue - this could be due to
5617 // abandoned queue or other consumer misbehavior, so not a fatal
5618 // error
5619 ALOGE("RequestThread: Can't get output buffer, skipping request:"
5620 " %s (%d)", strerror(-res), res);
5621
5622 return TIMED_OUT;
5623 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005624 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005625
5626 {
5627 sp<Camera3Device> parent = mParent.promote();
5628 if (parent != nullptr) {
5629 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5630 for (const auto& settings : captureRequest->mSettingsList) {
5631 if ((streamCameraId.isEmpty() &&
5632 parent->getId() == settings.cameraId.c_str()) ||
5633 streamCameraId == settings.cameraId.c_str()) {
5634 outputStream->fireBufferRequestForFrameNumber(
5635 captureRequest->mResultExtras.frameNumber,
5636 settings.metadata);
5637 }
5638 }
5639 }
5640 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005641
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005642 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5643
5644 if (!physicalCameraId.isEmpty()) {
5645 // Physical stream isn't supported for input request.
5646 if (halRequest->input_buffer) {
5647 CLOGE("Physical stream is not supported for input request");
5648 return INVALID_OPERATION;
5649 }
5650 requestedPhysicalCameras.insert(physicalCameraId);
5651 }
5652 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005653 }
5654 totalNumBuffers += halRequest->num_output_buffers;
5655
5656 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005657 // If this request list is for constrained high speed recording (not
5658 // preview), and the current request is not the last one in the batch,
5659 // do not send callback to the app.
5660 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005661 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005662 hasCallback = false;
5663 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005664 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005665 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005666 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5667 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5668 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5669 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5670 isStillCapture = true;
5671 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5672 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005673
5674 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5675 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5676 isZslCapture = true;
5677 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005678 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005679 res = parent->registerInFlight(halRequest->frame_number,
5680 totalNumBuffers, captureRequest->mResultExtras,
5681 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005682 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005683 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005684 requestedPhysicalCameras, isStillCapture, isZslCapture,
5685 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5686 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005687 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5688 ", burstId = %" PRId32 ".",
5689 __FUNCTION__,
5690 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5691 captureRequest->mResultExtras.burstId);
5692 if (res != OK) {
5693 SET_ERR("RequestThread: Unable to register new in-flight request:"
5694 " %s (%d)", strerror(-res), res);
5695 return INVALID_OPERATION;
5696 }
5697 }
5698
5699 return OK;
5700}
5701
Igor Murashkin1e479c02013-09-06 16:55:14 -07005702CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005703 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005704 Mutex::Autolock al(mLatestRequestMutex);
5705
5706 ALOGV("RequestThread::%s", __FUNCTION__);
5707
5708 return mLatestRequest;
5709}
5710
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005711bool Camera3Device::RequestThread::isStreamPending(
5712 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005713 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005714 Mutex::Autolock l(mRequestLock);
5715
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005716 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005717 if (!nextRequest.submitted) {
5718 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5719 if (stream == s) return true;
5720 }
5721 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005722 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005723 }
5724
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005725 for (const auto& request : mRequestQueue) {
5726 for (const auto& s : request->mOutputStreams) {
5727 if (stream == s) return true;
5728 }
5729 if (stream == request->mInputStream) return true;
5730 }
5731
5732 for (const auto& request : mRepeatingRequests) {
5733 for (const auto& s : request->mOutputStreams) {
5734 if (stream == s) return true;
5735 }
5736 if (stream == request->mInputStream) return true;
5737 }
5738
5739 return false;
5740}
Jianing Weicb0652e2014-03-12 18:29:36 -07005741
Emilian Peev40ead602017-09-26 15:46:36 +01005742bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5743 ATRACE_CALL();
5744 Mutex::Autolock l(mRequestLock);
5745
5746 for (const auto& nextRequest : mNextRequests) {
5747 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5748 if (s.first == streamId) {
5749 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5750 if (it != s.second.end()) {
5751 return true;
5752 }
5753 }
5754 }
5755 }
5756
5757 for (const auto& request : mRequestQueue) {
5758 for (const auto& s : request->mOutputSurfaces) {
5759 if (s.first == streamId) {
5760 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5761 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005762 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005763 }
5764 }
5765 }
5766 }
5767
5768 for (const auto& request : mRepeatingRequests) {
5769 for (const auto& s : request->mOutputSurfaces) {
5770 if (s.first == streamId) {
5771 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5772 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005773 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005774 }
5775 }
5776 }
5777 }
5778
5779 return false;
5780}
5781
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005782void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5783 if (!mUseHalBufManager) {
5784 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5785 return;
5786 }
5787
5788 Mutex::Autolock pl(mPauseLock);
5789 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005790 mInterface->signalPipelineDrain(streamIds);
5791 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005792 }
5793 // If request thread is still busy, wait until paused then notify HAL
5794 mNotifyPipelineDrain = true;
5795 mStreamIdsToBeDrained = streamIds;
5796}
5797
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005798nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005799 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005800 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005801 return mExpectedInflightDuration > kMinInflightDuration ?
5802 mExpectedInflightDuration : kMinInflightDuration;
5803}
5804
Emilian Peevaebbe412018-01-15 13:53:24 +00005805void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5806 camera3_capture_request_t *halRequest) {
5807 if ((request == nullptr) || (halRequest == nullptr)) {
5808 ALOGE("%s: Invalid request!", __FUNCTION__);
5809 return;
5810 }
5811
5812 if (halRequest->num_physcam_settings > 0) {
5813 if (halRequest->physcam_id != nullptr) {
5814 delete [] halRequest->physcam_id;
5815 halRequest->physcam_id = nullptr;
5816 }
5817 if (halRequest->physcam_settings != nullptr) {
5818 auto it = ++(request->mSettingsList.begin());
5819 size_t i = 0;
5820 for (; it != request->mSettingsList.end(); it++, i++) {
5821 it->metadata.unlock(halRequest->physcam_settings[i]);
5822 }
5823 delete [] halRequest->physcam_settings;
5824 halRequest->physcam_settings = nullptr;
5825 }
5826 }
5827}
5828
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005829void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5830 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005831 return;
5832 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005833
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005834 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005835 // Skip the ones that have been submitted successfully.
5836 if (nextRequest.submitted) {
5837 continue;
5838 }
5839
5840 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5841 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5842 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5843
5844 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005845 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005846 }
5847
Emilian Peevaebbe412018-01-15 13:53:24 +00005848 cleanupPhysicalSettings(captureRequest, halRequest);
5849
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005850 if (captureRequest->mInputStream != NULL) {
5851 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5852 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5853 }
5854
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005855 // No output buffer can be returned when using HAL buffer manager
5856 if (!mUseHalBufManager) {
5857 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5858 //Buffers that failed processing could still have
5859 //valid acquire fence.
5860 int acquireFence = (*outputBuffers)[i].acquire_fence;
5861 if (0 <= acquireFence) {
5862 close(acquireFence);
5863 outputBuffers->editItemAt(i).acquire_fence = -1;
5864 }
5865 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5866 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5867 /*timestampIncreasing*/true, std::vector<size_t> (),
5868 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005869 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005870 }
5871
5872 if (sendRequestError) {
5873 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005874 sp<NotificationListener> listener = mListener.promote();
5875 if (listener != NULL) {
5876 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005877 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005878 captureRequest->mResultExtras);
5879 }
5880 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005881
5882 // Remove yet-to-be submitted inflight request from inflightMap
5883 {
5884 sp<Camera3Device> parent = mParent.promote();
5885 if (parent != NULL) {
5886 Mutex::Autolock l(parent->mInFlightLock);
5887 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5888 if (idx >= 0) {
5889 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5890 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5891 parent->removeInFlightMapEntryLocked(idx);
5892 }
5893 }
5894 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005895 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005896
5897 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005898 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005899}
5900
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005901void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005902 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005903 // Optimized a bit for the simple steady-state case (single repeating
5904 // request), to avoid putting that request in the queue temporarily.
5905 Mutex::Autolock l(mRequestLock);
5906
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005907 assert(mNextRequests.empty());
5908
5909 NextRequest nextRequest;
5910 nextRequest.captureRequest = waitForNextRequestLocked();
5911 if (nextRequest.captureRequest == nullptr) {
5912 return;
5913 }
5914
5915 nextRequest.halRequest = camera3_capture_request_t();
5916 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005917 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005918
5919 // Wait for additional requests
5920 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5921
5922 for (size_t i = 1; i < batchSize; i++) {
5923 NextRequest additionalRequest;
5924 additionalRequest.captureRequest = waitForNextRequestLocked();
5925 if (additionalRequest.captureRequest == nullptr) {
5926 break;
5927 }
5928
5929 additionalRequest.halRequest = camera3_capture_request_t();
5930 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005931 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005932 }
5933
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005934 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005935 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005936 mNextRequests.size(), batchSize);
5937 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005938 }
5939
5940 return;
5941}
5942
5943sp<Camera3Device::CaptureRequest>
5944 Camera3Device::RequestThread::waitForNextRequestLocked() {
5945 status_t res;
5946 sp<CaptureRequest> nextRequest;
5947
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005948 while (mRequestQueue.empty()) {
5949 if (!mRepeatingRequests.empty()) {
5950 // Always atomically enqueue all requests in a repeating request
5951 // list. Guarantees a complete in-sequence set of captures to
5952 // application.
5953 const RequestList &requests = mRepeatingRequests;
5954 RequestList::const_iterator firstRequest =
5955 requests.begin();
5956 nextRequest = *firstRequest;
5957 mRequestQueue.insert(mRequestQueue.end(),
5958 ++firstRequest,
5959 requests.end());
5960 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005961
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005962 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005963
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005964 break;
5965 }
5966
5967 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5968
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005969 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5970 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005971 Mutex::Autolock pl(mPauseLock);
5972 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005973 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005974 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005975 if (mNotifyPipelineDrain) {
5976 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5977 mNotifyPipelineDrain = false;
5978 mStreamIdsToBeDrained.clear();
5979 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005980 // Let the tracker know
5981 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5982 if (statusTracker != 0) {
5983 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5984 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005985 sp<Camera3Device> parent = mParent.promote();
5986 if (parent != nullptr) {
5987 parent->mRequestBufferSM.onRequestThreadPaused();
5988 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005989 }
5990 // Stop waiting for now and let thread management happen
5991 return NULL;
5992 }
5993 }
5994
5995 if (nextRequest == NULL) {
5996 // Don't have a repeating request already in hand, so queue
5997 // must have an entry now.
5998 RequestList::iterator firstRequest =
5999 mRequestQueue.begin();
6000 nextRequest = *firstRequest;
6001 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07006002 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
6003 sp<NotificationListener> listener = mListener.promote();
6004 if (listener != NULL) {
6005 listener->notifyRequestQueueEmpty();
6006 }
6007 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006008 }
6009
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006010 // In case we've been unpaused by setPaused clearing mDoPause, need to
6011 // update internal pause state (capture/setRepeatingRequest unpause
6012 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006013 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006014 if (mPaused) {
6015 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
6016 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6017 if (statusTracker != 0) {
6018 statusTracker->markComponentActive(mStatusId);
6019 }
6020 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006021 mPaused = false;
6022
6023 // Check if we've reconfigured since last time, and reset the preview
6024 // request if so. Can't use 'NULL request == repeat' across configure calls.
6025 if (mReconfigured) {
6026 mPrevRequest.clear();
6027 mReconfigured = false;
6028 }
6029
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006030 if (nextRequest != NULL) {
6031 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006032 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
6033 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006034
6035 // Since RequestThread::clear() removes buffers from the input stream,
6036 // get the right buffer here before unlocking mRequestLock
6037 if (nextRequest->mInputStream != NULL) {
6038 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
6039 if (res != OK) {
6040 // Can't get input buffer from gralloc queue - this could be due to
6041 // disconnected queue or other producer misbehavior, so not a fatal
6042 // error
6043 ALOGE("%s: Can't get input buffer, skipping request:"
6044 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006045
6046 sp<NotificationListener> listener = mListener.promote();
6047 if (listener != NULL) {
6048 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006049 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006050 nextRequest->mResultExtras);
6051 }
6052 return NULL;
6053 }
6054 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006055 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07006056
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006057 return nextRequest;
6058}
6059
6060bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006061 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006062 status_t res;
6063 Mutex::Autolock l(mPauseLock);
6064 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006065 if (mPaused == false) {
6066 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006067 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006068 if (mNotifyPipelineDrain) {
6069 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6070 mNotifyPipelineDrain = false;
6071 mStreamIdsToBeDrained.clear();
6072 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006073 // Let the tracker know
6074 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6075 if (statusTracker != 0) {
6076 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6077 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006078 sp<Camera3Device> parent = mParent.promote();
6079 if (parent != nullptr) {
6080 parent->mRequestBufferSM.onRequestThreadPaused();
6081 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006082 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006083
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006084 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006085 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006086 return true;
6087 }
6088 }
6089 // We don't set mPaused to false here, because waitForNextRequest needs
6090 // to further manage the paused state in case of starvation.
6091 return false;
6092}
6093
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006094void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006095 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006096 // With work to do, mark thread as unpaused.
6097 // If paused by request (setPaused), don't resume, to avoid
6098 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006099 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006100 Mutex::Autolock p(mPauseLock);
6101 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006102 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6103 if (mPaused) {
6104 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6105 if (statusTracker != 0) {
6106 statusTracker->markComponentActive(mStatusId);
6107 }
6108 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006109 mPaused = false;
6110 }
6111}
6112
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006113void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6114 sp<Camera3Device> parent = mParent.promote();
6115 if (parent != NULL) {
6116 va_list args;
6117 va_start(args, fmt);
6118
6119 parent->setErrorStateV(fmt, args);
6120
6121 va_end(args);
6122 }
6123}
6124
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006125status_t Camera3Device::RequestThread::insertTriggers(
6126 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006127 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006128 Mutex::Autolock al(mTriggerMutex);
6129
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006130 sp<Camera3Device> parent = mParent.promote();
6131 if (parent == NULL) {
6132 CLOGE("RequestThread: Parent is gone");
6133 return DEAD_OBJECT;
6134 }
6135
Emilian Peevaebbe412018-01-15 13:53:24 +00006136 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006137 size_t count = mTriggerMap.size();
6138
6139 for (size_t i = 0; i < count; ++i) {
6140 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006141 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006142
6143 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6144 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6145 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006146 if (isAeTrigger) {
6147 request->mResultExtras.precaptureTriggerId = triggerId;
6148 mCurrentPreCaptureTriggerId = triggerId;
6149 } else {
6150 request->mResultExtras.afTriggerId = triggerId;
6151 mCurrentAfTriggerId = triggerId;
6152 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006153 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006154 }
6155
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006156 camera_metadata_entry entry = metadata.find(tag);
6157
6158 if (entry.count > 0) {
6159 /**
6160 * Already has an entry for this trigger in the request.
6161 * Rewrite it with our requested trigger value.
6162 */
6163 RequestTrigger oldTrigger = trigger;
6164
6165 oldTrigger.entryValue = entry.data.u8[0];
6166
6167 mTriggerReplacedMap.add(tag, oldTrigger);
6168 } else {
6169 /**
6170 * More typical, no trigger entry, so we just add it
6171 */
6172 mTriggerRemovedMap.add(tag, trigger);
6173 }
6174
6175 status_t res;
6176
6177 switch (trigger.getTagType()) {
6178 case TYPE_BYTE: {
6179 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6180 res = metadata.update(tag,
6181 &entryValue,
6182 /*count*/1);
6183 break;
6184 }
6185 case TYPE_INT32:
6186 res = metadata.update(tag,
6187 &trigger.entryValue,
6188 /*count*/1);
6189 break;
6190 default:
6191 ALOGE("%s: Type not supported: 0x%x",
6192 __FUNCTION__,
6193 trigger.getTagType());
6194 return INVALID_OPERATION;
6195 }
6196
6197 if (res != OK) {
6198 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6199 ", value %d", __FUNCTION__, trigger.getTagName(),
6200 trigger.entryValue);
6201 return res;
6202 }
6203
6204 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6205 trigger.getTagName(),
6206 trigger.entryValue);
6207 }
6208
6209 mTriggerMap.clear();
6210
6211 return count;
6212}
6213
6214status_t Camera3Device::RequestThread::removeTriggers(
6215 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006216 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006217 Mutex::Autolock al(mTriggerMutex);
6218
Emilian Peevaebbe412018-01-15 13:53:24 +00006219 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006220
6221 /**
6222 * Replace all old entries with their old values.
6223 */
6224 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6225 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6226
6227 status_t res;
6228
6229 uint32_t tag = trigger.metadataTag;
6230 switch (trigger.getTagType()) {
6231 case TYPE_BYTE: {
6232 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6233 res = metadata.update(tag,
6234 &entryValue,
6235 /*count*/1);
6236 break;
6237 }
6238 case TYPE_INT32:
6239 res = metadata.update(tag,
6240 &trigger.entryValue,
6241 /*count*/1);
6242 break;
6243 default:
6244 ALOGE("%s: Type not supported: 0x%x",
6245 __FUNCTION__,
6246 trigger.getTagType());
6247 return INVALID_OPERATION;
6248 }
6249
6250 if (res != OK) {
6251 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6252 ", trigger value %d", __FUNCTION__,
6253 trigger.getTagName(), trigger.entryValue);
6254 return res;
6255 }
6256 }
6257 mTriggerReplacedMap.clear();
6258
6259 /**
6260 * Remove all new entries.
6261 */
6262 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6263 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6264 status_t res = metadata.erase(trigger.metadataTag);
6265
6266 if (res != OK) {
6267 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6268 ", trigger value %d", __FUNCTION__,
6269 trigger.getTagName(), trigger.entryValue);
6270 return res;
6271 }
6272 }
6273 mTriggerRemovedMap.clear();
6274
6275 return OK;
6276}
6277
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006278status_t Camera3Device::RequestThread::addDummyTriggerIds(
6279 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006280 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006281 static const int32_t dummyTriggerId = 1;
6282 status_t res;
6283
Emilian Peevaebbe412018-01-15 13:53:24 +00006284 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006285
6286 // If AF trigger is active, insert a dummy AF trigger ID if none already
6287 // exists
6288 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6289 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6290 if (afTrigger.count > 0 &&
6291 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6292 afId.count == 0) {
6293 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6294 if (res != OK) return res;
6295 }
6296
6297 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6298 // if none already exists
6299 camera_metadata_entry pcTrigger =
6300 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6301 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6302 if (pcTrigger.count > 0 &&
6303 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6304 pcId.count == 0) {
6305 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6306 &dummyTriggerId, 1);
6307 if (res != OK) return res;
6308 }
6309
6310 return OK;
6311}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006312
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006313/**
6314 * PreparerThread inner class methods
6315 */
6316
6317Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006318 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006319 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006320}
6321
6322Camera3Device::PreparerThread::~PreparerThread() {
6323 Thread::requestExitAndWait();
6324 if (mCurrentStream != nullptr) {
6325 mCurrentStream->cancelPrepare();
6326 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6327 mCurrentStream.clear();
6328 }
6329 clear();
6330}
6331
Ruben Brunkc78ac262015-08-13 17:58:46 -07006332status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006333 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006334 status_t res;
6335
6336 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006337 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006338
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006339 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006340 if (res == OK) {
6341 // No preparation needed, fire listener right off
6342 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006343 if (listener != NULL) {
6344 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006345 }
6346 return OK;
6347 } else if (res != NOT_ENOUGH_DATA) {
6348 return res;
6349 }
6350
6351 // Need to prepare, start up thread if necessary
6352 if (!mActive) {
6353 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6354 // isn't running
6355 Thread::requestExitAndWait();
6356 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6357 if (res != OK) {
6358 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006359 if (listener != NULL) {
6360 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006361 }
6362 return res;
6363 }
6364 mCancelNow = false;
6365 mActive = true;
6366 ALOGV("%s: Preparer stream started", __FUNCTION__);
6367 }
6368
6369 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006370 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006371 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6372
6373 return OK;
6374}
6375
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006376void Camera3Device::PreparerThread::pause() {
6377 ATRACE_CALL();
6378
6379 Mutex::Autolock l(mLock);
6380
6381 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6382 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6383 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6384 int currentMaxCount = mCurrentMaxCount;
6385 mPendingStreams.clear();
6386 mCancelNow = true;
6387 while (mActive) {
6388 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6389 if (res == TIMED_OUT) {
6390 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6391 return;
6392 } else if (res != OK) {
6393 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6394 return;
6395 }
6396 }
6397
6398 //Check whether the prepare thread was able to complete the current
6399 //stream. In case work is still pending emplace it along with the rest
6400 //of the streams in the pending list.
6401 if (currentStream != nullptr) {
6402 if (!mCurrentPrepareComplete) {
6403 pendingStreams.emplace(currentMaxCount, currentStream);
6404 }
6405 }
6406
6407 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6408 for (const auto& it : mPendingStreams) {
6409 it.second->cancelPrepare();
6410 }
6411}
6412
6413status_t Camera3Device::PreparerThread::resume() {
6414 ATRACE_CALL();
6415 status_t res;
6416
6417 Mutex::Autolock l(mLock);
6418 sp<NotificationListener> listener = mListener.promote();
6419
6420 if (mActive) {
6421 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6422 return NO_INIT;
6423 }
6424
6425 auto it = mPendingStreams.begin();
6426 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006427 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006428 if (res == OK) {
6429 if (listener != NULL) {
6430 listener->notifyPrepared(it->second->getId());
6431 }
6432 it = mPendingStreams.erase(it);
6433 } else if (res != NOT_ENOUGH_DATA) {
6434 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6435 res, strerror(-res));
6436 it = mPendingStreams.erase(it);
6437 } else {
6438 it++;
6439 }
6440 }
6441
6442 if (mPendingStreams.empty()) {
6443 return OK;
6444 }
6445
6446 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6447 if (res != OK) {
6448 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6449 __FUNCTION__, res, strerror(-res));
6450 return res;
6451 }
6452 mCancelNow = false;
6453 mActive = true;
6454 ALOGV("%s: Preparer stream started", __FUNCTION__);
6455
6456 return OK;
6457}
6458
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006459status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006460 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006461 Mutex::Autolock l(mLock);
6462
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006463 for (const auto& it : mPendingStreams) {
6464 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006465 }
6466 mPendingStreams.clear();
6467 mCancelNow = true;
6468
6469 return OK;
6470}
6471
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006472void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006473 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006474 Mutex::Autolock l(mLock);
6475 mListener = listener;
6476}
6477
6478bool Camera3Device::PreparerThread::threadLoop() {
6479 status_t res;
6480 {
6481 Mutex::Autolock l(mLock);
6482 if (mCurrentStream == nullptr) {
6483 // End thread if done with work
6484 if (mPendingStreams.empty()) {
6485 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6486 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6487 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6488 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006489 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006490 return false;
6491 }
6492
6493 // Get next stream to prepare
6494 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006495 mCurrentStream = it->second;
6496 mCurrentMaxCount = it->first;
6497 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006498 mPendingStreams.erase(it);
6499 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6500 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6501 } else if (mCancelNow) {
6502 mCurrentStream->cancelPrepare();
6503 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6504 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6505 mCurrentStream.clear();
6506 mCancelNow = false;
6507 return true;
6508 }
6509 }
6510
6511 res = mCurrentStream->prepareNextBuffer();
6512 if (res == NOT_ENOUGH_DATA) return true;
6513 if (res != OK) {
6514 // Something bad happened; try to recover by cancelling prepare and
6515 // signalling listener anyway
6516 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6517 mCurrentStream->getId(), res, strerror(-res));
6518 mCurrentStream->cancelPrepare();
6519 }
6520
6521 // This stream has finished, notify listener
6522 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006523 sp<NotificationListener> listener = mListener.promote();
6524 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006525 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6526 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006527 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006528 }
6529
6530 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6531 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006532 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006533
6534 return true;
6535}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006536
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006537status_t Camera3Device::RequestBufferStateMachine::initialize(
6538 sp<camera3::StatusTracker> statusTracker) {
6539 if (statusTracker == nullptr) {
6540 ALOGE("%s: statusTracker is null", __FUNCTION__);
6541 return BAD_VALUE;
6542 }
6543
6544 std::lock_guard<std::mutex> lock(mLock);
6545 mStatusTracker = statusTracker;
6546 mRequestBufferStatusId = statusTracker->addComponent();
6547 return OK;
6548}
6549
6550bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6551 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006552 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006553 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006554 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006555 return true;
6556 }
6557 return false;
6558}
6559
6560void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6561 std::lock_guard<std::mutex> lock(mLock);
6562 if (!mRequestBufferOngoing) {
6563 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6564 return;
6565 }
6566 mRequestBufferOngoing = false;
6567 if (mStatus == RB_STATUS_PENDING_STOP) {
6568 checkSwitchToStopLocked();
6569 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006570 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006571}
6572
6573void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6574 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006575 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006576 return;
6577}
6578
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006579void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006580 std::lock_guard<std::mutex> lock(mLock);
6581 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006582 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6583 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006584 mInflightMapEmpty = false;
6585 if (mStatus == RB_STATUS_STOPPED) {
6586 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006587 }
6588 return;
6589}
6590
6591void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6592 std::lock_guard<std::mutex> lock(mLock);
6593 mRequestThreadPaused = true;
6594 if (mStatus == RB_STATUS_PENDING_STOP) {
6595 checkSwitchToStopLocked();
6596 }
6597 return;
6598}
6599
6600void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6601 std::lock_guard<std::mutex> lock(mLock);
6602 mInflightMapEmpty = true;
6603 if (mStatus == RB_STATUS_PENDING_STOP) {
6604 checkSwitchToStopLocked();
6605 }
6606 return;
6607}
6608
6609void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6610 std::lock_guard<std::mutex> lock(mLock);
6611 if (!checkSwitchToStopLocked()) {
6612 mStatus = RB_STATUS_PENDING_STOP;
6613 }
6614 return;
6615}
6616
6617void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6618 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6619 if (statusTracker != nullptr) {
6620 if (active) {
6621 statusTracker->markComponentActive(mRequestBufferStatusId);
6622 } else {
6623 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6624 }
6625 }
6626}
6627
6628bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6629 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6630 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006631 return true;
6632 }
6633 return false;
6634}
6635
Shuzhen Wang268a1362018-10-16 16:32:59 -07006636status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6637 CameraMetadata& resultMetadata) {
6638 status_t res = OK;
6639 if (!mNeedFixupMonochromeTags) {
6640 return res;
6641 }
6642
6643 // Remove tags that are not applicable to monochrome camera.
6644 int32_t tagsToRemove[] = {
6645 ANDROID_SENSOR_GREEN_SPLIT,
6646 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6647 ANDROID_COLOR_CORRECTION_MODE,
6648 ANDROID_COLOR_CORRECTION_TRANSFORM,
6649 ANDROID_COLOR_CORRECTION_GAINS,
6650 };
6651 for (auto tag : tagsToRemove) {
6652 res = resultMetadata.erase(tag);
6653 if (res != OK) {
6654 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6655 return res;
6656 }
6657 }
6658
6659 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6660 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6661 for (size_t i = 1; i < blEntry.count; i++) {
6662 blEntry.data.f[i] = blEntry.data.f[0];
6663 }
6664
6665 // ANDROID_SENSOR_NOISE_PROFILE
6666 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6667 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6668 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6669 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6670 if (res != OK) {
6671 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6672 __FUNCTION__, strerror(-res), res);
6673 return res;
6674 }
6675 }
6676
6677 // ANDROID_STATISTICS_LENS_SHADING_MAP
6678 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6679 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6680 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6681 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6682 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6683 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6684 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6685 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6686 }
6687 }
6688
6689 // ANDROID_TONEMAP_CURVE_BLUE
6690 // ANDROID_TONEMAP_CURVE_GREEN
6691 // ANDROID_TONEMAP_CURVE_RED
6692 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6693 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6694 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6695 if (tcbEntry.count > 0
6696 && tcbEntry.count == tcgEntry.count
6697 && tcbEntry.count == tcrEntry.count) {
6698 for (size_t i = 0; i < tcbEntry.count; i++) {
6699 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6700 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6701 }
6702 }
6703
6704 return res;
6705}
6706
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006707}; // namespace android