blob: ef99deac01c0a06e08f20ac795ff4970ac07d6b4 [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) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001065 if (res == NO_INIT || res == DEAD_OBJECT) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001066 ALOGV("%s: Can't get output buffer for stream %d: %s (%d)",
1067 __FUNCTION__, streamId, strerror(-res), res);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001068 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001069 } else {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001070 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1071 __FUNCTION__, streamId, strerror(-res), res);
1072 if (res == TIMED_OUT || res == NO_MEMORY) {
1073 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1074 } else {
1075 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1076 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001077 }
1078 currentReqSucceeds = false;
1079 break;
1080 }
1081 numAllocatedBuffers++;
1082
1083 buffer_handle_t *buffer = sb.buffer;
1084 auto pair = mInterface->getBufferId(*buffer, streamId);
1085 bool isNewBuffer = pair.first;
1086 uint64_t bufferId = pair.second;
1087 StreamBuffer& hBuf = tmpRetBuffers[b];
1088
1089 hBuf.streamId = streamId;
1090 hBuf.bufferId = bufferId;
1091 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1092 hBuf.status = BufferStatus::OK;
1093 hBuf.releaseFence = nullptr;
1094
1095 native_handle_t *acquireFence = nullptr;
1096 if (sb.acquire_fence != -1) {
1097 acquireFence = native_handle_create(1,0);
1098 acquireFence->data[0] = sb.acquire_fence;
1099 }
1100 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1101 hBuf.releaseFence = nullptr;
1102
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08001103 res = mInterface->pushInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001104 if (res != OK) {
1105 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1106 __FUNCTION__, streamId, strerror(-res), res);
1107 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1108 currentReqSucceeds = false;
1109 break;
1110 }
1111 numPushedInflightBuffers++;
1112 }
1113 if (currentReqSucceeds) {
1114 bufRet.val.buffers(std::move(tmpRetBuffers));
1115 oneReqSucceeds = true;
1116 } else {
1117 allReqsSucceeds = false;
1118 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1119 StreamBuffer& hBuf = tmpRetBuffers[b];
1120 buffer_handle_t* buffer;
1121 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1122 if (res != OK) {
1123 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1124 __FUNCTION__, streamId, strerror(-res), res);
1125 }
1126 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001127 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1128 camera3_stream_buffer_t& sb = streamBuffers[b];
1129 sb.acquire_fence = -1;
1130 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1131 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001132 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1133 }
1134 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001135
1136 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1137 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1138 BufferRequestStatus::FAILED_UNKNOWN,
1139 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001140 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001141 return hardware::Void();
1142}
1143
1144hardware::Return<void> Camera3Device::returnStreamBuffers(
1145 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1146 if (!mUseHalBufManager) {
1147 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1148 __FUNCTION__, mId.string());
1149 return hardware::Void();
1150 }
1151
1152 for (const auto& buf : buffers) {
1153 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1154 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1155 continue;
1156 }
1157
1158 buffer_handle_t* buffer;
1159 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1160
1161 if (res != OK) {
1162 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1163 __FUNCTION__, buf.bufferId, buf.streamId);
1164 continue;
1165 }
1166
1167 camera3_stream_buffer_t streamBuffer;
1168 streamBuffer.buffer = buffer;
1169 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1170 streamBuffer.acquire_fence = -1;
1171 streamBuffer.release_fence = -1;
1172
1173 if (buf.releaseFence == nullptr) {
1174 streamBuffer.release_fence = -1;
1175 } else if (buf.releaseFence->numFds == 1) {
1176 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1177 } else {
1178 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1179 __FUNCTION__, buf.releaseFence->numFds);
1180 continue;
1181 }
1182
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001183 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1184 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001185 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1186 continue;
1187 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001188 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001189 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1190 }
1191 return hardware::Void();
1192}
1193
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001194hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001195 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001196 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001197 // Ideally we should grab mLock, but that can lead to deadlock, and
1198 // it's not super important to get up to date value of mStatus for this
1199 // warning print, hence skipping the lock here
1200 if (mStatus == STATUS_ERROR) {
1201 // Per API contract, HAL should act as closed after device error
1202 // But mStatus can be set to error by framework as well, so just log
1203 // a warning here.
1204 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001205 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001206
1207 if (mProcessCaptureResultLock.tryLock() != OK) {
1208 // This should never happen; it indicates a wrong client implementation
1209 // that doesn't follow the contract. But, we can be tolerant here.
1210 ALOGE("%s: callback overlapped! waiting 1s...",
1211 __FUNCTION__);
1212 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1213 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1214 __FUNCTION__);
1215 // really don't know what to do, so bail out.
1216 return hardware::Void();
1217 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001218 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001219 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001220 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001221 }
1222 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001223 return hardware::Void();
1224}
1225
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001226// Only one processCaptureResult should be called at a time, so
1227// the locks won't block. The locks are present here simply to enforce this.
1228hardware::Return<void> Camera3Device::processCaptureResult(
1229 const hardware::hidl_vec<
1230 hardware::camera::device::V3_2::CaptureResult>& results) {
1231 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1232
1233 // Ideally we should grab mLock, but that can lead to deadlock, and
1234 // it's not super important to get up to date value of mStatus for this
1235 // warning print, hence skipping the lock here
1236 if (mStatus == STATUS_ERROR) {
1237 // Per API contract, HAL should act as closed after device error
1238 // But mStatus can be set to error by framework as well, so just log
1239 // a warning here.
1240 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1241 }
1242
1243 if (mProcessCaptureResultLock.tryLock() != OK) {
1244 // This should never happen; it indicates a wrong client implementation
1245 // that doesn't follow the contract. But, we can be tolerant here.
1246 ALOGE("%s: callback overlapped! waiting 1s...",
1247 __FUNCTION__);
1248 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1249 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1250 __FUNCTION__);
1251 // really don't know what to do, so bail out.
1252 return hardware::Void();
1253 }
1254 }
1255 for (const auto& result : results) {
1256 processOneCaptureResultLocked(result, noPhysMetadata);
1257 }
1258 mProcessCaptureResultLock.unlock();
1259 return hardware::Void();
1260}
1261
1262status_t Camera3Device::readOneCameraMetadataLocked(
1263 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1264 const hardware::camera::device::V3_2::CameraMetadata& result) {
1265 if (fmqResultSize > 0) {
1266 resultMetadata.resize(fmqResultSize);
1267 if (mResultMetadataQueue == nullptr) {
1268 return NO_MEMORY; // logged in initialize()
1269 }
1270 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1271 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1272 __FUNCTION__, fmqResultSize);
1273 return INVALID_OPERATION;
1274 }
1275 } else {
1276 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1277 result.size());
1278 }
1279
1280 if (resultMetadata.size() != 0) {
1281 status_t res;
1282 const camera_metadata_t* metadata =
1283 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1284 size_t expected_metadata_size = resultMetadata.size();
1285 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1286 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1287 __FUNCTION__, strerror(-res), res);
1288 return INVALID_OPERATION;
1289 }
1290 }
1291
1292 return OK;
1293}
1294
Yifan Honga640c5a2017-04-12 16:30:31 -07001295void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001296 const hardware::camera::device::V3_2::CaptureResult& result,
1297 const hardware::hidl_vec<
1298 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadatas) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001299 camera3_capture_result r;
1300 status_t res;
1301 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001302
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001303 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001304 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001305 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1306 if (res != OK) {
1307 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1308 __FUNCTION__, result.frameNumber);
1309 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001310 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001311 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001312
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001313 // Read and validate physical camera metadata
1314 size_t physResultCount = physicalCameraMetadatas.size();
1315 std::vector<const char*> physCamIds(physResultCount);
1316 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1317 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1318 physResultMetadata.resize(physResultCount);
1319 for (size_t i = 0; i < physicalCameraMetadatas.size(); i++) {
1320 res = readOneCameraMetadataLocked(physicalCameraMetadatas[i].fmqMetadataSize,
1321 physResultMetadata[i], physicalCameraMetadatas[i].metadata);
1322 if (res != OK) {
1323 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1324 __FUNCTION__, result.frameNumber,
1325 physicalCameraMetadatas[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001326 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001327 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001328 physCamIds[i] = physicalCameraMetadatas[i].physicalCameraId.c_str();
1329 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1330 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001331 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001332 r.num_physcam_metadata = physResultCount;
1333 r.physcam_ids = physCamIds.data();
1334 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001335
1336 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1337 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1338 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1339 auto& bDst = outputBuffers[i];
1340 const StreamBuffer &bSrc = result.outputBuffers[i];
1341
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001342 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1343 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001344 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1345 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001346 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001347 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001348 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001349
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001350 bool noBufferReturned = false;
1351 buffer_handle_t *buffer = nullptr;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001352 if (mUseHalBufManager) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001353 // This is suspicious most of the time but can be correct during flush where HAL
1354 // has to return capture result before a buffer is requested
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001355 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001356 if (bSrc.status == BufferStatus::OK) {
1357 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1358 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1359 // Still proceeds so other buffers can be returned
1360 }
1361 noBufferReturned = true;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001362 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001363 if (noBufferReturned) {
1364 res = OK;
1365 } else {
1366 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1367 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001368 } else {
1369 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1370 }
1371
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001372 if (res != OK) {
1373 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1374 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001375 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001376 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001377
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001378 bDst.buffer = buffer;
1379 bDst.status = mapHidlBufferStatus(bSrc.status);
1380 bDst.acquire_fence = -1;
1381 if (bSrc.releaseFence == nullptr) {
1382 bDst.release_fence = -1;
1383 } else if (bSrc.releaseFence->numFds == 1) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001384 if (noBufferReturned) {
1385 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
1386 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001387 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1388 } else {
1389 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1390 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001391 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001392 }
1393 }
1394 r.num_output_buffers = outputBuffers.size();
1395 r.output_buffers = outputBuffers.data();
1396
1397 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001398 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001399 r.input_buffer = nullptr;
1400 } else {
1401 if (mInputStream->getId() != result.inputBuffer.streamId) {
1402 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1403 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001404 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001405 }
1406 inputBuffer.stream = mInputStream->asHalStream();
1407 buffer_handle_t *buffer;
1408 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1409 &buffer);
1410 if (res != OK) {
1411 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1412 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001413 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001414 }
1415 inputBuffer.buffer = buffer;
1416 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1417 inputBuffer.acquire_fence = -1;
1418 if (result.inputBuffer.releaseFence == nullptr) {
1419 inputBuffer.release_fence = -1;
1420 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1421 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1422 } else {
1423 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1424 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001425 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001426 }
1427 r.input_buffer = &inputBuffer;
1428 }
1429
1430 r.partial_result = result.partialResult;
1431
1432 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001433}
1434
1435hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001436 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001437 // Ideally we should grab mLock, but that can lead to deadlock, and
1438 // it's not super important to get up to date value of mStatus for this
1439 // warning print, hence skipping the lock here
1440 if (mStatus == STATUS_ERROR) {
1441 // Per API contract, HAL should act as closed after device error
1442 // But mStatus can be set to error by framework as well, so just log
1443 // a warning here.
1444 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001445 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001446
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001447 for (const auto& msg : msgs) {
1448 notify(msg);
1449 }
1450 return hardware::Void();
1451}
1452
1453void Camera3Device::notify(
1454 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1455
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001456 camera3_notify_msg m;
1457 switch (msg.type) {
1458 case MsgType::ERROR:
1459 m.type = CAMERA3_MSG_ERROR;
1460 m.message.error.frame_number = msg.msg.error.frameNumber;
1461 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001462 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1463 if (stream == nullptr) {
1464 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1465 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001466 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001467 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001468 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001469 } else {
1470 m.message.error.error_stream = nullptr;
1471 }
1472 switch (msg.msg.error.errorCode) {
1473 case ErrorCode::ERROR_DEVICE:
1474 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1475 break;
1476 case ErrorCode::ERROR_REQUEST:
1477 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1478 break;
1479 case ErrorCode::ERROR_RESULT:
1480 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1481 break;
1482 case ErrorCode::ERROR_BUFFER:
1483 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1484 break;
1485 }
1486 break;
1487 case MsgType::SHUTTER:
1488 m.type = CAMERA3_MSG_SHUTTER;
1489 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1490 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1491 break;
1492 }
1493 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001494}
1495
Emilian Peevaebbe412018-01-15 13:53:24 +00001496status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001497 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001498 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001499 ATRACE_CALL();
1500
Emilian Peevaebbe412018-01-15 13:53:24 +00001501 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001502}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001503
Jianing Weicb0652e2014-03-12 18:29:36 -07001504status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1505 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001506 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001507
Emilian Peevaebbe412018-01-15 13:53:24 +00001508 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001509 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001510 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001511
Emilian Peevaebbe412018-01-15 13:53:24 +00001512 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001513 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001514}
1515
Emilian Peevaebbe412018-01-15 13:53:24 +00001516status_t Camera3Device::setStreamingRequestList(
1517 const List<const PhysicalCameraSettingsList> &requestsList,
1518 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001519 ATRACE_CALL();
1520
Emilian Peevaebbe412018-01-15 13:53:24 +00001521 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001522}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001523
1524sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001525 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001526 status_t res;
1527
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001528 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001529 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1530 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001531 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1532 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001533 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001534 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001535 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001536 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001537 } else if (mStatus == STATUS_UNCONFIGURED) {
1538 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001539 CLOGE("No streams configured");
1540 return NULL;
1541 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001542 }
1543
Shuzhen Wang0129d522016-10-30 22:43:41 -07001544 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001545 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001546}
1547
Jianing Weicb0652e2014-03-12 18:29:36 -07001548status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001549 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001550 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001551 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001552
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001553 switch (mStatus) {
1554 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001555 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001556 return INVALID_OPERATION;
1557 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001558 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001559 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001560 case STATUS_UNCONFIGURED:
1561 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001562 case STATUS_ACTIVE:
1563 // OK
1564 break;
1565 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001566 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001567 return INVALID_OPERATION;
1568 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001569 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001570
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001571 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001572}
1573
1574status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1575 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001576 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001577
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001578 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001579}
1580
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001581status_t Camera3Device::createInputStream(
1582 uint32_t width, uint32_t height, int format, int *id) {
1583 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001584 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001585 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001586 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001587 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1588 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001589
1590 status_t res;
1591 bool wasActive = false;
1592
1593 switch (mStatus) {
1594 case STATUS_ERROR:
1595 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1596 return INVALID_OPERATION;
1597 case STATUS_UNINITIALIZED:
1598 ALOGE("%s: Device not initialized", __FUNCTION__);
1599 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001600 case STATUS_UNCONFIGURED:
1601 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001602 // OK
1603 break;
1604 case STATUS_ACTIVE:
1605 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001606 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001607 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001608 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001609 return res;
1610 }
1611 wasActive = true;
1612 break;
1613 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001614 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001615 return INVALID_OPERATION;
1616 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001617 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001618
1619 if (mInputStream != 0) {
1620 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1621 return INVALID_OPERATION;
1622 }
1623
1624 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1625 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001626 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001627
1628 mInputStream = newStream;
1629
1630 *id = mNextStreamId++;
1631
1632 // Continue captures if active at start
1633 if (wasActive) {
1634 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001635 // Reuse current operating mode and session parameters for new stream config
1636 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001637 if (res != OK) {
1638 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1639 __FUNCTION__, mNextStreamId, strerror(-res), res);
1640 return res;
1641 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001642 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001643 }
1644
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001645 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001646 return OK;
1647}
1648
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001649status_t Camera3Device::StreamSet::add(
1650 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1651 if (stream == nullptr) {
1652 ALOGE("%s: cannot add null stream", __FUNCTION__);
1653 return BAD_VALUE;
1654 }
1655 std::lock_guard<std::mutex> lock(mLock);
1656 return mData.add(streamId, stream);
1657}
1658
1659ssize_t Camera3Device::StreamSet::remove(int streamId) {
1660 std::lock_guard<std::mutex> lock(mLock);
1661 return mData.removeItem(streamId);
1662}
1663
1664sp<camera3::Camera3OutputStreamInterface>
1665Camera3Device::StreamSet::get(int streamId) {
1666 std::lock_guard<std::mutex> lock(mLock);
1667 ssize_t idx = mData.indexOfKey(streamId);
1668 if (idx == NAME_NOT_FOUND) {
1669 return nullptr;
1670 }
1671 return mData.editValueAt(idx);
1672}
1673
1674sp<camera3::Camera3OutputStreamInterface>
1675Camera3Device::StreamSet::operator[] (size_t index) {
1676 std::lock_guard<std::mutex> lock(mLock);
1677 return mData.editValueAt(index);
1678}
1679
1680size_t Camera3Device::StreamSet::size() const {
1681 std::lock_guard<std::mutex> lock(mLock);
1682 return mData.size();
1683}
1684
1685void Camera3Device::StreamSet::clear() {
1686 std::lock_guard<std::mutex> lock(mLock);
1687 return mData.clear();
1688}
1689
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001690std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1691 std::lock_guard<std::mutex> lock(mLock);
1692 std::vector<int> streamIds(mData.size());
1693 for (size_t i = 0; i < mData.size(); i++) {
1694 streamIds[i] = mData.keyAt(i);
1695 }
1696 return streamIds;
1697}
1698
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001699status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001700 uint32_t width, uint32_t height, int format,
1701 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001702 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001703 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001704 ATRACE_CALL();
1705
1706 if (consumer == nullptr) {
1707 ALOGE("%s: consumer must not be null", __FUNCTION__);
1708 return BAD_VALUE;
1709 }
1710
1711 std::vector<sp<Surface>> consumers;
1712 consumers.push_back(consumer);
1713
1714 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001715 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1716 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001717}
1718
1719status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1720 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1721 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001722 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001723 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001724 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001725
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001726 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001727 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001728 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001729 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001730 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1731 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1732 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001733
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001734 status_t res;
1735 bool wasActive = false;
1736
1737 switch (mStatus) {
1738 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001739 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001740 return INVALID_OPERATION;
1741 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001742 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001743 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001744 case STATUS_UNCONFIGURED:
1745 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001746 // OK
1747 break;
1748 case STATUS_ACTIVE:
1749 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001750 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001751 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001752 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001753 return res;
1754 }
1755 wasActive = true;
1756 break;
1757 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001758 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001759 return INVALID_OPERATION;
1760 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001761 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001762
1763 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001764
Shuzhen Wang0129d522016-10-30 22:43:41 -07001765 if (consumers.size() == 0 && !hasDeferredConsumer) {
1766 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1767 return BAD_VALUE;
1768 }
Zhijun He5d677d12016-05-29 16:52:39 -07001769
Shuzhen Wang0129d522016-10-30 22:43:41 -07001770 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001771 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1772 return BAD_VALUE;
1773 }
1774
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001775 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001776 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001777 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001778 blobBufferSize = getPointCloudBufferSize();
1779 if (blobBufferSize <= 0) {
1780 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1781 return BAD_VALUE;
1782 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001783 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1784 blobBufferSize = width * height;
1785 } else {
1786 blobBufferSize = getJpegBufferSize(width, height);
1787 if (blobBufferSize <= 0) {
1788 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1789 return BAD_VALUE;
1790 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001791 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001792 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001793 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001794 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001795 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1796 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1797 if (rawOpaqueBufferSize <= 0) {
1798 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1799 return BAD_VALUE;
1800 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001801 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001802 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001803 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001804 } else if (isShared) {
1805 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1806 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001807 mTimestampOffset, physicalCameraId, streamSetId,
1808 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001809 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001810 newStream = new Camera3OutputStream(mNextStreamId,
1811 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001812 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001813 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001814 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001815 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001816 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001817 }
Emilian Peev40ead602017-09-26 15:46:36 +01001818
1819 size_t consumerCount = consumers.size();
1820 for (size_t i = 0; i < consumerCount; i++) {
1821 int id = newStream->getSurfaceId(consumers[i]);
1822 if (id < 0) {
1823 SET_ERR_L("Invalid surface id");
1824 return BAD_VALUE;
1825 }
1826 if (surfaceIds != nullptr) {
1827 surfaceIds->push_back(id);
1828 }
1829 }
1830
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001831 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001832
Emilian Peev08dd2452017-04-06 16:55:14 +01001833 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001834
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001835 res = mOutputStreams.add(mNextStreamId, newStream);
1836 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001837 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001838 return res;
1839 }
1840
1841 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001842 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001843
1844 // Continue captures if active at start
1845 if (wasActive) {
1846 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001847 // Reuse current operating mode and session parameters for new stream config
1848 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001849 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001850 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1851 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001852 return res;
1853 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001854 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001855 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001856 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001857 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001858}
1859
Emilian Peev710c1422017-08-30 11:19:38 +01001860status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001861 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001862 if (nullptr == streamInfo) {
1863 return BAD_VALUE;
1864 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001865 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001866 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001867
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001868 switch (mStatus) {
1869 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001870 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001871 return INVALID_OPERATION;
1872 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001873 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001874 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001875 case STATUS_UNCONFIGURED:
1876 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001877 case STATUS_ACTIVE:
1878 // OK
1879 break;
1880 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001881 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001882 return INVALID_OPERATION;
1883 }
1884
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001885 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1886 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001887 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001888 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001889 }
1890
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001891 streamInfo->width = stream->getWidth();
1892 streamInfo->height = stream->getHeight();
1893 streamInfo->format = stream->getFormat();
1894 streamInfo->dataSpace = stream->getDataSpace();
1895 streamInfo->formatOverridden = stream->isFormatOverridden();
1896 streamInfo->originalFormat = stream->getOriginalFormat();
1897 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1898 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001899 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001900}
1901
1902status_t Camera3Device::setStreamTransform(int id,
1903 int transform) {
1904 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001905 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001906 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001907
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001908 switch (mStatus) {
1909 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001910 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001911 return INVALID_OPERATION;
1912 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001913 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001914 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001915 case STATUS_UNCONFIGURED:
1916 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001917 case STATUS_ACTIVE:
1918 // OK
1919 break;
1920 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001921 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001922 return INVALID_OPERATION;
1923 }
1924
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001925 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1926 if (stream == nullptr) {
1927 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001928 return BAD_VALUE;
1929 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001930 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001931}
1932
1933status_t Camera3Device::deleteStream(int id) {
1934 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001935 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001936 Mutex::Autolock l(mLock);
1937 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001938
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001939 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001940
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001941 // CameraDevice semantics require device to already be idle before
1942 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001943 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001944 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001945 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001946 }
1947
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001948 if (mStatus == STATUS_ERROR) {
1949 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1950 __FUNCTION__, mId.string());
1951 return -EBUSY;
1952 }
1953
Igor Murashkin2fba5842013-04-22 14:03:54 -07001954 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001955 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001956 if (mInputStream != NULL && id == mInputStream->getId()) {
1957 deletedStream = mInputStream;
1958 mInputStream.clear();
1959 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001960 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001961 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001962 return BAD_VALUE;
1963 }
Zhijun He5f446352014-01-22 09:49:33 -08001964 }
1965
1966 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001967 if (stream != nullptr) {
1968 deletedStream = stream;
1969 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001970 }
1971
1972 // Free up the stream endpoint so that it can be used by some other stream
1973 res = deletedStream->disconnect();
1974 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001975 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001976 // fall through since we want to still list the stream as deleted.
1977 }
1978 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001979 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001980
1981 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001982}
1983
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001984status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07001985 ATRACE_CALL();
1986 ALOGV("%s: E", __FUNCTION__);
1987
1988 Mutex::Autolock il(mInterfaceLock);
1989 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07001990
Emilian Peev811d2952018-05-25 11:08:40 +01001991 // In case the client doesn't include any session parameter, try a
1992 // speculative configuration using the values from the last cached
1993 // default request.
1994 if (sessionParams.isEmpty() &&
1995 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
1996 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
1997 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
1998 mLastTemplateId);
1999 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
2000 operatingMode);
2001 }
2002
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002003 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
2004}
2005
2006status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
2007 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002008 //Filter out any incoming session parameters
2009 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002010 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
2011 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002012 CameraMetadata filteredParams(availableSessionKeys.count);
2013 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2014 filteredParams.getAndLock());
2015 set_camera_metadata_vendor_id(meta, mVendorTagId);
2016 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002017 if (availableSessionKeys.count > 0) {
2018 for (size_t i = 0; i < availableSessionKeys.count; i++) {
2019 camera_metadata_ro_entry entry = params.find(
2020 availableSessionKeys.data.i32[i]);
2021 if (entry.count > 0) {
2022 filteredParams.update(entry);
2023 }
2024 }
2025 }
2026
2027 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07002028}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002029
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002030status_t Camera3Device::getInputBufferProducer(
2031 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002032 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002033 Mutex::Autolock il(mInterfaceLock);
2034 Mutex::Autolock l(mLock);
2035
2036 if (producer == NULL) {
2037 return BAD_VALUE;
2038 } else if (mInputStream == NULL) {
2039 return INVALID_OPERATION;
2040 }
2041
2042 return mInputStream->getInputBufferProducer(producer);
2043}
2044
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002045status_t Camera3Device::createDefaultRequest(int templateId,
2046 CameraMetadata *request) {
2047 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002048 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002049
2050 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2051 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002052 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002053 return BAD_VALUE;
2054 }
2055
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002056 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002057
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002058 {
2059 Mutex::Autolock l(mLock);
2060 switch (mStatus) {
2061 case STATUS_ERROR:
2062 CLOGE("Device has encountered a serious error");
2063 return INVALID_OPERATION;
2064 case STATUS_UNINITIALIZED:
2065 CLOGE("Device is not initialized!");
2066 return INVALID_OPERATION;
2067 case STATUS_UNCONFIGURED:
2068 case STATUS_CONFIGURED:
2069 case STATUS_ACTIVE:
2070 // OK
2071 break;
2072 default:
2073 SET_ERR_L("Unexpected status: %d", mStatus);
2074 return INVALID_OPERATION;
2075 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002076
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002077 if (!mRequestTemplateCache[templateId].isEmpty()) {
2078 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002079 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002080 return OK;
2081 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002082 }
2083
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002084 camera_metadata_t *rawRequest;
2085 status_t res = mInterface->constructDefaultRequestSettings(
2086 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002087
2088 {
2089 Mutex::Autolock l(mLock);
2090 if (res == BAD_VALUE) {
2091 ALOGI("%s: template %d is not supported on this camera device",
2092 __FUNCTION__, templateId);
2093 return res;
2094 } else if (res != OK) {
2095 CLOGE("Unable to construct request template %d: %s (%d)",
2096 templateId, strerror(-res), res);
2097 return res;
2098 }
2099
2100 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2101 mRequestTemplateCache[templateId].acquire(rawRequest);
2102
2103 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002104 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002105 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002106 return OK;
2107}
2108
2109status_t Camera3Device::waitUntilDrained() {
2110 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002111 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002112 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002113 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002114
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002115 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002116}
2117
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002118status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002119 switch (mStatus) {
2120 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002121 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002122 ALOGV("%s: Already idle", __FUNCTION__);
2123 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002124 case STATUS_CONFIGURED:
2125 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002126 case STATUS_ERROR:
2127 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002128 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002129 break;
2130 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002131 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002132 return INVALID_OPERATION;
2133 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002134 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2135 maxExpectedDuration);
2136 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002137 if (res != OK) {
2138 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2139 res);
2140 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002141 return res;
2142}
2143
Ruben Brunk183f0562015-08-12 12:55:02 -07002144
2145void Camera3Device::internalUpdateStatusLocked(Status status) {
2146 mStatus = status;
2147 mRecentStatusUpdates.add(mStatus);
2148 mStatusChanged.broadcast();
2149}
2150
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002151void Camera3Device::pauseStateNotify(bool enable) {
2152 Mutex::Autolock il(mInterfaceLock);
2153 Mutex::Autolock l(mLock);
2154
2155 mPauseStateNotify = enable;
2156}
2157
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002158// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002159status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08002160 if (mRequestThread.get() != nullptr) {
2161 mRequestThread->setPaused(true);
2162 } else {
2163 return NO_INIT;
2164 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002165
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002166 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2167 maxExpectedDuration);
2168 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002169 if (res != OK) {
2170 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002171 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002172 }
2173
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002174 return res;
2175}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002176
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002177// Resume after internalPauseAndWaitLocked
2178status_t Camera3Device::internalResumeLocked() {
2179 status_t res;
2180
2181 mRequestThread->setPaused(false);
2182
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002183 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2184 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002185 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2186 if (res != OK) {
2187 SET_ERR_L("Can't transition to active in %f seconds!",
2188 kActiveTimeout/1e9);
2189 }
2190 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002191 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002192}
2193
Ruben Brunk183f0562015-08-12 12:55:02 -07002194status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002195 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002196
2197 size_t startIndex = 0;
2198 if (mStatusWaiters == 0) {
2199 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2200 // this status list
2201 mRecentStatusUpdates.clear();
2202 } else {
2203 // If other threads are waiting on updates to this status list, set the position of the
2204 // first element that this list will check rather than clearing the list.
2205 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002206 }
2207
Ruben Brunk183f0562015-08-12 12:55:02 -07002208 mStatusWaiters++;
2209
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002210 if (!active && mUseHalBufManager) {
2211 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08002212 if (mStatus == STATUS_ACTIVE) {
2213 mRequestThread->signalPipelineDrain(streamIds);
2214 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002215 mRequestBufferSM.onWaitUntilIdle();
2216 }
2217
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002218 bool stateSeen = false;
2219 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002220 if (active == (mStatus == STATUS_ACTIVE)) {
2221 // Desired state is current
2222 break;
2223 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002224
2225 res = mStatusChanged.waitRelative(mLock, timeout);
2226 if (res != OK) break;
2227
Ruben Brunk183f0562015-08-12 12:55:02 -07002228 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2229 // transitions.
2230 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2231 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2232 __FUNCTION__);
2233
2234 // Encountered desired state since we began waiting
2235 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002236 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2237 stateSeen = true;
2238 break;
2239 }
2240 }
2241 } while (!stateSeen);
2242
Ruben Brunk183f0562015-08-12 12:55:02 -07002243 mStatusWaiters--;
2244
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002245 return res;
2246}
2247
2248
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002249status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002250 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002251 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002252
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002253 if (listener != NULL && mListener != NULL) {
2254 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2255 }
2256 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002257 mRequestThread->setNotificationListener(listener);
2258 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002259
2260 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002261}
2262
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002263bool Camera3Device::willNotify3A() {
2264 return false;
2265}
2266
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002267status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002268 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002269 status_t res;
2270 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002271
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002272 while (mResultQueue.empty()) {
2273 res = mResultSignal.waitRelative(mOutputLock, timeout);
2274 if (res == TIMED_OUT) {
2275 return res;
2276 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002277 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2278 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002279 return res;
2280 }
2281 }
2282 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002283}
2284
Jianing Weicb0652e2014-03-12 18:29:36 -07002285status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002286 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002287 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002288
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002289 if (mResultQueue.empty()) {
2290 return NOT_ENOUGH_DATA;
2291 }
2292
Jianing Weicb0652e2014-03-12 18:29:36 -07002293 if (frame == NULL) {
2294 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2295 return BAD_VALUE;
2296 }
2297
2298 CaptureResult &result = *(mResultQueue.begin());
2299 frame->mResultExtras = result.mResultExtras;
2300 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002301 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002302 mResultQueue.erase(mResultQueue.begin());
2303
2304 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002305}
2306
2307status_t Camera3Device::triggerAutofocus(uint32_t id) {
2308 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002309 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002310
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002311 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2312 // Mix-in this trigger into the next request and only the next request.
2313 RequestTrigger trigger[] = {
2314 {
2315 ANDROID_CONTROL_AF_TRIGGER,
2316 ANDROID_CONTROL_AF_TRIGGER_START
2317 },
2318 {
2319 ANDROID_CONTROL_AF_TRIGGER_ID,
2320 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002321 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002322 };
2323
2324 return mRequestThread->queueTrigger(trigger,
2325 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002326}
2327
2328status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2329 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002330 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002331
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002332 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2333 // Mix-in this trigger into the next request and only the next request.
2334 RequestTrigger trigger[] = {
2335 {
2336 ANDROID_CONTROL_AF_TRIGGER,
2337 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2338 },
2339 {
2340 ANDROID_CONTROL_AF_TRIGGER_ID,
2341 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002342 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002343 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002344
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002345 return mRequestThread->queueTrigger(trigger,
2346 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002347}
2348
2349status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2350 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002351 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002352
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002353 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2354 // Mix-in this trigger into the next request and only the next request.
2355 RequestTrigger trigger[] = {
2356 {
2357 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2358 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2359 },
2360 {
2361 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2362 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002363 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002364 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002365
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002366 return mRequestThread->queueTrigger(trigger,
2367 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002368}
2369
Jianing Weicb0652e2014-03-12 18:29:36 -07002370status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002371 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002372 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002373 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002374
Zhijun He7ef20392014-04-21 16:04:17 -07002375 {
2376 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002377
2378 // b/116514106 "disconnect()" can get called twice for the same device. The
2379 // camera device will not be initialized during the second run.
2380 if (mStatus == STATUS_UNINITIALIZED) {
2381 return OK;
2382 }
2383
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002384 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002385 }
2386
Emilian Peev08dd2452017-04-06 16:55:14 +01002387 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002388}
2389
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002390status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002391 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2392}
2393
2394status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002395 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002396 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002397 Mutex::Autolock il(mInterfaceLock);
2398 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002399
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002400 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2401 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002402 CLOGE("Stream %d does not exist", streamId);
2403 return BAD_VALUE;
2404 }
2405
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002406 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002407 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002408 return BAD_VALUE;
2409 }
2410
2411 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002412 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002413 return BAD_VALUE;
2414 }
2415
Ruben Brunkc78ac262015-08-13 17:58:46 -07002416 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002417}
2418
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002419status_t Camera3Device::tearDown(int streamId) {
2420 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002421 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002422 Mutex::Autolock il(mInterfaceLock);
2423 Mutex::Autolock l(mLock);
2424
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002425 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2426 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002427 CLOGE("Stream %d does not exist", streamId);
2428 return BAD_VALUE;
2429 }
2430
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002431 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2432 CLOGE("Stream %d is a target of a in-progress request", streamId);
2433 return BAD_VALUE;
2434 }
2435
2436 return stream->tearDown();
2437}
2438
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002439status_t Camera3Device::addBufferListenerForStream(int streamId,
2440 wp<Camera3StreamBufferListener> listener) {
2441 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002442 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002443 Mutex::Autolock il(mInterfaceLock);
2444 Mutex::Autolock l(mLock);
2445
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002446 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2447 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002448 CLOGE("Stream %d does not exist", streamId);
2449 return BAD_VALUE;
2450 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002451 stream->addBufferListener(listener);
2452
2453 return OK;
2454}
2455
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002456/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002457 * Methods called by subclasses
2458 */
2459
2460void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002461 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002462 {
2463 // Need mLock to safely update state and synchronize to current
2464 // state of methods in flight.
2465 Mutex::Autolock l(mLock);
2466 // We can get various system-idle notices from the status tracker
2467 // while starting up. Only care about them if we've actually sent
2468 // in some requests recently.
2469 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2470 return;
2471 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002472 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2473 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002474 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002475
2476 // Skip notifying listener if we're doing some user-transparent
2477 // state changes
2478 if (mPauseStateNotify) return;
2479 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002480
2481 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002482 {
2483 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002484 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002485 }
2486 if (idle && listener != NULL) {
2487 listener->notifyIdle();
2488 }
2489}
2490
Shuzhen Wang758c2152017-01-10 18:26:18 -08002491status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002492 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002493 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002494 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2495 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002496
2497 if (surfaceIds == nullptr) {
2498 return BAD_VALUE;
2499 }
2500
Zhijun He5d677d12016-05-29 16:52:39 -07002501 Mutex::Autolock il(mInterfaceLock);
2502 Mutex::Autolock l(mLock);
2503
Shuzhen Wang758c2152017-01-10 18:26:18 -08002504 if (consumers.size() == 0) {
2505 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002506 return BAD_VALUE;
2507 }
2508
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002509 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2510 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002511 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002512 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002513 }
Shuzhen Wang758c2152017-01-10 18:26:18 -08002514 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002515 if (res != OK) {
2516 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2517 return res;
2518 }
2519
Emilian Peev40ead602017-09-26 15:46:36 +01002520 for (auto &consumer : consumers) {
2521 int id = stream->getSurfaceId(consumer);
2522 if (id < 0) {
2523 CLOGE("Invalid surface id!");
2524 return BAD_VALUE;
2525 }
2526 surfaceIds->push_back(id);
2527 }
2528
Shuzhen Wang0129d522016-10-30 22:43:41 -07002529 if (stream->isConsumerConfigurationDeferred()) {
2530 if (!stream->isConfiguring()) {
2531 CLOGE("Stream %d was already fully configured.", streamId);
2532 return INVALID_OPERATION;
2533 }
Zhijun He5d677d12016-05-29 16:52:39 -07002534
Shuzhen Wang0129d522016-10-30 22:43:41 -07002535 res = stream->finishConfiguration();
2536 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002537 // If finishConfiguration fails due to abandoned surface, do not set
2538 // device to error state.
2539 bool isSurfaceAbandoned =
2540 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2541 if (!isSurfaceAbandoned) {
2542 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2543 stream->getId(), strerror(-res), res);
2544 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002545 return res;
2546 }
Zhijun He5d677d12016-05-29 16:52:39 -07002547 }
2548
2549 return OK;
2550}
2551
Emilian Peev40ead602017-09-26 15:46:36 +01002552status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2553 const std::vector<OutputStreamInfo> &outputInfo,
2554 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2555 Mutex::Autolock il(mInterfaceLock);
2556 Mutex::Autolock l(mLock);
2557
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002558 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2559 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002560 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002561 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002562 }
2563
2564 for (const auto &it : removedSurfaceIds) {
2565 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2566 CLOGE("Shared surface still part of a pending request!");
2567 return -EBUSY;
2568 }
2569 }
2570
Emilian Peev40ead602017-09-26 15:46:36 +01002571 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2572 if (res != OK) {
2573 CLOGE("Stream %d failed to update stream (error %d %s) ",
2574 streamId, res, strerror(-res));
2575 if (res == UNKNOWN_ERROR) {
2576 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2577 __FUNCTION__);
2578 }
2579 return res;
2580 }
2581
2582 return res;
2583}
2584
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002585status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2586 Mutex::Autolock il(mInterfaceLock);
2587 Mutex::Autolock l(mLock);
2588
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002589 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2590 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002591 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2592 return BAD_VALUE;
2593 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002594 return stream->dropBuffers(dropping);
2595}
2596
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002597/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002598 * Camera3Device private methods
2599 */
2600
2601sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002602 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002603 ATRACE_CALL();
2604 status_t res;
2605
2606 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002607 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002608
2609 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002610 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002611 if (inputStreams.count > 0) {
2612 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002613 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002614 CLOGE("Request references unknown input stream %d",
2615 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002616 return NULL;
2617 }
2618 // Lazy completion of stream configuration (allocation/registration)
2619 // on first use
2620 if (mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002621 res = mInputStream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002622 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002623 SET_ERR_L("Unable to finish configuring input stream %d:"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002624 " %s (%d)",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002625 mInputStream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002626 return NULL;
2627 }
2628 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002629 // Check if stream prepare is blocking requests.
2630 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002631 CLOGE("Request references an input stream that's being prepared!");
2632 return NULL;
2633 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002634
2635 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002636 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002637 }
2638
2639 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002640 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002641 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002642 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002643 return NULL;
2644 }
2645
2646 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002647 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2648 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002649 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002650 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002651 return NULL;
2652 }
Zhijun He5d677d12016-05-29 16:52:39 -07002653 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002654 auto iter = surfaceMap.find(streams.data.i32[i]);
2655 if (iter != surfaceMap.end()) {
2656 const std::vector<size_t>& surfaces = iter->second;
2657 for (const auto& surface : surfaces) {
2658 if (stream->isConsumerConfigurationDeferred(surface)) {
2659 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2660 "due to deferred consumer", stream->getId(), surface);
2661 return NULL;
2662 }
2663 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002664 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002665 }
2666
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002667 // Lazy completion of stream configuration (allocation/registration)
2668 // on first use
2669 if (stream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002670 res = stream->finishConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002671 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002672 SET_ERR_L("Unable to finish configuring stream %d: %s (%d)",
2673 stream->getId(), strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002674 return NULL;
2675 }
2676 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002677 // Check if stream prepare is blocking requests.
2678 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002679 CLOGE("Request references an output stream that's being prepared!");
2680 return NULL;
2681 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002682
2683 newRequest->mOutputStreams.push(stream);
2684 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002685 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002686 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002687
2688 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002689}
2690
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002691bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2692 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2693 Size size = mSupportedOpaqueInputSizes[i];
2694 if (size.width == width && size.height == height) {
2695 return true;
2696 }
2697 }
2698
2699 return false;
2700}
2701
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002702void Camera3Device::cancelStreamsConfigurationLocked() {
2703 int res = OK;
2704 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2705 res = mInputStream->cancelConfiguration();
2706 if (res != OK) {
2707 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2708 mInputStream->getId(), strerror(-res), res);
2709 }
2710 }
2711
2712 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002713 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002714 if (outputStream->isConfiguring()) {
2715 res = outputStream->cancelConfiguration();
2716 if (res != OK) {
2717 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2718 outputStream->getId(), strerror(-res), res);
2719 }
2720 }
2721 }
2722
2723 // Return state to that at start of call, so that future configures
2724 // properly clean things up
2725 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2726 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002727
2728 res = mPreparerThread->resume();
2729 if (res != OK) {
2730 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2731 }
2732}
2733
2734bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2735 ATRACE_CALL();
2736 bool ret = false;
2737
2738 Mutex::Autolock il(mInterfaceLock);
2739 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2740
2741 Mutex::Autolock l(mLock);
2742 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2743 if (rc == NO_ERROR) {
2744 mNeedConfig = true;
2745 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2746 if (rc == NO_ERROR) {
2747 ret = true;
2748 mPauseStateNotify = false;
2749 //Moving to active state while holding 'mLock' is important.
2750 //There could be pending calls to 'create-/deleteStream' which
2751 //will trigger another stream configuration while the already
2752 //present streams end up with outstanding buffers that will
2753 //not get drained.
2754 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002755 } else if (rc == DEAD_OBJECT) {
2756 // DEAD_OBJECT can be returned if either the consumer surface is
2757 // abandoned, or the HAL has died.
2758 // - If the HAL has died, configureStreamsLocked call will set
2759 // device to error state,
2760 // - If surface is abandoned, we should not set device to error
2761 // state.
2762 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002763 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002764 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002765 }
2766 } else {
2767 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2768 }
2769
2770 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002771}
2772
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002773status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002774 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002775 ATRACE_CALL();
2776 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002777
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002778 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002779 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002780 return INVALID_OPERATION;
2781 }
2782
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002783 if (operatingMode < 0) {
2784 CLOGE("Invalid operating mode: %d", operatingMode);
2785 return BAD_VALUE;
2786 }
2787
2788 bool isConstrainedHighSpeed =
2789 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2790 operatingMode;
2791
2792 if (mOperatingMode != operatingMode) {
2793 mNeedConfig = true;
2794 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2795 mOperatingMode = operatingMode;
2796 }
2797
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002798 if (!mNeedConfig) {
2799 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2800 return OK;
2801 }
2802
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002803 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2804 // adding a dummy stream instead.
2805 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2806 if (mOutputStreams.size() == 0) {
2807 addDummyStreamLocked();
2808 } else {
2809 tryRemoveDummyStreamLocked();
2810 }
2811
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002812 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002813 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002814
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002815 mPreparerThread->pause();
2816
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002817 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002818 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002819 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2820
2821 Vector<camera3_stream_t*> streams;
2822 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002823 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002824
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002825
2826 if (mInputStream != NULL) {
2827 camera3_stream_t *inputStream;
2828 inputStream = mInputStream->startConfiguration();
2829 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002830 CLOGE("Can't start input stream configuration");
2831 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002832 return INVALID_OPERATION;
2833 }
2834 streams.add(inputStream);
2835 }
2836
2837 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002838
2839 // Don't configure bidi streams twice, nor add them twice to the list
2840 if (mOutputStreams[i].get() ==
2841 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2842
2843 config.num_streams--;
2844 continue;
2845 }
2846
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002847 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002848 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002849 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002850 CLOGE("Can't start output stream configuration");
2851 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002852 return INVALID_OPERATION;
2853 }
2854 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002855
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002856 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002857 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2858 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002859 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2860 bufferSizes[k] = static_cast<uint32_t>(
2861 getJpegBufferSize(outputStream->width, outputStream->height));
2862 } else if (outputStream->data_space ==
2863 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2864 bufferSizes[k] = outputStream->width * outputStream->height;
2865 } else {
2866 ALOGW("%s: Blob dataSpace %d not supported",
2867 __FUNCTION__, outputStream->data_space);
2868 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002869 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002870 }
2871
2872 config.streams = streams.editArray();
2873
2874 // Do the HAL configuration; will potentially touch stream
2875 // max_buffers, usage, priv fields.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002876
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002877 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002878 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002879 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002880
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002881 if (res == BAD_VALUE) {
2882 // HAL rejected this set of streams as unsupported, clean up config
2883 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002884 CLOGE("Set of requested inputs/outputs not supported by HAL");
2885 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002886 return BAD_VALUE;
2887 } else if (res != OK) {
2888 // Some other kind of error from configure_streams - this is not
2889 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002890 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2891 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002892 return res;
2893 }
2894
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002895 // Finish all stream configuration immediately.
2896 // TODO: Try to relax this later back to lazy completion, which should be
2897 // faster
2898
Igor Murashkin073f8572013-05-02 14:59:28 -07002899 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002900 res = mInputStream->finishConfiguration();
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002901 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002902 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002903 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002904 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002905 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2906 return DEAD_OBJECT;
2907 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002908 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002909 }
2910 }
2911
2912 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002913 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002914 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002915 res = outputStream->finishConfiguration();
Igor Murashkin073f8572013-05-02 14:59:28 -07002916 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002917 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002918 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002919 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002920 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2921 return DEAD_OBJECT;
2922 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002923 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002924 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002925 }
2926 }
2927
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002928 // Request thread needs to know to avoid using repeat-last-settings protocol
2929 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002930 if (notifyRequestThread) {
2931 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
2932 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002933
Zhijun He90f7c372016-08-16 16:19:43 -07002934 char value[PROPERTY_VALUE_MAX];
2935 property_get("camera.fifo.disable", value, "0");
2936 int32_t disableFifo = atoi(value);
2937 if (disableFifo != 1) {
2938 // Boost priority of request thread to SCHED_FIFO.
2939 pid_t requestThreadTid = mRequestThread->getTid();
2940 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08002941 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07002942 if (res != OK) {
2943 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
2944 strerror(-res), res);
2945 } else {
2946 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
2947 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07002948 }
2949
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002950 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002951 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
2952 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
2953 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
2954 sessionParams.unlock(newSessionParams);
2955 mSessionParams.unlock(currentSessionParams);
2956 if (updateSessionParams) {
2957 mSessionParams = sessionParams;
2958 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002959
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002960 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002961
Ruben Brunk183f0562015-08-12 12:55:02 -07002962 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
2963 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002964
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002965 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002966
Zhijun He0a210512014-07-24 13:45:15 -07002967 // tear down the deleted streams after configure streams.
2968 mDeletedStreams.clear();
2969
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002970 auto rc = mPreparerThread->resume();
2971 if (rc != OK) {
2972 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2973 return rc;
2974 }
2975
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002976 if (mDummyStreamId == NO_STREAM) {
2977 mRequestBufferSM.onStreamsConfigured();
2978 }
2979
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002980 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002981}
2982
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002983status_t Camera3Device::addDummyStreamLocked() {
2984 ATRACE_CALL();
2985 status_t res;
2986
2987 if (mDummyStreamId != NO_STREAM) {
2988 // Should never be adding a second dummy stream when one is already
2989 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002990 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
2991 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002992 return INVALID_OPERATION;
2993 }
2994
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002995 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002996
2997 sp<Camera3OutputStreamInterface> dummyStream =
2998 new Camera3DummyStream(mNextStreamId);
2999
3000 res = mOutputStreams.add(mNextStreamId, dummyStream);
3001 if (res < 0) {
3002 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
3003 return res;
3004 }
3005
3006 mDummyStreamId = mNextStreamId;
3007 mNextStreamId++;
3008
3009 return OK;
3010}
3011
3012status_t Camera3Device::tryRemoveDummyStreamLocked() {
3013 ATRACE_CALL();
3014 status_t res;
3015
3016 if (mDummyStreamId == NO_STREAM) return OK;
3017 if (mOutputStreams.size() == 1) return OK;
3018
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003019 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003020
3021 // Ok, have a dummy stream and there's at least one other output stream,
3022 // so remove the dummy
3023
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003024 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
3025 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003026 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3027 return INVALID_OPERATION;
3028 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003029 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003030
3031 // Free up the stream endpoint so that it can be used by some other stream
3032 res = deletedStream->disconnect();
3033 if (res != OK) {
3034 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3035 // fall through since we want to still list the stream as deleted.
3036 }
3037 mDeletedStreams.add(deletedStream);
3038 mDummyStreamId = NO_STREAM;
3039
3040 return res;
3041}
3042
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003043void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003044 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003045 Mutex::Autolock l(mLock);
3046 va_list args;
3047 va_start(args, fmt);
3048
3049 setErrorStateLockedV(fmt, args);
3050
3051 va_end(args);
3052}
3053
3054void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003055 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003056 Mutex::Autolock l(mLock);
3057 setErrorStateLockedV(fmt, args);
3058}
3059
3060void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3061 va_list args;
3062 va_start(args, fmt);
3063
3064 setErrorStateLockedV(fmt, args);
3065
3066 va_end(args);
3067}
3068
3069void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003070 // Print out all error messages to log
3071 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003072 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003073
3074 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003075 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003076
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003077 mErrorCause = errorCause;
3078
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003079 if (mRequestThread != nullptr) {
3080 mRequestThread->setPaused(true);
3081 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003082 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003083
3084 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003085 sp<NotificationListener> listener = mListener.promote();
3086 if (listener != NULL) {
3087 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003088 CaptureResultExtras());
3089 }
3090
3091 // Save stack trace. View by dumping it later.
3092 CameraTraces::saveTrace();
3093 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003094}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003095
3096/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003097 * In-flight request management
3098 */
3099
Jianing Weicb0652e2014-03-12 18:29:36 -07003100status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003101 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003102 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003103 std::set<String8>& physicalCameraIds, bool isStillCapture,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003104 bool isZslCapture, const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003105 ATRACE_CALL();
3106 Mutex::Autolock l(mInFlightLock);
3107
3108 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003109 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003110 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
3111 outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003112 if (res < 0) return res;
3113
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003114 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003115 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3116 // avoid a deadlock during reprocess requests.
3117 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003118 if (mStatusTracker != nullptr) {
3119 mStatusTracker->markComponentActive(mInFlightStatusId);
3120 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003121 }
3122
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003123 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003124 return OK;
3125}
3126
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003127void Camera3Device::returnOutputBuffers(
3128 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003129 nsecs_t timestamp, bool timestampIncreasing,
3130 const SurfaceMap& outputSurfaces,
3131 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003132
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003133 for (size_t i = 0; i < numBuffers; i++)
3134 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003135 if (outputBuffers[i].buffer == nullptr) {
3136 if (!mUseHalBufManager) {
3137 // With HAL buffer management API, HAL sometimes will have to return buffers that
3138 // has not got a output buffer handle filled yet. This is though illegal if HAL
3139 // buffer management API is not being used.
3140 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3141 }
3142 continue;
3143 }
3144
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003145 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3146 int streamId = stream->getId();
3147 const auto& it = outputSurfaces.find(streamId);
3148 status_t res = OK;
3149 if (it != outputSurfaces.end()) {
3150 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003151 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3152 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003153 } else {
3154 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003155 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3156 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003157 }
3158
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003159 // Note: stream may be deallocated at this point, if this buffer was
3160 // the last reference to it.
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003161 if (res == NO_INIT || res == DEAD_OBJECT) {
3162 ALOGV("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
3163 } else if (res != OK) {
3164 ALOGE("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003165 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003166
3167 // Long processing consumers can cause returnBuffer timeout for shared stream
3168 // If that happens, cancel the buffer and send a buffer error to client
3169 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3170 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3171 // cancel the buffer
3172 camera3_stream_buffer_t sb = outputBuffers[i];
3173 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003174 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3175 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003176
3177 // notify client buffer error
3178 sp<NotificationListener> listener;
3179 {
3180 Mutex::Autolock l(mOutputLock);
3181 listener = mListener.promote();
3182 }
3183
3184 if (listener != nullptr) {
3185 CaptureResultExtras extras = inResultExtras;
3186 extras.errorStreamId = streamId;
3187 listener->notifyError(
3188 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3189 extras);
3190 }
3191 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003192 }
3193}
3194
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003195void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003196 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003197 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003198 mInFlightMap.removeItemsAt(idx, 1);
3199
3200 // Indicate idle inFlightMap to the status tracker
3201 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003202 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003203 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3204 // avoid a deadlock during reprocess requests.
3205 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003206 if (mStatusTracker != nullptr) {
3207 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3208 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003209 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003210 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003211}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003212
3213void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3214
3215 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3216 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3217
3218 nsecs_t sensorTimestamp = request.sensorTimestamp;
3219 nsecs_t shutterTimestamp = request.shutterTimestamp;
3220
3221 // Check if it's okay to remove the request from InFlightMap:
3222 // In the case of a successful request:
3223 // all input and output buffers, all result metadata, shutter callback
3224 // arrived.
3225 // In the case of a unsuccessful request:
3226 // all input and output buffers arrived.
3227 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003228 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003229 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003230 if (request.stillCapture) {
3231 ATRACE_ASYNC_END("still capture", frameNumber);
3232 }
3233
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003234 ATRACE_ASYNC_END("frame capture", frameNumber);
3235
Shuzhen Wang403044a2017-02-26 23:29:04 -08003236 // Sanity check - if sensor timestamp matches shutter timestamp in the
3237 // case of request having callback.
3238 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003239 sensorTimestamp != shutterTimestamp) {
3240 SET_ERR("sensor timestamp (%" PRId64
3241 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3242 sensorTimestamp, frameNumber, shutterTimestamp);
3243 }
3244
3245 // for an unsuccessful request, it may have pending output buffers to
3246 // return.
3247 assert(request.requestStatus != OK ||
3248 request.pendingOutputBuffers.size() == 0);
3249 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003250 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3251 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003252
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003253 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003254 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3255 }
3256
3257 // Sanity check - if we have too many in-flight frames, something has
3258 // likely gone wrong
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003259 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003260 CLOGE("In-flight list too large: %zu", mInFlightMap.size());
Chien-Yu Chenc96ac8d2015-08-12 16:46:24 -07003261 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3262 kInFlightWarnLimitHighSpeed) {
3263 CLOGE("In-flight list too large for high speed configuration: %zu",
3264 mInFlightMap.size());
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003265 }
3266}
3267
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003268void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003269 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003270 { // First return buffers cached in mInFlightMap
3271 Mutex::Autolock l(mInFlightLock);
3272 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3273 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3274 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003275 request.pendingOutputBuffers.size(), 0,
3276 /*timestampIncreasing*/true, request.outputSurfaces,
3277 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003278 }
3279 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003280 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003281 }
3282
3283 // Then return all inflight buffers not returned by HAL
3284 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3285 mInterface->getInflightBufferKeys(&inflightKeys);
3286
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003287 // Inflight buffers for HAL buffer manager
3288 std::vector<uint64_t> inflightRequestBufferKeys;
3289 mInterface->getInflightRequestBufferKeys(&inflightRequestBufferKeys);
3290
3291 // (streamId, frameNumber, buffer_handle_t*) tuple for all inflight buffers.
3292 // frameNumber will be -1 for buffers from HAL buffer manager
3293 std::vector<std::tuple<int32_t, int32_t, buffer_handle_t*>> inflightBuffers;
3294 inflightBuffers.reserve(inflightKeys.size() + inflightRequestBufferKeys.size());
3295
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003296 for (auto& pair : inflightKeys) {
3297 int32_t frameNumber = pair.first;
3298 int32_t streamId = pair.second;
3299 buffer_handle_t* buffer;
3300 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3301 if (res != OK) {
3302 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3303 __FUNCTION__, frameNumber, streamId);
3304 continue;
3305 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003306 inflightBuffers.push_back(std::make_tuple(streamId, frameNumber, buffer));
3307 }
3308
3309 for (auto& bufferId : inflightRequestBufferKeys) {
3310 int32_t streamId = -1;
3311 buffer_handle_t* buffer = nullptr;
3312 status_t res = mInterface->popInflightRequestBuffer(bufferId, &buffer, &streamId);
3313 if (res != OK) {
3314 ALOGE("%s: cannot find in-flight buffer %" PRIu64, __FUNCTION__, bufferId);
3315 continue;
3316 }
3317 inflightBuffers.push_back(std::make_tuple(streamId, /*frameNumber*/-1, buffer));
3318 }
3319
3320 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3321 for (auto& tuple : inflightBuffers) {
3322 status_t res = OK;
3323 int32_t streamId = std::get<0>(tuple);
3324 int32_t frameNumber = std::get<1>(tuple);
3325 buffer_handle_t* buffer = std::get<2>(tuple);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003326
3327 camera3_stream_buffer_t streamBuffer;
3328 streamBuffer.buffer = buffer;
3329 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3330 streamBuffer.acquire_fence = -1;
3331 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003332
3333 // First check if the buffer belongs to deleted stream
3334 bool streamDeleted = false;
3335 for (auto& stream : mDeletedStreams) {
3336 if (streamId == stream->getId()) {
3337 streamDeleted = true;
3338 // Return buffer to deleted stream
3339 camera3_stream* halStream = stream->asHalStream();
3340 streamBuffer.stream = halStream;
3341 switch (halStream->stream_type) {
3342 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003343 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3344 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003345 if (res != OK) {
3346 ALOGE("%s: Can't return output buffer for frame %d to"
3347 " stream %d: %s (%d)", __FUNCTION__,
3348 frameNumber, streamId, strerror(-res), res);
3349 }
3350 break;
3351 case CAMERA3_STREAM_INPUT:
3352 res = stream->returnInputBuffer(streamBuffer);
3353 if (res != OK) {
3354 ALOGE("%s: Can't return input buffer for frame %d to"
3355 " stream %d: %s (%d)", __FUNCTION__,
3356 frameNumber, streamId, strerror(-res), res);
3357 }
3358 break;
3359 default: // Bi-direcitonal stream is deprecated
3360 ALOGE("%s: stream %d has unknown stream type %d",
3361 __FUNCTION__, streamId, halStream->stream_type);
3362 break;
3363 }
3364 break;
3365 }
3366 }
3367 if (streamDeleted) {
3368 continue;
3369 }
3370
3371 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003372 if (streamId == inputStreamId) {
3373 streamBuffer.stream = mInputStream->asHalStream();
3374 res = mInputStream->returnInputBuffer(streamBuffer);
3375 if (res != OK) {
3376 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003377 " stream %d: %s (%d)", __FUNCTION__,
3378 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003379 }
3380 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003381 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3382 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003383 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3384 continue;
3385 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003386 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003387 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3388 }
3389 }
3390}
3391
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003392void Camera3Device::insertResultLocked(CaptureResult *result,
3393 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003394 if (result == nullptr) return;
3395
Emilian Peev71c73a22017-03-21 16:35:51 +00003396 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3397 result->mMetadata.getAndLock());
3398 set_camera_metadata_vendor_id(meta, mVendorTagId);
3399 result->mMetadata.unlock(meta);
3400
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003401 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3402 (int32_t*)&frameNumber, 1) != OK) {
3403 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3404 return;
3405 }
3406
3407 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3408 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3409 return;
3410 }
3411
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003412 // Valid result, insert into queue
3413 List<CaptureResult>::iterator queuedResult =
3414 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3415 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3416 ", burstId = %" PRId32, __FUNCTION__,
3417 queuedResult->mResultExtras.requestId,
3418 queuedResult->mResultExtras.frameNumber,
3419 queuedResult->mResultExtras.burstId);
3420
3421 mResultSignal.signal();
3422}
3423
3424
3425void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003426 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003427 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003428 Mutex::Autolock l(mOutputLock);
3429
3430 CaptureResult captureResult;
3431 captureResult.mResultExtras = resultExtras;
3432 captureResult.mMetadata = partialResult;
3433
Shuzhen Wang268a1362018-10-16 16:32:59 -07003434 // Fix up result metadata for monochrome camera.
3435 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3436 if (res != OK) {
3437 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3438 return;
3439 }
3440
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003441 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003442}
3443
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003444
3445void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3446 CaptureResultExtras &resultExtras,
3447 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003448 uint32_t frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003449 bool reprocess,
3450 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003451 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003452 if (pendingMetadata.isEmpty())
3453 return;
3454
3455 Mutex::Autolock l(mOutputLock);
3456
3457 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003458 if (reprocess) {
3459 if (frameNumber < mNextReprocessResultFrameNumber) {
3460 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003461 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003462 frameNumber, mNextReprocessResultFrameNumber);
3463 return;
3464 }
3465 mNextReprocessResultFrameNumber = frameNumber + 1;
3466 } else {
3467 if (frameNumber < mNextResultFrameNumber) {
3468 SET_ERR("Out-of-order capture result metadata submitted! "
3469 "(got frame number %d, expecting %d)",
3470 frameNumber, mNextResultFrameNumber);
3471 return;
3472 }
3473 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003474 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003475
3476 CaptureResult captureResult;
3477 captureResult.mResultExtras = resultExtras;
3478 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003479 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003480
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003481 // Append any previous partials to form a complete result
3482 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3483 captureResult.mMetadata.append(collectedPartialResult);
3484 }
3485
3486 captureResult.mMetadata.sort();
3487
3488 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003489 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3490 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003491 SET_ERR("No timestamp provided by HAL for frame %d!",
3492 frameNumber);
3493 return;
3494 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003495 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3496 camera_metadata_entry timestamp =
3497 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3498 if (timestamp.count == 0) {
3499 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3500 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3501 return;
3502 }
3503 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003504
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003505 // Fix up some result metadata to account for HAL-level distortion correction
3506 status_t res = mDistortionMapper.correctCaptureResult(&captureResult.mMetadata);
3507 if (res != OK) {
3508 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
3509 frameNumber, strerror(res), res);
3510 return;
3511 }
Shuzhen Wang268a1362018-10-16 16:32:59 -07003512 // Fix up result metadata for monochrome camera.
3513 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3514 if (res != OK) {
3515 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3516 return;
3517 }
3518 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3519 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3520 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3521 physicalMetadata.mPhysicalCameraMetadata);
3522 if (res != OK) {
3523 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3524 return;
3525 }
3526 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003527
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003528 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
3529 frameNumber, timestamp.data.i64[0], captureResult.mMetadata);
3530
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003531 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003532}
3533
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003534/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003535 * Camera HAL device callback methods
3536 */
3537
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003538void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003539 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003540
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003541 status_t res;
3542
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003543 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003544 if (result->result == NULL && result->num_output_buffers == 0 &&
3545 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003546 SET_ERR("No result data provided by HAL for frame %d",
3547 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003548 return;
3549 }
Zhijun He204e3292014-07-14 17:09:23 -07003550
Zhijun He204e3292014-07-14 17:09:23 -07003551 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003552 result->result != NULL &&
3553 result->partial_result != 1) {
3554 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3555 " if partial result is not supported",
3556 frameNumber, result->partial_result);
3557 return;
3558 }
3559
3560 bool isPartialResult = false;
3561 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003562 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003563
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003564 // Get shutter timestamp and resultExtras from list of in-flight requests,
3565 // where it was added by the shutter notification for this frame. If the
3566 // shutter timestamp isn't received yet, append the output buffers to the
3567 // in-flight request and they will be returned when the shutter timestamp
3568 // arrives. Update the in-flight status and remove the in-flight entry if
3569 // all result data and shutter timestamp have been received.
3570 nsecs_t shutterTimestamp = 0;
3571
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003572 {
3573 Mutex::Autolock l(mInFlightLock);
3574 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3575 if (idx == NAME_NOT_FOUND) {
3576 SET_ERR("Unknown frame number for capture result: %d",
3577 frameNumber);
3578 return;
3579 }
3580 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003581 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3582 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003583 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003584 __FUNCTION__, request.resultExtras.requestId,
3585 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003586 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003587 // Always update the partial count to the latest one if it's not 0
3588 // (buffers only). When framework aggregates adjacent partial results
3589 // into one, the latest partial count will be used.
3590 if (result->partial_result != 0)
3591 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003592
3593 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003594 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003595 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3596 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3597 " the range of [1, %d] when metadata is included in the result",
3598 frameNumber, result->partial_result, mNumPartialResults);
3599 return;
3600 }
3601 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003602 if (isPartialResult && result->num_physcam_metadata) {
3603 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3604 " physical camera result", frameNumber);
3605 return;
3606 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003607 if (isPartialResult) {
3608 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003609 }
3610
Shuzhen Wang4a472662017-02-26 23:29:04 -08003611 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003612 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003613 sendPartialCaptureResult(result->result, request.resultExtras,
3614 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003615 }
3616 }
3617
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003618 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003619 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003620
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003621 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003622 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003623 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
3624 SET_ERR("Requested physical Camera Ids %d not equal to number of metadata %d",
3625 request.physicalCameraIds.size(), result->num_physcam_metadata);
3626 return;
3627 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003628 if (request.haveResultMetadata) {
3629 SET_ERR("Called multiple times with metadata for frame %d",
3630 frameNumber);
3631 return;
3632 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003633 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3634 String8 physicalId(result->physcam_ids[i]);
3635 std::set<String8>::iterator cameraIdIter =
3636 request.physicalCameraIds.find(physicalId);
3637 if (cameraIdIter != request.physicalCameraIds.end()) {
3638 request.physicalCameraIds.erase(cameraIdIter);
3639 } else {
3640 SET_ERR("Total result for frame %d has already returned for camera %s",
3641 frameNumber, physicalId.c_str());
3642 return;
3643 }
3644 }
Zhijun He204e3292014-07-14 17:09:23 -07003645 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003646 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003647 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003648 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003649 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003650 request.haveResultMetadata = true;
3651 }
3652
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003653 uint32_t numBuffersReturned = result->num_output_buffers;
3654 if (result->input_buffer != NULL) {
3655 if (hasInputBufferInRequest) {
3656 numBuffersReturned += 1;
3657 } else {
3658 ALOGW("%s: Input buffer should be NULL if there is no input"
3659 " buffer sent in the request",
3660 __FUNCTION__);
3661 }
3662 }
3663 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003664 if (request.numBuffersLeft < 0) {
3665 SET_ERR("Too many buffers returned for frame %d",
3666 frameNumber);
3667 return;
3668 }
3669
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003670 camera_metadata_ro_entry_t entry;
3671 res = find_camera_metadata_ro_entry(result->result,
3672 ANDROID_SENSOR_TIMESTAMP, &entry);
3673 if (res == OK && entry.count == 1) {
3674 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003675 }
3676
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003677 // If shutter event isn't received yet, append the output buffers to
3678 // the in-flight request. Otherwise, return the output buffers to
3679 // streams.
3680 if (shutterTimestamp == 0) {
3681 request.pendingOutputBuffers.appendArray(result->output_buffers,
3682 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003683 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003684 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003685 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003686 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3687 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003688 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003689
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003690 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003691 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3692 CameraMetadata physicalMetadata;
3693 physicalMetadata.append(result->physcam_metadata[i]);
3694 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3695 physicalMetadata});
3696 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003697 if (shutterTimestamp == 0) {
3698 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003699 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003700 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003701 CameraMetadata metadata;
3702 metadata = result->result;
3703 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003704 collectedPartialResult, frameNumber,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003705 hasInputBufferInRequest, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003706 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003707 }
3708
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003709 removeInFlightRequestIfReadyLocked(idx);
3710 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003711
Zhijun Hef0d962a2014-06-30 10:24:11 -07003712 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003713 if (hasInputBufferInRequest) {
3714 Camera3Stream *stream =
3715 Camera3Stream::cast(result->input_buffer->stream);
3716 res = stream->returnInputBuffer(*(result->input_buffer));
3717 // Note: stream may be deallocated at this point, if this buffer was the
3718 // last reference to it.
3719 if (res != OK) {
3720 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3721 " its stream:%s (%d)", __FUNCTION__,
3722 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003723 }
3724 } else {
3725 ALOGW("%s: Input buffer should be NULL if there is no input"
3726 " buffer sent in the request, skipping input buffer return.",
3727 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003728 }
3729 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003730}
3731
3732void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003733 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003734 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003735 {
3736 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003737 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003738 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003739
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003740 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003741 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003742 return;
3743 }
3744
3745 switch (msg->type) {
3746 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003747 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003748 break;
3749 }
3750 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003751 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003752 break;
3753 }
3754 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003755 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003756 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003757 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003758}
3759
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003760void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003761 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003762 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003763 // Map camera HAL error codes to ICameraDeviceCallback error codes
3764 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003765 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003766 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003767 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003768 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003769 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003770 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003771 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003772 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003773 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003774 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003775 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003776 };
3777
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003778 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003779 ((msg.error_code >= 0) &&
3780 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3781 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003782 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003783
3784 int streamId = 0;
3785 if (msg.error_stream != NULL) {
3786 Camera3Stream *stream =
3787 Camera3Stream::cast(msg.error_stream);
3788 streamId = stream->getId();
3789 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003790 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3791 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003792 streamId, msg.error_code);
3793
3794 CaptureResultExtras resultExtras;
3795 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003796 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003797 // SET_ERR calls notifyError
3798 SET_ERR("Camera HAL reported serious device error");
3799 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003800 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3801 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3802 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003803 {
3804 Mutex::Autolock l(mInFlightLock);
3805 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3806 if (idx >= 0) {
3807 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3808 r.requestStatus = msg.error_code;
3809 resultExtras = r.resultExtras;
Shuzhen Wang20f57342017-08-24 15:39:05 -07003810 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT == errorCode
3811 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3812 errorCode) {
3813 r.skipResultMetadata = true;
3814 }
Emilian Peevba0fac32017-03-30 09:05:34 +01003815 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3816 errorCode) {
3817 // In case of missing result check whether the buffers
3818 // returned. If they returned, then remove inflight
3819 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003820 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3821 // otherwise we are depending on HAL to send the buffers back after
3822 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003823 removeInFlightRequestIfReadyLocked(idx);
3824 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003825 } else {
3826 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003827 ALOGE("Camera %s: %s: cannot find in-flight request on "
3828 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003829 resultExtras.frameNumber);
3830 }
3831 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003832 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003833 if (listener != NULL) {
3834 listener->notifyError(errorCode, resultExtras);
3835 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003836 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003837 }
3838 break;
3839 default:
3840 // SET_ERR calls notifyError
3841 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
3842 break;
3843 }
3844}
3845
3846void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003847 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003848 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003849 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003850
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003851 // Set timestamp for the request in the in-flight tracking
3852 // and get the request ID to send upstream
3853 {
3854 Mutex::Autolock l(mInFlightLock);
3855 idx = mInFlightMap.indexOfKey(msg.frame_number);
3856 if (idx >= 0) {
3857 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003858
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07003859 // Verify ordering of shutter notifications
3860 {
3861 Mutex::Autolock l(mOutputLock);
3862 // TODO: need to track errors for tighter bounds on expected frame number.
3863 if (r.hasInputBuffer) {
3864 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
3865 SET_ERR("Shutter notification out-of-order. Expected "
3866 "notification for frame %d, got frame %d",
3867 mNextReprocessShutterFrameNumber, msg.frame_number);
3868 return;
3869 }
3870 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
3871 } else {
3872 if (msg.frame_number < mNextShutterFrameNumber) {
3873 SET_ERR("Shutter notification out-of-order. Expected "
3874 "notification for frame %d, got frame %d",
3875 mNextShutterFrameNumber, msg.frame_number);
3876 return;
3877 }
3878 mNextShutterFrameNumber = msg.frame_number + 1;
3879 }
3880 }
3881
Shuzhen Wang4a472662017-02-26 23:29:04 -08003882 r.shutterTimestamp = msg.timestamp;
3883 if (r.hasCallback) {
3884 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003885 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003886 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08003887 // Call listener, if any
3888 if (listener != NULL) {
3889 listener->notifyShutter(r.resultExtras, msg.timestamp);
3890 }
3891 // send pending result and buffers
3892 sendCaptureResult(r.pendingMetadata, r.resultExtras,
3893 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003894 r.hasInputBuffer, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003895 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003896 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003897 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003898 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
3899 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003900 r.pendingOutputBuffers.clear();
3901
3902 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003903 }
3904 }
3905 if (idx < 0) {
3906 SET_ERR("Shutter notification for non-existent frame number %d",
3907 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003908 }
3909}
3910
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003911CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07003912 ALOGV("%s", __FUNCTION__);
3913
Igor Murashkin1e479c02013-09-06 16:55:14 -07003914 CameraMetadata retVal;
3915
3916 if (mRequestThread != NULL) {
3917 retVal = mRequestThread->getLatestRequest();
3918 }
3919
Igor Murashkin1e479c02013-09-06 16:55:14 -07003920 return retVal;
3921}
3922
Jianing Weicb0652e2014-03-12 18:29:36 -07003923
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003924void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
3925 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata) {
3926 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata);
3927}
3928
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003929/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003930 * HalInterface inner class methods
3931 */
3932
Yifan Hongf79b5542017-04-11 14:44:25 -07003933Camera3Device::HalInterface::HalInterface(
3934 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003935 std::shared_ptr<RequestMetadataQueue> queue,
3936 bool useHalBufManager) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003937 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003938 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08003939 mUseHalBufManager(useHalBufManager),
3940 mIsReconfigurationQuerySupported(true) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003941 // Check with hardware service manager if we can downcast these interfaces
3942 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07003943 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
3944 if (castResult_3_5.isOk()) {
3945 mHidlSession_3_5 = castResult_3_5;
3946 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003947 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
3948 if (castResult_3_4.isOk()) {
3949 mHidlSession_3_4 = castResult_3_4;
3950 }
3951 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
3952 if (castResult_3_3.isOk()) {
3953 mHidlSession_3_3 = castResult_3_3;
3954 }
3955}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003956
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003957Camera3Device::HalInterface::HalInterface() : mUseHalBufManager(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003958
3959Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07003960 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003961 mRequestMetadataQueue(other.mRequestMetadataQueue),
3962 mUseHalBufManager(other.mUseHalBufManager) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003963
3964bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01003965 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003966}
3967
3968void Camera3Device::HalInterface::clear() {
Emilian Peev644a3e12018-11-23 13:52:39 +00003969 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00003970 mHidlSession_3_4.clear();
3971 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003972 mHidlSession.clear();
3973}
3974
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08003975bool Camera3Device::HalInterface::supportBatchRequest() {
3976 return mHidlSession != nullptr;
3977}
3978
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003979status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
3980 camera3_request_template_t templateId,
3981 /*out*/ camera_metadata_t **requestTemplate) {
3982 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
3983 if (!valid()) return INVALID_OPERATION;
3984 status_t res = OK;
3985
Emilian Peev31abd0a2017-05-11 18:37:46 +01003986 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003987
3988 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01003989 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08003990 status = s;
3991 if (status == common::V1_0::Status::OK) {
3992 const camera_metadata *r =
3993 reinterpret_cast<const camera_metadata_t*>(request.data());
3994 size_t expectedSize = request.size();
3995 int ret = validate_camera_metadata_structure(r, &expectedSize);
3996 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
3997 *requestTemplate = clone_camera_metadata(r);
3998 if (*requestTemplate == nullptr) {
3999 ALOGE("%s: Unable to clone camera metadata received from HAL",
4000 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004001 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004002 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004003 } else {
4004 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
4005 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004006 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004007 }
4008 };
4009 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004010 RequestTemplate id;
4011 switch (templateId) {
4012 case CAMERA3_TEMPLATE_PREVIEW:
4013 id = RequestTemplate::PREVIEW;
4014 break;
4015 case CAMERA3_TEMPLATE_STILL_CAPTURE:
4016 id = RequestTemplate::STILL_CAPTURE;
4017 break;
4018 case CAMERA3_TEMPLATE_VIDEO_RECORD:
4019 id = RequestTemplate::VIDEO_RECORD;
4020 break;
4021 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
4022 id = RequestTemplate::VIDEO_SNAPSHOT;
4023 break;
4024 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
4025 id = RequestTemplate::ZERO_SHUTTER_LAG;
4026 break;
4027 case CAMERA3_TEMPLATE_MANUAL:
4028 id = RequestTemplate::MANUAL;
4029 break;
4030 default:
4031 // Unknown template ID, or this HAL is too old to support it
4032 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004033 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004034 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004035
Emilian Peev31abd0a2017-05-11 18:37:46 +01004036 if (!err.isOk()) {
4037 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4038 res = DEAD_OBJECT;
4039 } else {
4040 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004041 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004042
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004043 return res;
4044}
4045
Emilian Peev4ec17882019-01-24 17:16:58 -08004046bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4047 CameraMetadata& newSessionParams) {
4048 // We do reconfiguration by default;
4049 bool ret = true;
4050 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4051 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4052 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4053 oldSessionParams.getAndLock());
4054 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4055 newSessionParams.getAndLock());
4056 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4057 get_camera_metadata_size(oldSessioMeta));
4058 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4059 get_camera_metadata_size(newSessioMeta));
4060 hardware::camera::common::V1_0::Status callStatus;
4061 bool required;
4062 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4063 bool requiredFlag) {
4064 callStatus = s;
4065 required = requiredFlag;
4066 };
4067 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4068 oldSessionParams.unlock(oldSessioMeta);
4069 newSessionParams.unlock(newSessioMeta);
4070 if (err.isOk()) {
4071 switch (callStatus) {
4072 case hardware::camera::common::V1_0::Status::OK:
4073 ret = required;
4074 break;
4075 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4076 mIsReconfigurationQuerySupported = false;
4077 ret = true;
4078 break;
4079 default:
4080 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4081 ret = true;
4082 }
4083 } else {
4084 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4085 ret = true;
4086 }
4087 }
4088
4089 return ret;
4090}
4091
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004092status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004093 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004094 ATRACE_NAME("CameraHal::configureStreams");
4095 if (!valid()) return INVALID_OPERATION;
4096 status_t res = OK;
4097
Emilian Peev31abd0a2017-05-11 18:37:46 +01004098 // Convert stream config to HIDL
4099 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004100 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4101 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4102 requestedConfiguration3_2.streams.resize(config->num_streams);
4103 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004104 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004105 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4106 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004107 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004108
Emilian Peev31abd0a2017-05-11 18:37:46 +01004109 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4110 cam3stream->setBufferFreedListener(this);
4111 int streamId = cam3stream->getId();
4112 StreamType streamType;
4113 switch (src->stream_type) {
4114 case CAMERA3_STREAM_OUTPUT:
4115 streamType = StreamType::OUTPUT;
4116 break;
4117 case CAMERA3_STREAM_INPUT:
4118 streamType = StreamType::INPUT;
4119 break;
4120 default:
4121 ALOGE("%s: Stream %d: Unsupported stream type %d",
4122 __FUNCTION__, streamId, config->streams[i]->stream_type);
4123 return BAD_VALUE;
4124 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004125 dst3_2.id = streamId;
4126 dst3_2.streamType = streamType;
4127 dst3_2.width = src->width;
4128 dst3_2.height = src->height;
4129 dst3_2.format = mapToPixelFormat(src->format);
4130 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
4131 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4132 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
4133 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004134 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004135 if (src->physical_camera_id != nullptr) {
4136 dst3_4.physicalCameraId = src->physical_camera_id;
4137 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004138
4139 activeStreams.insert(streamId);
4140 // Create Buffer ID map if necessary
4141 if (mBufferIdMaps.count(streamId) == 0) {
4142 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4143 }
4144 }
4145 // remove BufferIdMap for deleted streams
4146 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4147 int streamId = it->first;
4148 bool active = activeStreams.count(streamId) > 0;
4149 if (!active) {
4150 it = mBufferIdMaps.erase(it);
4151 } else {
4152 ++it;
4153 }
4154 }
4155
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004156 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004157 res = mapToStreamConfigurationMode(
4158 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004159 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004160 if (res != OK) {
4161 return res;
4162 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004163 requestedConfiguration3_2.operationMode = operationMode;
4164 requestedConfiguration3_4.operationMode = operationMode;
4165 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004166 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4167 get_camera_metadata_size(sessionParams));
4168
Emilian Peev31abd0a2017-05-11 18:37:46 +01004169 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004170 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004171 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004172 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004173
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004174 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004175 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4176 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004177 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004178 };
4179
4180 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4181 (hardware::Return<void>& err) -> status_t {
4182 if (!err.isOk()) {
4183 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4184 return DEAD_OBJECT;
4185 }
4186 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4187 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4188 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4189 }
4190 return OK;
4191 };
4192
4193 // See if we have v3.4 or v3.3 HAL
4194 if (mHidlSession_3_5 != nullptr) {
4195 ALOGV("%s: v3.5 device found", __FUNCTION__);
4196 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4197 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4198 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4199 auto err = mHidlSession_3_5->configureStreams_3_5(
4200 requestedConfiguration3_5, configStream34Cb);
4201 res = postprocConfigStream34(err);
4202 if (res != OK) {
4203 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004204 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004205 } else if (mHidlSession_3_4 != nullptr) {
4206 // We do; use v3.4 for the call
4207 ALOGV("%s: v3.4 device found", __FUNCTION__);
4208 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
4209 auto err = mHidlSession_3_4->configureStreams_3_4(
4210 requestedConfiguration3_4, configStream34Cb);
4211 res = postprocConfigStream34(err);
4212 if (res != OK) {
4213 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004214 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004215 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004216 // We do; use v3.3 for the call
4217 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004218 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004219 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004220 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004221 finalConfiguration = halConfiguration;
4222 status = s;
4223 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004224 if (!err.isOk()) {
4225 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4226 return DEAD_OBJECT;
4227 }
4228 } else {
4229 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4230 ALOGV("%s: v3.2 device found", __FUNCTION__);
4231 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004232 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004233 [&status, &finalConfiguration_3_2]
4234 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4235 finalConfiguration_3_2 = halConfiguration;
4236 status = s;
4237 });
4238 if (!err.isOk()) {
4239 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4240 return DEAD_OBJECT;
4241 }
4242 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4243 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4244 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4245 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004246 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004247 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004248 }
4249
4250 if (status != common::V1_0::Status::OK ) {
4251 return CameraProviderManager::mapToStatusT(status);
4252 }
4253
4254 // And convert output stream configuration from HIDL
4255
4256 for (size_t i = 0; i < config->num_streams; i++) {
4257 camera3_stream_t *dst = config->streams[i];
4258 int streamId = Camera3Stream::cast(dst)->getId();
4259
4260 // Start scan at i, with the assumption that the stream order matches
4261 size_t realIdx = i;
4262 bool found = false;
4263 for (size_t idx = 0; idx < finalConfiguration.streams.size(); idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004264 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004265 found = true;
4266 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004267 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004268 realIdx = (realIdx >= finalConfiguration.streams.size()) ? 0 : realIdx + 1;
4269 }
4270 if (!found) {
4271 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4272 __FUNCTION__, streamId);
4273 return INVALID_OPERATION;
4274 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004275 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004276
Emilian Peev710c1422017-08-30 11:19:38 +01004277 Camera3Stream* dstStream = Camera3Stream::cast(dst);
4278 dstStream->setFormatOverride(false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004279 dstStream->setDataSpaceOverride(false);
4280 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4281 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4282
Emilian Peev31abd0a2017-05-11 18:37:46 +01004283 if (dst->format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
4284 if (dst->format != overrideFormat) {
4285 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4286 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004287 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004288 if (dst->data_space != overrideDataSpace) {
4289 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4290 streamId, dst->format);
4291 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004292 } else {
Emilian Peev710c1422017-08-30 11:19:38 +01004293 dstStream->setFormatOverride((dst->format != overrideFormat) ? true : false);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004294 dstStream->setDataSpaceOverride((dst->data_space != overrideDataSpace) ? true : false);
4295
Emilian Peev31abd0a2017-05-11 18:37:46 +01004296 // Override allowed with IMPLEMENTATION_DEFINED
4297 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004298 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004299 }
4300
Emilian Peev31abd0a2017-05-11 18:37:46 +01004301 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004302 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004303 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004304 __FUNCTION__, streamId);
4305 return INVALID_OPERATION;
4306 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004307 dstStream->setUsage(
4308 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004309 } else {
4310 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004311 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004312 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4313 __FUNCTION__, streamId);
4314 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004315 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004316 dstStream->setUsage(
4317 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004318 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004319 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004320 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004321
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004322 return res;
4323}
4324
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004325status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004326 /*out*/device::V3_2::CaptureRequest* captureRequest,
4327 /*out*/std::vector<native_handle_t*>* handlesCreated) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004328 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004329 if (captureRequest == nullptr || handlesCreated == nullptr) {
4330 ALOGE("%s: captureRequest (%p) and handlesCreated (%p) must not be null",
4331 __FUNCTION__, captureRequest, handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004332 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004333 }
4334
4335 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004336
4337 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004338
4339 {
4340 std::lock_guard<std::mutex> lock(mInflightLock);
4341 if (request->input_buffer != nullptr) {
4342 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4343 buffer_handle_t buf = *(request->input_buffer->buffer);
4344 auto pair = getBufferId(buf, streamId);
4345 bool isNewBuffer = pair.first;
4346 uint64_t bufferId = pair.second;
4347 captureRequest->inputBuffer.streamId = streamId;
4348 captureRequest->inputBuffer.bufferId = bufferId;
4349 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4350 captureRequest->inputBuffer.status = BufferStatus::OK;
4351 native_handle_t *acquireFence = nullptr;
4352 if (request->input_buffer->acquire_fence != -1) {
4353 acquireFence = native_handle_create(1,0);
4354 acquireFence->data[0] = request->input_buffer->acquire_fence;
4355 handlesCreated->push_back(acquireFence);
4356 }
4357 captureRequest->inputBuffer.acquireFence = acquireFence;
4358 captureRequest->inputBuffer.releaseFence = nullptr;
4359
4360 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4361 request->input_buffer->buffer,
4362 request->input_buffer->acquire_fence);
4363 } else {
4364 captureRequest->inputBuffer.streamId = -1;
4365 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4366 }
4367
4368 captureRequest->outputBuffers.resize(request->num_output_buffers);
4369 for (size_t i = 0; i < request->num_output_buffers; i++) {
4370 const camera3_stream_buffer_t *src = request->output_buffers + i;
4371 StreamBuffer &dst = captureRequest->outputBuffers[i];
4372 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004373 if (src->buffer != nullptr) {
4374 buffer_handle_t buf = *(src->buffer);
4375 auto pair = getBufferId(buf, streamId);
4376 bool isNewBuffer = pair.first;
4377 dst.bufferId = pair.second;
4378 dst.buffer = isNewBuffer ? buf : nullptr;
4379 native_handle_t *acquireFence = nullptr;
4380 if (src->acquire_fence != -1) {
4381 acquireFence = native_handle_create(1,0);
4382 acquireFence->data[0] = src->acquire_fence;
4383 handlesCreated->push_back(acquireFence);
4384 }
4385 dst.acquireFence = acquireFence;
4386 } else if (mUseHalBufManager) {
4387 // HAL buffer management path
4388 dst.bufferId = BUFFER_ID_NO_BUFFER;
4389 dst.buffer = nullptr;
4390 dst.acquireFence = nullptr;
4391 } else {
4392 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4393 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004394 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004395 dst.streamId = streamId;
4396 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004397 dst.releaseFence = nullptr;
4398
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004399 // Output buffers are empty when using HAL buffer manager
4400 if (!mUseHalBufManager) {
4401 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
4402 src->buffer, src->acquire_fence);
4403 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004404 }
4405 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004406 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004407}
4408
4409status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4410 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4411 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4412 if (!valid()) return INVALID_OPERATION;
4413
Emilian Peevaebbe412018-01-15 13:53:24 +00004414 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4415 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4416 if (castResult_3_4.isOk()) {
4417 hidlSession_3_4 = castResult_3_4;
4418 }
4419
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004420 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004421 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004422 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004423 if (hidlSession_3_4 != nullptr) {
4424 captureRequests_3_4.resize(batchSize);
4425 } else {
4426 captureRequests.resize(batchSize);
4427 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004428 std::vector<native_handle_t*> handlesCreated;
4429
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004430 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004431 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004432 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004433 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Emilian Peevaebbe412018-01-15 13:53:24 +00004434 /*out*/&handlesCreated);
4435 } else {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004436 res = wrapAsHidlRequest(requests[i],
4437 /*out*/&captureRequests[i], /*out*/&handlesCreated);
4438 }
4439 if (res != OK) {
4440 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004441 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004442 }
4443
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004444 std::vector<device::V3_2::BufferCache> cachesToRemove;
4445 {
4446 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4447 for (auto& pair : mFreedBuffers) {
4448 // The stream might have been removed since onBufferFreed
4449 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4450 cachesToRemove.push_back({pair.first, pair.second});
4451 }
4452 }
4453 mFreedBuffers.clear();
4454 }
4455
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004456 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4457 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004458
4459 // Write metadata to FMQ.
4460 for (size_t i = 0; i < batchSize; i++) {
4461 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004462 device::V3_2::CaptureRequest* captureRequest;
4463 if (hidlSession_3_4 != nullptr) {
4464 captureRequest = &captureRequests_3_4[i].v3_2;
4465 } else {
4466 captureRequest = &captureRequests[i];
4467 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004468
4469 if (request->settings != nullptr) {
4470 size_t settingsSize = get_camera_metadata_size(request->settings);
4471 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4472 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4473 captureRequest->settings.resize(0);
4474 captureRequest->fmqSettingsSize = settingsSize;
4475 } else {
4476 if (mRequestMetadataQueue != nullptr) {
4477 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4478 }
4479 captureRequest->settings.setToExternal(
4480 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4481 get_camera_metadata_size(request->settings));
4482 captureRequest->fmqSettingsSize = 0u;
4483 }
4484 } else {
4485 // A null request settings maps to a size-0 CameraMetadata
4486 captureRequest->settings.resize(0);
4487 captureRequest->fmqSettingsSize = 0u;
4488 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004489
4490 if (hidlSession_3_4 != nullptr) {
4491 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4492 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004493 if (request->physcam_settings != nullptr) {
4494 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4495 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4496 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4497 settingsSize)) {
4498 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4499 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4500 settingsSize;
4501 } else {
4502 if (mRequestMetadataQueue != nullptr) {
4503 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4504 }
4505 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4506 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4507 request->physcam_settings[j])),
4508 get_camera_metadata_size(request->physcam_settings[j]));
4509 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004510 }
Emilian Peev00420d22018-02-05 21:33:13 +00004511 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004512 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004513 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004514 }
4515 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4516 request->physcam_id[j];
4517 }
4518 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004519 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004520
4521 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004522 auto resultCallback =
4523 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4524 status = s;
4525 *numRequestProcessed = n;
4526 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004527 if (hidlSession_3_4 != nullptr) {
4528 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004529 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004530 } else {
4531 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004532 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004533 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004534 if (!err.isOk()) {
4535 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4536 return DEAD_OBJECT;
4537 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004538 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4539 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4540 __FUNCTION__, *numRequestProcessed, batchSize);
4541 status = common::V1_0::Status::INTERNAL_ERROR;
4542 }
4543
4544 for (auto& handle : handlesCreated) {
4545 native_handle_delete(handle);
4546 }
4547 return CameraProviderManager::mapToStatusT(status);
4548}
4549
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004550status_t Camera3Device::HalInterface::processCaptureRequest(
4551 camera3_capture_request_t *request) {
4552 ATRACE_NAME("CameraHal::processCaptureRequest");
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004553 if (!valid()) return INVALID_OPERATION;
4554 status_t res = OK;
4555
Emilian Peev31abd0a2017-05-11 18:37:46 +01004556 uint32_t numRequestProcessed = 0;
4557 std::vector<camera3_capture_request_t*> requests(1);
4558 requests[0] = request;
4559 res = processBatchCaptureRequests(requests, &numRequestProcessed);
4560
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004561 return res;
4562}
4563
4564status_t Camera3Device::HalInterface::flush() {
4565 ATRACE_NAME("CameraHal::flush");
4566 if (!valid()) return INVALID_OPERATION;
4567 status_t res = OK;
4568
Emilian Peev31abd0a2017-05-11 18:37:46 +01004569 auto err = mHidlSession->flush();
4570 if (!err.isOk()) {
4571 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4572 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004573 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004574 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004575 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004576
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004577 return res;
4578}
4579
Emilian Peev31abd0a2017-05-11 18:37:46 +01004580status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004581 ATRACE_NAME("CameraHal::dump");
4582 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004583
Emilian Peev31abd0a2017-05-11 18:37:46 +01004584 // Handled by CameraProviderManager::dump
4585
4586 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004587}
4588
4589status_t Camera3Device::HalInterface::close() {
4590 ATRACE_NAME("CameraHal::close()");
4591 if (!valid()) return INVALID_OPERATION;
4592 status_t res = OK;
4593
Emilian Peev31abd0a2017-05-11 18:37:46 +01004594 auto err = mHidlSession->close();
4595 // Interface will be dead shortly anyway, so don't log errors
4596 if (!err.isOk()) {
4597 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004598 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004599
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004600 return res;
4601}
4602
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004603void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4604 ATRACE_NAME("CameraHal::signalPipelineDrain");
4605 if (!valid() || mHidlSession_3_5 == nullptr) {
4606 ALOGE("%s called on invalid camera!", __FUNCTION__);
4607 return;
4608 }
4609
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004610 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004611 if (!err.isOk()) {
4612 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4613 return;
4614 }
4615}
4616
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004617void Camera3Device::HalInterface::getInflightBufferKeys(
4618 std::vector<std::pair<int32_t, int32_t>>* out) {
4619 std::lock_guard<std::mutex> lock(mInflightLock);
4620 out->clear();
4621 out->reserve(mInflightBufferMap.size());
4622 for (auto& pair : mInflightBufferMap) {
4623 uint64_t key = pair.first;
4624 int32_t streamId = key & 0xFFFFFFFF;
4625 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4626 out->push_back(std::make_pair(frameNumber, streamId));
4627 }
4628 return;
4629}
4630
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004631void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4632 std::vector<uint64_t>* out) {
4633 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4634 out->clear();
4635 out->reserve(mRequestedBuffers.size());
4636 for (auto& pair : mRequestedBuffers) {
4637 out->push_back(pair.first);
4638 }
4639 return;
4640}
4641
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004642status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004643 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer, int acquireFence) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004644 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004645 auto pair = std::make_pair(buffer, acquireFence);
4646 mInflightBufferMap[key] = pair;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004647 return OK;
4648}
4649
4650status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004651 int32_t frameNumber, int32_t streamId,
4652 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004653 std::lock_guard<std::mutex> lock(mInflightLock);
4654
4655 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4656 auto it = mInflightBufferMap.find(key);
4657 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004658 auto pair = it->second;
4659 *buffer = pair.first;
4660 int acquireFence = pair.second;
4661 if (acquireFence > 0) {
4662 ::close(acquireFence);
4663 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004664 mInflightBufferMap.erase(it);
4665 return OK;
4666}
4667
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004668status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004669 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004670 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004671 auto pair = mRequestedBuffers.insert({bufferId, {streamId, buf}});
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004672 if (!pair.second) {
4673 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4674 __FUNCTION__, bufferId);
4675 return BAD_VALUE;
4676 }
4677 return OK;
4678}
4679
4680// Find and pop a buffer_handle_t based on bufferId
4681status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004682 uint64_t bufferId,
4683 /*out*/ buffer_handle_t** buffer,
4684 /*optional out*/ int32_t* streamId) {
4685 if (buffer == nullptr) {
4686 ALOGE("%s: buffer (%p) must not be null", __FUNCTION__, buffer);
4687 return BAD_VALUE;
4688 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004689 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4690 auto it = mRequestedBuffers.find(bufferId);
4691 if (it == mRequestedBuffers.end()) {
4692 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4693 __FUNCTION__, bufferId);
4694 return BAD_VALUE;
4695 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004696 *buffer = it->second.second;
4697 if (streamId != nullptr) {
4698 *streamId = it->second.first;
4699 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004700 mRequestedBuffers.erase(it);
4701 return OK;
4702}
4703
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004704std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4705 const buffer_handle_t& buf, int streamId) {
4706 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4707
4708 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4709 auto it = bIdMap.find(buf);
4710 if (it == bIdMap.end()) {
4711 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004712 ALOGV("stream %d now have %zu buffer caches, buf %p",
4713 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004714 return std::make_pair(true, mNextBufferId - 1);
4715 } else {
4716 return std::make_pair(false, it->second);
4717 }
4718}
4719
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004720void Camera3Device::HalInterface::onBufferFreed(
4721 int streamId, const native_handle_t* handle) {
4722 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4723 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4724 auto mapIt = mBufferIdMaps.find(streamId);
4725 if (mapIt == mBufferIdMaps.end()) {
4726 // streamId might be from a deleted stream here
4727 ALOGI("%s: stream %d has been removed",
4728 __FUNCTION__, streamId);
4729 return;
4730 }
4731 BufferIdMap& bIdMap = mapIt->second;
4732 auto it = bIdMap.find(handle);
4733 if (it == bIdMap.end()) {
4734 ALOGW("%s: cannot find buffer %p in stream %d",
4735 __FUNCTION__, handle, streamId);
4736 return;
4737 } else {
4738 bufferId = it->second;
4739 bIdMap.erase(it);
4740 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4741 __FUNCTION__, streamId, bIdMap.size(), handle);
4742 }
4743 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4744}
4745
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004746/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004747 * RequestThread inner class methods
4748 */
4749
4750Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004751 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004752 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
4753 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004754 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004755 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004756 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004757 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07004758 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004759 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004760 mReconfigured(false),
4761 mDoPause(false),
4762 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004763 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004764 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07004765 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07004766 mCurrentAfTriggerId(0),
4767 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004768 mRepeatingLastFrameNumber(
4769 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07004770 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004771 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004772 mRequestLatency(kRequestLatencyBinSize),
4773 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004774 mLatestSessionParams(sessionParamKeys.size()),
4775 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004776 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004777}
4778
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004779Camera3Device::RequestThread::~RequestThread() {}
4780
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07004781void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004782 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004783 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004784 Mutex::Autolock l(mRequestLock);
4785 mListener = listener;
4786}
4787
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004788void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
4789 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004790 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004791 Mutex::Autolock l(mRequestLock);
4792 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00004793 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07004794 // Prepare video stream for high speed recording.
4795 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01004796 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004797}
4798
Jianing Wei90e59c92014-03-12 18:29:36 -07004799status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004800 List<sp<CaptureRequest> > &requests,
4801 /*out*/
4802 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004803 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07004804 Mutex::Autolock l(mRequestLock);
4805 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
4806 ++it) {
4807 mRequestQueue.push_back(*it);
4808 }
4809
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004810 if (lastFrameNumber != NULL) {
4811 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
4812 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
4813 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
4814 *lastFrameNumber);
4815 }
Jianing Weicb0652e2014-03-12 18:29:36 -07004816
Jianing Wei90e59c92014-03-12 18:29:36 -07004817 unpauseForNewRequests();
4818
4819 return OK;
4820}
4821
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004822
4823status_t Camera3Device::RequestThread::queueTrigger(
4824 RequestTrigger trigger[],
4825 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004826 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004827 Mutex::Autolock l(mTriggerMutex);
4828 status_t ret;
4829
4830 for (size_t i = 0; i < count; ++i) {
4831 ret = queueTriggerLocked(trigger[i]);
4832
4833 if (ret != OK) {
4834 return ret;
4835 }
4836 }
4837
4838 return OK;
4839}
4840
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004841const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
4842 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004843 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004844 if (d != nullptr) return d->mId;
4845 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004846}
4847
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004848status_t Camera3Device::RequestThread::queueTriggerLocked(
4849 RequestTrigger trigger) {
4850
4851 uint32_t tag = trigger.metadataTag;
4852 ssize_t index = mTriggerMap.indexOfKey(tag);
4853
4854 switch (trigger.getTagType()) {
4855 case TYPE_BYTE:
4856 // fall-through
4857 case TYPE_INT32:
4858 break;
4859 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07004860 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
4861 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004862 return INVALID_OPERATION;
4863 }
4864
4865 /**
4866 * Collect only the latest trigger, since we only have 1 field
4867 * in the request settings per trigger tag, and can't send more than 1
4868 * trigger per request.
4869 */
4870 if (index != NAME_NOT_FOUND) {
4871 mTriggerMap.editValueAt(index) = trigger;
4872 } else {
4873 mTriggerMap.add(tag, trigger);
4874 }
4875
4876 return OK;
4877}
4878
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004879status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004880 const RequestList &requests,
4881 /*out*/
4882 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004883 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004884 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004885 if (lastFrameNumber != NULL) {
4886 *lastFrameNumber = mRepeatingLastFrameNumber;
4887 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004888 mRepeatingRequests.clear();
4889 mRepeatingRequests.insert(mRepeatingRequests.begin(),
4890 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07004891
4892 unpauseForNewRequests();
4893
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004894 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004895 return OK;
4896}
4897
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07004898bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004899 if (mRepeatingRequests.empty()) {
4900 return false;
4901 }
4902 int32_t requestId = requestIn->mResultExtras.requestId;
4903 const RequestList &repeatRequests = mRepeatingRequests;
4904 // All repeating requests are guaranteed to have same id so only check first quest
4905 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
4906 return (firstRequest->mResultExtras.requestId == requestId);
4907}
4908
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004909status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004910 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004911 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07004912 return clearRepeatingRequestsLocked(lastFrameNumber);
4913
4914}
4915
4916status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004917 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004918 if (lastFrameNumber != NULL) {
4919 *lastFrameNumber = mRepeatingLastFrameNumber;
4920 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004921 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004922 return OK;
4923}
4924
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004925status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004926 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004927 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004928 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004929 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004930
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004931 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004932
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004933 // Send errors for all requests pending in the request queue, including
4934 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004935 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004936 if (listener != NULL) {
4937 for (RequestList::iterator it = mRequestQueue.begin();
4938 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004939 // Abort the input buffers for reprocess requests.
4940 if ((*it)->mInputStream != NULL) {
4941 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07004942 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
4943 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07004944 if (res != OK) {
4945 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
4946 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4947 } else {
4948 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
4949 if (res != OK) {
4950 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
4951 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
4952 }
4953 }
4954 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004955 // Set the frame number this request would have had, if it
4956 // had been submitted; this frame number will not be reused.
4957 // The requestId and burstId fields were set when the request was
4958 // submitted originally (in convertMetadataListToRequestListLocked)
4959 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004960 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004961 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07004962 }
4963 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004964 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08004965
4966 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004967 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07004968 if (lastFrameNumber != NULL) {
4969 *lastFrameNumber = mRepeatingLastFrameNumber;
4970 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08004971 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07004972 return OK;
4973}
4974
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004975status_t Camera3Device::RequestThread::flush() {
4976 ATRACE_CALL();
4977 Mutex::Autolock l(mFlushLock);
4978
Emilian Peev08dd2452017-04-06 16:55:14 +01004979 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07004980}
4981
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004982void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004983 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08004984 Mutex::Autolock l(mPauseLock);
4985 mDoPause = paused;
4986 mDoPauseSignal.signal();
4987}
4988
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004989status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
4990 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004991 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07004992 Mutex::Autolock l(mLatestRequestMutex);
4993 status_t res;
4994 while (mLatestRequestId != requestId) {
4995 nsecs_t startTime = systemTime();
4996
4997 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
4998 if (res != OK) return res;
4999
5000 timeout -= (systemTime() - startTime);
5001 }
5002
5003 return OK;
5004}
5005
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005006void Camera3Device::RequestThread::requestExit() {
5007 // Call parent to set up shutdown
5008 Thread::requestExit();
5009 // The exit from any possible waits
5010 mDoPauseSignal.signal();
5011 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07005012
5013 mRequestLatency.log("ProcessCaptureRequest latency histogram");
5014 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005015}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005016
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005017void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005018 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005019 bool surfaceAbandoned = false;
5020 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005021 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005022 {
5023 Mutex::Autolock l(mRequestLock);
5024 // Check all streams needed by repeating requests are still valid. Otherwise, stop
5025 // repeating requests.
5026 for (const auto& request : mRepeatingRequests) {
5027 for (const auto& s : request->mOutputStreams) {
5028 if (s->isAbandoned()) {
5029 surfaceAbandoned = true;
5030 clearRepeatingRequestsLocked(&lastFrameNumber);
5031 break;
5032 }
5033 }
5034 if (surfaceAbandoned) {
5035 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005036 }
5037 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005038 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005039 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005040
5041 if (listener != NULL && surfaceAbandoned) {
5042 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005043 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005044}
5045
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005046bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005047 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005048 status_t res;
5049 size_t batchSize = mNextRequests.size();
5050 std::vector<camera3_capture_request_t*> requests(batchSize);
5051 uint32_t numRequestProcessed = 0;
5052 for (size_t i = 0; i < batchSize; i++) {
5053 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07005054 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005055 }
5056
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005057 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
5058
5059 bool triggerRemoveFailed = false;
5060 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
5061 for (size_t i = 0; i < numRequestProcessed; i++) {
5062 NextRequest& nextRequest = mNextRequests.editItemAt(i);
5063 nextRequest.submitted = true;
5064
5065
5066 // Update the latest request sent to HAL
5067 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5068 Mutex::Autolock al(mLatestRequestMutex);
5069
5070 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5071 mLatestRequest.acquire(cloned);
5072
5073 sp<Camera3Device> parent = mParent.promote();
5074 if (parent != NULL) {
5075 parent->monitorMetadata(TagMonitor::REQUEST,
5076 nextRequest.halRequest.frame_number,
5077 0, mLatestRequest);
5078 }
5079 }
5080
5081 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005082 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5083 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005084 }
5085
Emilian Peevaebbe412018-01-15 13:53:24 +00005086 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5087
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005088 if (!triggerRemoveFailed) {
5089 // Remove any previously queued triggers (after unlock)
5090 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5091 if (removeTriggerRes != OK) {
5092 triggerRemoveFailed = true;
5093 triggerFailedRequest = nextRequest;
5094 }
5095 }
5096 }
5097
5098 if (triggerRemoveFailed) {
5099 SET_ERR("RequestThread: Unable to remove triggers "
5100 "(capture request %d, HAL device: %s (%d)",
5101 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5102 cleanUpFailedRequests(/*sendRequestError*/ false);
5103 return false;
5104 }
5105
5106 if (res != OK) {
5107 // Should only get a failure here for malformed requests or device-level
5108 // errors, so consider all errors fatal. Bad metadata failures should
5109 // come through notify.
5110 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5111 mNextRequests[numRequestProcessed].halRequest.frame_number,
5112 strerror(-res), res);
5113 cleanUpFailedRequests(/*sendRequestError*/ false);
5114 return false;
5115 }
5116 return true;
5117}
5118
5119bool Camera3Device::RequestThread::sendRequestsOneByOne() {
5120 status_t res;
5121
5122 for (auto& nextRequest : mNextRequests) {
5123 // Submit request and block until ready for next one
5124 ATRACE_ASYNC_BEGIN("frame capture", nextRequest.halRequest.frame_number);
5125 res = mInterface->processCaptureRequest(&nextRequest.halRequest);
5126
5127 if (res != OK) {
5128 // Should only get a failure here for malformed requests or device-level
5129 // errors, so consider all errors fatal. Bad metadata failures should
5130 // come through notify.
5131 SET_ERR("RequestThread: Unable to submit capture request %d to HAL"
5132 " device: %s (%d)", nextRequest.halRequest.frame_number, strerror(-res),
5133 res);
5134 cleanUpFailedRequests(/*sendRequestError*/ false);
5135 return false;
5136 }
5137
5138 // Mark that the request has be submitted successfully.
5139 nextRequest.submitted = true;
5140
5141 // Update the latest request sent to HAL
5142 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5143 Mutex::Autolock al(mLatestRequestMutex);
5144
5145 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5146 mLatestRequest.acquire(cloned);
5147
5148 sp<Camera3Device> parent = mParent.promote();
5149 if (parent != NULL) {
5150 parent->monitorMetadata(TagMonitor::REQUEST, nextRequest.halRequest.frame_number,
5151 0, mLatestRequest);
5152 }
5153 }
5154
5155 if (nextRequest.halRequest.settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005156 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5157 nextRequest.halRequest.settings);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005158 }
5159
Emilian Peevaebbe412018-01-15 13:53:24 +00005160 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5161
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005162 // Remove any previously queued triggers (after unlock)
5163 res = removeTriggers(mPrevRequest);
5164 if (res != OK) {
5165 SET_ERR("RequestThread: Unable to remove triggers "
5166 "(capture request %d, HAL device: %s (%d)",
5167 nextRequest.halRequest.frame_number, strerror(-res), res);
5168 cleanUpFailedRequests(/*sendRequestError*/ false);
5169 return false;
5170 }
5171 }
5172 return true;
5173}
5174
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005175nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5176 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5177 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5178 find_camera_metadata_ro_entry(request,
5179 ANDROID_CONTROL_AE_MODE,
5180 &e);
5181 if (e.count == 0) return maxExpectedDuration;
5182
5183 switch (e.data.u8[0]) {
5184 case ANDROID_CONTROL_AE_MODE_OFF:
5185 find_camera_metadata_ro_entry(request,
5186 ANDROID_SENSOR_EXPOSURE_TIME,
5187 &e);
5188 if (e.count > 0) {
5189 maxExpectedDuration = e.data.i64[0];
5190 }
5191 find_camera_metadata_ro_entry(request,
5192 ANDROID_SENSOR_FRAME_DURATION,
5193 &e);
5194 if (e.count > 0) {
5195 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5196 }
5197 break;
5198 default:
5199 find_camera_metadata_ro_entry(request,
5200 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5201 &e);
5202 if (e.count > 1) {
5203 maxExpectedDuration = 1e9 / e.data.u8[0];
5204 }
5205 break;
5206 }
5207
5208 return maxExpectedDuration;
5209}
5210
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005211bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5212 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5213 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5214 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5215 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5216 return true;
5217 }
5218
5219 return false;
5220}
5221
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005222bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5223 ATRACE_CALL();
5224 bool updatesDetected = false;
5225
Emilian Peev4ec17882019-01-24 17:16:58 -08005226 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005227 for (auto tag : mSessionParamKeys) {
5228 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005229 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005230
5231 if (entry.count > 0) {
5232 bool isDifferent = false;
5233 if (lastEntry.count > 0) {
5234 // Have a last value, compare to see if changed
5235 if (lastEntry.type == entry.type &&
5236 lastEntry.count == entry.count) {
5237 // Same type and count, compare values
5238 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5239 size_t entryBytes = bytesPerValue * lastEntry.count;
5240 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5241 if (cmp != 0) {
5242 isDifferent = true;
5243 }
5244 } else {
5245 // Count or type has changed
5246 isDifferent = true;
5247 }
5248 } else {
5249 // No last entry, so always consider to be different
5250 isDifferent = true;
5251 }
5252
5253 if (isDifferent) {
5254 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005255 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5256 updatesDetected = true;
5257 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005258 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005259 }
5260 } else if (lastEntry.count > 0) {
5261 // Value has been removed
5262 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005263 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005264 updatesDetected = true;
5265 }
5266 }
5267
Emilian Peev4ec17882019-01-24 17:16:58 -08005268 bool reconfigureRequired;
5269 if (updatesDetected) {
5270 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5271 updatedParams);
5272 mLatestSessionParams = updatedParams;
5273 } else {
5274 reconfigureRequired = false;
5275 }
5276
5277 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005278}
5279
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005280bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005281 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005282 status_t res;
5283
5284 // Handle paused state.
5285 if (waitIfPaused()) {
5286 return true;
5287 }
5288
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005289 // Wait for the next batch of requests.
5290 waitForNextRequestBatch();
5291 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005292 return true;
5293 }
5294
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005295 // Get the latest request ID, if any
5296 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005297 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005298 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005299 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005300 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005301 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005302 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5303 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005304 }
5305
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005306 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5307 // or a single request from streaming or burst. In either case the first element
5308 // should contain the latest camera settings that we need to check for any session
5309 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005310 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005311 res = OK;
5312
5313 //Input stream buffers are already acquired at this point so an input stream
5314 //will not be able to move to idle state unless we force it.
5315 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5316 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5317 if (res != OK) {
5318 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5319 cleanUpFailedRequests(/*sendRequestError*/ false);
5320 return false;
5321 }
5322 }
5323
5324 if (res == OK) {
5325 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5326 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005327 sp<Camera3Device> parent = mParent.promote();
5328 if (parent != nullptr) {
5329 parent->pauseStateNotify(true);
5330 }
5331
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005332 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5333
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005334 if (parent != nullptr) {
5335 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5336 }
5337
5338 statusTracker->markComponentActive(mStatusId);
5339 setPaused(false);
5340 }
5341
5342 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5343 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5344 if (res != OK) {
5345 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5346 cleanUpFailedRequests(/*sendRequestError*/ false);
5347 return false;
5348 }
5349 }
5350 }
5351 }
5352
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005353 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005354 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005355 if (res == TIMED_OUT) {
5356 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005357 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005358 // Check if any stream is abandoned.
5359 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005360 return true;
5361 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005362 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005363 return false;
5364 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005365
Zhijun Hecc27e112013-10-03 16:12:43 -07005366 // Inform waitUntilRequestProcessed thread of a new request ID
5367 {
5368 Mutex::Autolock al(mLatestRequestMutex);
5369
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005370 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005371 mLatestRequestSignal.signal();
5372 }
5373
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005374 // Submit a batch of requests to HAL.
5375 // Use flush lock only when submitting multilple requests in a batch.
5376 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5377 // which may take a long time to finish so synchronizing flush() and
5378 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5379 // For now, only synchronize for high speed recording and we should figure something out for
5380 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005381 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005382
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005383 if (useFlushLock) {
5384 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005385 }
5386
Zhijun Hef0645c12016-08-02 00:58:11 -07005387 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005388 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005389
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005390 sp<Camera3Device> parent = mParent.promote();
5391 if (parent != nullptr) {
5392 parent->mRequestBufferSM.onSubmittingRequest();
5393 }
5394
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005395 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005396 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005397 if (mInterface->supportBatchRequest()) {
5398 submitRequestSuccess = sendRequestsBatch();
5399 } else {
5400 submitRequestSuccess = sendRequestsOneByOne();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005401 }
Shuzhen Wang686f6442017-06-20 16:16:04 -07005402 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5403 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005404
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005405 if (useFlushLock) {
5406 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005407 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005408
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005409 // Unset as current request
5410 {
5411 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005412 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005413 }
5414
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005415 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005416}
5417
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005418status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005419 ATRACE_CALL();
5420
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005421 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005422 for (size_t i = 0; i < mNextRequests.size(); i++) {
5423 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005424 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5425 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5426 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5427
5428 // Prepare a request to HAL
5429 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5430
5431 // Insert any queued triggers (before metadata is locked)
5432 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005433 if (res < 0) {
5434 SET_ERR("RequestThread: Unable to insert triggers "
5435 "(capture request %d, HAL device: %s (%d)",
5436 halRequest->frame_number, strerror(-res), res);
5437 return INVALID_OPERATION;
5438 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005439
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005440 int triggerCount = res;
5441 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5442 mPrevTriggers = triggerCount;
5443
5444 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005445 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5446 // Request settings are all the same within one batch, so only treat the first
5447 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005448 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005449 if (newRequest) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005450 /**
5451 * HAL workaround:
5452 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5453 */
5454 res = addDummyTriggerIds(captureRequest);
5455 if (res != OK) {
5456 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5457 "(capture request %d, HAL device: %s (%d)",
5458 halRequest->frame_number, strerror(-res), res);
5459 return INVALID_OPERATION;
5460 }
5461
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005462 {
5463 // Correct metadata regions for distortion correction if enabled
5464 sp<Camera3Device> parent = mParent.promote();
5465 if (parent != nullptr) {
5466 res = parent->mDistortionMapper.correctCaptureRequest(
5467 &(captureRequest->mSettingsList.begin()->metadata));
5468 if (res != OK) {
5469 SET_ERR("RequestThread: Unable to correct capture requests "
5470 "for lens distortion for request %d: %s (%d)",
5471 halRequest->frame_number, strerror(-res), res);
5472 return INVALID_OPERATION;
5473 }
5474 }
5475 }
5476
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005477 /**
5478 * The request should be presorted so accesses in HAL
5479 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5480 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005481 captureRequest->mSettingsList.begin()->metadata.sort();
5482 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005483 mPrevRequest = captureRequest;
5484 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5485
5486 IF_ALOGV() {
5487 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5488 find_camera_metadata_ro_entry(
5489 halRequest->settings,
5490 ANDROID_CONTROL_AF_TRIGGER,
5491 &e
5492 );
5493 if (e.count > 0) {
5494 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5495 __FUNCTION__,
5496 halRequest->frame_number,
5497 e.data.u8[0]);
5498 }
5499 }
5500 } else {
5501 // leave request.settings NULL to indicate 'reuse latest given'
5502 ALOGVV("%s: Request settings are REUSED",
5503 __FUNCTION__);
5504 }
5505
Emilian Peevaebbe412018-01-15 13:53:24 +00005506 if (captureRequest->mSettingsList.size() > 1) {
5507 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5508 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005509 if (newRequest) {
5510 halRequest->physcam_settings =
5511 new const camera_metadata* [halRequest->num_physcam_settings];
5512 } else {
5513 halRequest->physcam_settings = nullptr;
5514 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005515 auto it = ++captureRequest->mSettingsList.begin();
5516 size_t i = 0;
5517 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5518 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005519 if (newRequest) {
5520 it->metadata.sort();
5521 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5522 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005523 }
5524 }
5525
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005526 uint32_t totalNumBuffers = 0;
5527
5528 // Fill in buffers
5529 if (captureRequest->mInputStream != NULL) {
5530 halRequest->input_buffer = &captureRequest->mInputBuffer;
5531 totalNumBuffers += 1;
5532 } else {
5533 halRequest->input_buffer = NULL;
5534 }
5535
5536 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5537 captureRequest->mOutputStreams.size());
5538 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005539 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005540
5541 sp<Camera3Device> parent = mParent.promote();
5542 if (parent == NULL) {
5543 // Should not happen, and nowhere to send errors to, so just log it
5544 CLOGE("RequestThread: Parent is gone");
5545 return INVALID_OPERATION;
5546 }
5547 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5548
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005549 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005550 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005551 sp<Camera3OutputStreamInterface> outputStream =
5552 captureRequest->mOutputStreams.editItemAt(j);
5553 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005554
5555 // Prepare video buffers for high speed recording on the first video request.
5556 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5557 // Only try to prepare video stream on the first video request.
5558 mPrepareVideoStream = false;
5559
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005560 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5561 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005562 while (res == NOT_ENOUGH_DATA) {
5563 res = outputStream->prepareNextBuffer();
5564 }
5565 if (res != OK) {
5566 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5567 __FUNCTION__, strerror(-res), res);
5568 outputStream->cancelPrepare();
5569 }
5570 }
5571
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005572 std::vector<size_t> uniqueSurfaceIds;
5573 res = outputStream->getUniqueSurfaceIds(
5574 captureRequest->mOutputSurfaces[streamId],
5575 &uniqueSurfaceIds);
5576 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5577 if (res != OK && res != INVALID_OPERATION) {
5578 ALOGE("%s: failed to query stream %d unique surface IDs",
5579 __FUNCTION__, streamId);
5580 return res;
5581 }
5582 if (res == OK) {
5583 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5584 }
5585
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005586 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005587 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005588 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005589 return TIMED_OUT;
5590 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005591 // HAL will request buffer through requestStreamBuffer API
5592 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5593 buffer.stream = outputStream->asHalStream();
5594 buffer.buffer = nullptr;
5595 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5596 buffer.acquire_fence = -1;
5597 buffer.release_fence = -1;
5598 } else {
5599 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5600 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005601 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005602 if (res != OK) {
5603 // Can't get output buffer from gralloc queue - this could be due to
5604 // abandoned queue or other consumer misbehavior, so not a fatal
5605 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005606 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005607 " %s (%d)", strerror(-res), res);
5608
5609 return TIMED_OUT;
5610 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005611 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005612
5613 {
5614 sp<Camera3Device> parent = mParent.promote();
5615 if (parent != nullptr) {
5616 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5617 for (const auto& settings : captureRequest->mSettingsList) {
5618 if ((streamCameraId.isEmpty() &&
5619 parent->getId() == settings.cameraId.c_str()) ||
5620 streamCameraId == settings.cameraId.c_str()) {
5621 outputStream->fireBufferRequestForFrameNumber(
5622 captureRequest->mResultExtras.frameNumber,
5623 settings.metadata);
5624 }
5625 }
5626 }
5627 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005628
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005629 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5630
5631 if (!physicalCameraId.isEmpty()) {
5632 // Physical stream isn't supported for input request.
5633 if (halRequest->input_buffer) {
5634 CLOGE("Physical stream is not supported for input request");
5635 return INVALID_OPERATION;
5636 }
5637 requestedPhysicalCameras.insert(physicalCameraId);
5638 }
5639 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005640 }
5641 totalNumBuffers += halRequest->num_output_buffers;
5642
5643 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005644 // If this request list is for constrained high speed recording (not
5645 // preview), and the current request is not the last one in the batch,
5646 // do not send callback to the app.
5647 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005648 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005649 hasCallback = false;
5650 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005651 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005652 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005653 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5654 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5655 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5656 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5657 isStillCapture = true;
5658 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5659 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005660
5661 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5662 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5663 isZslCapture = true;
5664 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005665 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005666 res = parent->registerInFlight(halRequest->frame_number,
5667 totalNumBuffers, captureRequest->mResultExtras,
5668 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005669 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005670 calculateMaxExpectedDuration(halRequest->settings),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005671 requestedPhysicalCameras, isStillCapture, isZslCapture,
5672 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5673 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005674 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5675 ", burstId = %" PRId32 ".",
5676 __FUNCTION__,
5677 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5678 captureRequest->mResultExtras.burstId);
5679 if (res != OK) {
5680 SET_ERR("RequestThread: Unable to register new in-flight request:"
5681 " %s (%d)", strerror(-res), res);
5682 return INVALID_OPERATION;
5683 }
5684 }
5685
5686 return OK;
5687}
5688
Igor Murashkin1e479c02013-09-06 16:55:14 -07005689CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005690 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005691 Mutex::Autolock al(mLatestRequestMutex);
5692
5693 ALOGV("RequestThread::%s", __FUNCTION__);
5694
5695 return mLatestRequest;
5696}
5697
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005698bool Camera3Device::RequestThread::isStreamPending(
5699 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005700 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005701 Mutex::Autolock l(mRequestLock);
5702
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005703 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005704 if (!nextRequest.submitted) {
5705 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5706 if (stream == s) return true;
5707 }
5708 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005709 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005710 }
5711
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005712 for (const auto& request : mRequestQueue) {
5713 for (const auto& s : request->mOutputStreams) {
5714 if (stream == s) return true;
5715 }
5716 if (stream == request->mInputStream) return true;
5717 }
5718
5719 for (const auto& request : mRepeatingRequests) {
5720 for (const auto& s : request->mOutputStreams) {
5721 if (stream == s) return true;
5722 }
5723 if (stream == request->mInputStream) return true;
5724 }
5725
5726 return false;
5727}
Jianing Weicb0652e2014-03-12 18:29:36 -07005728
Emilian Peev40ead602017-09-26 15:46:36 +01005729bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5730 ATRACE_CALL();
5731 Mutex::Autolock l(mRequestLock);
5732
5733 for (const auto& nextRequest : mNextRequests) {
5734 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5735 if (s.first == streamId) {
5736 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5737 if (it != s.second.end()) {
5738 return true;
5739 }
5740 }
5741 }
5742 }
5743
5744 for (const auto& request : mRequestQueue) {
5745 for (const auto& s : request->mOutputSurfaces) {
5746 if (s.first == streamId) {
5747 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5748 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005749 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005750 }
5751 }
5752 }
5753 }
5754
5755 for (const auto& request : mRepeatingRequests) {
5756 for (const auto& s : request->mOutputSurfaces) {
5757 if (s.first == streamId) {
5758 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5759 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005760 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005761 }
5762 }
5763 }
5764 }
5765
5766 return false;
5767}
5768
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005769void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
5770 if (!mUseHalBufManager) {
5771 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
5772 return;
5773 }
5774
5775 Mutex::Autolock pl(mPauseLock);
5776 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005777 mInterface->signalPipelineDrain(streamIds);
5778 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005779 }
5780 // If request thread is still busy, wait until paused then notify HAL
5781 mNotifyPipelineDrain = true;
5782 mStreamIdsToBeDrained = streamIds;
5783}
5784
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005785nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005786 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07005787 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005788 return mExpectedInflightDuration > kMinInflightDuration ?
5789 mExpectedInflightDuration : kMinInflightDuration;
5790}
5791
Emilian Peevaebbe412018-01-15 13:53:24 +00005792void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
5793 camera3_capture_request_t *halRequest) {
5794 if ((request == nullptr) || (halRequest == nullptr)) {
5795 ALOGE("%s: Invalid request!", __FUNCTION__);
5796 return;
5797 }
5798
5799 if (halRequest->num_physcam_settings > 0) {
5800 if (halRequest->physcam_id != nullptr) {
5801 delete [] halRequest->physcam_id;
5802 halRequest->physcam_id = nullptr;
5803 }
5804 if (halRequest->physcam_settings != nullptr) {
5805 auto it = ++(request->mSettingsList.begin());
5806 size_t i = 0;
5807 for (; it != request->mSettingsList.end(); it++, i++) {
5808 it->metadata.unlock(halRequest->physcam_settings[i]);
5809 }
5810 delete [] halRequest->physcam_settings;
5811 halRequest->physcam_settings = nullptr;
5812 }
5813 }
5814}
5815
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005816void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
5817 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005818 return;
5819 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005820
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005821 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005822 // Skip the ones that have been submitted successfully.
5823 if (nextRequest.submitted) {
5824 continue;
5825 }
5826
5827 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5828 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5829 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5830
5831 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00005832 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005833 }
5834
Emilian Peevaebbe412018-01-15 13:53:24 +00005835 cleanupPhysicalSettings(captureRequest, halRequest);
5836
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005837 if (captureRequest->mInputStream != NULL) {
5838 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
5839 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
5840 }
5841
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08005842 // No output buffer can be returned when using HAL buffer manager
5843 if (!mUseHalBufManager) {
5844 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
5845 //Buffers that failed processing could still have
5846 //valid acquire fence.
5847 int acquireFence = (*outputBuffers)[i].acquire_fence;
5848 if (0 <= acquireFence) {
5849 close(acquireFence);
5850 outputBuffers->editItemAt(i).acquire_fence = -1;
5851 }
5852 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
5853 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
5854 /*timestampIncreasing*/true, std::vector<size_t> (),
5855 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01005856 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005857 }
5858
5859 if (sendRequestError) {
5860 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005861 sp<NotificationListener> listener = mListener.promote();
5862 if (listener != NULL) {
5863 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005864 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005865 captureRequest->mResultExtras);
5866 }
5867 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07005868
5869 // Remove yet-to-be submitted inflight request from inflightMap
5870 {
5871 sp<Camera3Device> parent = mParent.promote();
5872 if (parent != NULL) {
5873 Mutex::Autolock l(parent->mInFlightLock);
5874 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
5875 if (idx >= 0) {
5876 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
5877 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
5878 parent->removeInFlightMapEntryLocked(idx);
5879 }
5880 }
5881 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005882 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005883
5884 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005885 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005886}
5887
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005888void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005889 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005890 // Optimized a bit for the simple steady-state case (single repeating
5891 // request), to avoid putting that request in the queue temporarily.
5892 Mutex::Autolock l(mRequestLock);
5893
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005894 assert(mNextRequests.empty());
5895
5896 NextRequest nextRequest;
5897 nextRequest.captureRequest = waitForNextRequestLocked();
5898 if (nextRequest.captureRequest == nullptr) {
5899 return;
5900 }
5901
5902 nextRequest.halRequest = camera3_capture_request_t();
5903 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005904 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005905
5906 // Wait for additional requests
5907 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
5908
5909 for (size_t i = 1; i < batchSize; i++) {
5910 NextRequest additionalRequest;
5911 additionalRequest.captureRequest = waitForNextRequestLocked();
5912 if (additionalRequest.captureRequest == nullptr) {
5913 break;
5914 }
5915
5916 additionalRequest.halRequest = camera3_capture_request_t();
5917 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005918 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005919 }
5920
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005921 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08005922 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005923 mNextRequests.size(), batchSize);
5924 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005925 }
5926
5927 return;
5928}
5929
5930sp<Camera3Device::CaptureRequest>
5931 Camera3Device::RequestThread::waitForNextRequestLocked() {
5932 status_t res;
5933 sp<CaptureRequest> nextRequest;
5934
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005935 while (mRequestQueue.empty()) {
5936 if (!mRepeatingRequests.empty()) {
5937 // Always atomically enqueue all requests in a repeating request
5938 // list. Guarantees a complete in-sequence set of captures to
5939 // application.
5940 const RequestList &requests = mRepeatingRequests;
5941 RequestList::const_iterator firstRequest =
5942 requests.begin();
5943 nextRequest = *firstRequest;
5944 mRequestQueue.insert(mRequestQueue.end(),
5945 ++firstRequest,
5946 requests.end());
5947 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07005948
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005949 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07005950
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005951 break;
5952 }
5953
5954 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
5955
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005956 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
5957 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005958 Mutex::Autolock pl(mPauseLock);
5959 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005960 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005961 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005962 if (mNotifyPipelineDrain) {
5963 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
5964 mNotifyPipelineDrain = false;
5965 mStreamIdsToBeDrained.clear();
5966 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08005967 // Let the tracker know
5968 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5969 if (statusTracker != 0) {
5970 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5971 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07005972 sp<Camera3Device> parent = mParent.promote();
5973 if (parent != nullptr) {
5974 parent->mRequestBufferSM.onRequestThreadPaused();
5975 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005976 }
5977 // Stop waiting for now and let thread management happen
5978 return NULL;
5979 }
5980 }
5981
5982 if (nextRequest == NULL) {
5983 // Don't have a repeating request already in hand, so queue
5984 // must have an entry now.
5985 RequestList::iterator firstRequest =
5986 mRequestQueue.begin();
5987 nextRequest = *firstRequest;
5988 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07005989 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
5990 sp<NotificationListener> listener = mListener.promote();
5991 if (listener != NULL) {
5992 listener->notifyRequestQueueEmpty();
5993 }
5994 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005995 }
5996
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005997 // In case we've been unpaused by setPaused clearing mDoPause, need to
5998 // update internal pause state (capture/setRepeatingRequest unpause
5999 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006000 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006001 if (mPaused) {
6002 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
6003 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6004 if (statusTracker != 0) {
6005 statusTracker->markComponentActive(mStatusId);
6006 }
6007 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006008 mPaused = false;
6009
6010 // Check if we've reconfigured since last time, and reset the preview
6011 // request if so. Can't use 'NULL request == repeat' across configure calls.
6012 if (mReconfigured) {
6013 mPrevRequest.clear();
6014 mReconfigured = false;
6015 }
6016
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006017 if (nextRequest != NULL) {
6018 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006019 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
6020 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006021
6022 // Since RequestThread::clear() removes buffers from the input stream,
6023 // get the right buffer here before unlocking mRequestLock
6024 if (nextRequest->mInputStream != NULL) {
6025 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
6026 if (res != OK) {
6027 // Can't get input buffer from gralloc queue - this could be due to
6028 // disconnected queue or other producer misbehavior, so not a fatal
6029 // error
6030 ALOGE("%s: Can't get input buffer, skipping request:"
6031 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006032
6033 sp<NotificationListener> listener = mListener.promote();
6034 if (listener != NULL) {
6035 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006036 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006037 nextRequest->mResultExtras);
6038 }
6039 return NULL;
6040 }
6041 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006042 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07006043
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006044 return nextRequest;
6045}
6046
6047bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006048 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006049 status_t res;
6050 Mutex::Autolock l(mPauseLock);
6051 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006052 if (mPaused == false) {
6053 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006054 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006055 if (mNotifyPipelineDrain) {
6056 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6057 mNotifyPipelineDrain = false;
6058 mStreamIdsToBeDrained.clear();
6059 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006060 // Let the tracker know
6061 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6062 if (statusTracker != 0) {
6063 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6064 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006065 sp<Camera3Device> parent = mParent.promote();
6066 if (parent != nullptr) {
6067 parent->mRequestBufferSM.onRequestThreadPaused();
6068 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006069 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006070
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006071 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006072 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006073 return true;
6074 }
6075 }
6076 // We don't set mPaused to false here, because waitForNextRequest needs
6077 // to further manage the paused state in case of starvation.
6078 return false;
6079}
6080
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006081void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006082 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006083 // With work to do, mark thread as unpaused.
6084 // If paused by request (setPaused), don't resume, to avoid
6085 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006086 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006087 Mutex::Autolock p(mPauseLock);
6088 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006089 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6090 if (mPaused) {
6091 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6092 if (statusTracker != 0) {
6093 statusTracker->markComponentActive(mStatusId);
6094 }
6095 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006096 mPaused = false;
6097 }
6098}
6099
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006100void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6101 sp<Camera3Device> parent = mParent.promote();
6102 if (parent != NULL) {
6103 va_list args;
6104 va_start(args, fmt);
6105
6106 parent->setErrorStateV(fmt, args);
6107
6108 va_end(args);
6109 }
6110}
6111
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006112status_t Camera3Device::RequestThread::insertTriggers(
6113 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006114 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006115 Mutex::Autolock al(mTriggerMutex);
6116
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006117 sp<Camera3Device> parent = mParent.promote();
6118 if (parent == NULL) {
6119 CLOGE("RequestThread: Parent is gone");
6120 return DEAD_OBJECT;
6121 }
6122
Emilian Peevaebbe412018-01-15 13:53:24 +00006123 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006124 size_t count = mTriggerMap.size();
6125
6126 for (size_t i = 0; i < count; ++i) {
6127 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006128 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006129
6130 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6131 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6132 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006133 if (isAeTrigger) {
6134 request->mResultExtras.precaptureTriggerId = triggerId;
6135 mCurrentPreCaptureTriggerId = triggerId;
6136 } else {
6137 request->mResultExtras.afTriggerId = triggerId;
6138 mCurrentAfTriggerId = triggerId;
6139 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006140 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006141 }
6142
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006143 camera_metadata_entry entry = metadata.find(tag);
6144
6145 if (entry.count > 0) {
6146 /**
6147 * Already has an entry for this trigger in the request.
6148 * Rewrite it with our requested trigger value.
6149 */
6150 RequestTrigger oldTrigger = trigger;
6151
6152 oldTrigger.entryValue = entry.data.u8[0];
6153
6154 mTriggerReplacedMap.add(tag, oldTrigger);
6155 } else {
6156 /**
6157 * More typical, no trigger entry, so we just add it
6158 */
6159 mTriggerRemovedMap.add(tag, trigger);
6160 }
6161
6162 status_t res;
6163
6164 switch (trigger.getTagType()) {
6165 case TYPE_BYTE: {
6166 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6167 res = metadata.update(tag,
6168 &entryValue,
6169 /*count*/1);
6170 break;
6171 }
6172 case TYPE_INT32:
6173 res = metadata.update(tag,
6174 &trigger.entryValue,
6175 /*count*/1);
6176 break;
6177 default:
6178 ALOGE("%s: Type not supported: 0x%x",
6179 __FUNCTION__,
6180 trigger.getTagType());
6181 return INVALID_OPERATION;
6182 }
6183
6184 if (res != OK) {
6185 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6186 ", value %d", __FUNCTION__, trigger.getTagName(),
6187 trigger.entryValue);
6188 return res;
6189 }
6190
6191 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6192 trigger.getTagName(),
6193 trigger.entryValue);
6194 }
6195
6196 mTriggerMap.clear();
6197
6198 return count;
6199}
6200
6201status_t Camera3Device::RequestThread::removeTriggers(
6202 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006203 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006204 Mutex::Autolock al(mTriggerMutex);
6205
Emilian Peevaebbe412018-01-15 13:53:24 +00006206 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006207
6208 /**
6209 * Replace all old entries with their old values.
6210 */
6211 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6212 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6213
6214 status_t res;
6215
6216 uint32_t tag = trigger.metadataTag;
6217 switch (trigger.getTagType()) {
6218 case TYPE_BYTE: {
6219 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6220 res = metadata.update(tag,
6221 &entryValue,
6222 /*count*/1);
6223 break;
6224 }
6225 case TYPE_INT32:
6226 res = metadata.update(tag,
6227 &trigger.entryValue,
6228 /*count*/1);
6229 break;
6230 default:
6231 ALOGE("%s: Type not supported: 0x%x",
6232 __FUNCTION__,
6233 trigger.getTagType());
6234 return INVALID_OPERATION;
6235 }
6236
6237 if (res != OK) {
6238 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6239 ", trigger value %d", __FUNCTION__,
6240 trigger.getTagName(), trigger.entryValue);
6241 return res;
6242 }
6243 }
6244 mTriggerReplacedMap.clear();
6245
6246 /**
6247 * Remove all new entries.
6248 */
6249 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6250 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6251 status_t res = metadata.erase(trigger.metadataTag);
6252
6253 if (res != OK) {
6254 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6255 ", trigger value %d", __FUNCTION__,
6256 trigger.getTagName(), trigger.entryValue);
6257 return res;
6258 }
6259 }
6260 mTriggerRemovedMap.clear();
6261
6262 return OK;
6263}
6264
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006265status_t Camera3Device::RequestThread::addDummyTriggerIds(
6266 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006267 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006268 static const int32_t dummyTriggerId = 1;
6269 status_t res;
6270
Emilian Peevaebbe412018-01-15 13:53:24 +00006271 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006272
6273 // If AF trigger is active, insert a dummy AF trigger ID if none already
6274 // exists
6275 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6276 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6277 if (afTrigger.count > 0 &&
6278 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6279 afId.count == 0) {
6280 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6281 if (res != OK) return res;
6282 }
6283
6284 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6285 // if none already exists
6286 camera_metadata_entry pcTrigger =
6287 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6288 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6289 if (pcTrigger.count > 0 &&
6290 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6291 pcId.count == 0) {
6292 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6293 &dummyTriggerId, 1);
6294 if (res != OK) return res;
6295 }
6296
6297 return OK;
6298}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006299
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006300/**
6301 * PreparerThread inner class methods
6302 */
6303
6304Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006305 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006306 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006307}
6308
6309Camera3Device::PreparerThread::~PreparerThread() {
6310 Thread::requestExitAndWait();
6311 if (mCurrentStream != nullptr) {
6312 mCurrentStream->cancelPrepare();
6313 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6314 mCurrentStream.clear();
6315 }
6316 clear();
6317}
6318
Ruben Brunkc78ac262015-08-13 17:58:46 -07006319status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006320 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006321 status_t res;
6322
6323 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006324 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006325
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006326 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006327 if (res == OK) {
6328 // No preparation needed, fire listener right off
6329 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006330 if (listener != NULL) {
6331 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006332 }
6333 return OK;
6334 } else if (res != NOT_ENOUGH_DATA) {
6335 return res;
6336 }
6337
6338 // Need to prepare, start up thread if necessary
6339 if (!mActive) {
6340 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6341 // isn't running
6342 Thread::requestExitAndWait();
6343 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6344 if (res != OK) {
6345 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006346 if (listener != NULL) {
6347 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006348 }
6349 return res;
6350 }
6351 mCancelNow = false;
6352 mActive = true;
6353 ALOGV("%s: Preparer stream started", __FUNCTION__);
6354 }
6355
6356 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006357 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006358 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6359
6360 return OK;
6361}
6362
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006363void Camera3Device::PreparerThread::pause() {
6364 ATRACE_CALL();
6365
6366 Mutex::Autolock l(mLock);
6367
6368 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6369 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6370 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6371 int currentMaxCount = mCurrentMaxCount;
6372 mPendingStreams.clear();
6373 mCancelNow = true;
6374 while (mActive) {
6375 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6376 if (res == TIMED_OUT) {
6377 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6378 return;
6379 } else if (res != OK) {
6380 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6381 return;
6382 }
6383 }
6384
6385 //Check whether the prepare thread was able to complete the current
6386 //stream. In case work is still pending emplace it along with the rest
6387 //of the streams in the pending list.
6388 if (currentStream != nullptr) {
6389 if (!mCurrentPrepareComplete) {
6390 pendingStreams.emplace(currentMaxCount, currentStream);
6391 }
6392 }
6393
6394 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6395 for (const auto& it : mPendingStreams) {
6396 it.second->cancelPrepare();
6397 }
6398}
6399
6400status_t Camera3Device::PreparerThread::resume() {
6401 ATRACE_CALL();
6402 status_t res;
6403
6404 Mutex::Autolock l(mLock);
6405 sp<NotificationListener> listener = mListener.promote();
6406
6407 if (mActive) {
6408 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6409 return NO_INIT;
6410 }
6411
6412 auto it = mPendingStreams.begin();
6413 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006414 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006415 if (res == OK) {
6416 if (listener != NULL) {
6417 listener->notifyPrepared(it->second->getId());
6418 }
6419 it = mPendingStreams.erase(it);
6420 } else if (res != NOT_ENOUGH_DATA) {
6421 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6422 res, strerror(-res));
6423 it = mPendingStreams.erase(it);
6424 } else {
6425 it++;
6426 }
6427 }
6428
6429 if (mPendingStreams.empty()) {
6430 return OK;
6431 }
6432
6433 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6434 if (res != OK) {
6435 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6436 __FUNCTION__, res, strerror(-res));
6437 return res;
6438 }
6439 mCancelNow = false;
6440 mActive = true;
6441 ALOGV("%s: Preparer stream started", __FUNCTION__);
6442
6443 return OK;
6444}
6445
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006446status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006447 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006448 Mutex::Autolock l(mLock);
6449
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006450 for (const auto& it : mPendingStreams) {
6451 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006452 }
6453 mPendingStreams.clear();
6454 mCancelNow = true;
6455
6456 return OK;
6457}
6458
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006459void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
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 mListener = listener;
6463}
6464
6465bool Camera3Device::PreparerThread::threadLoop() {
6466 status_t res;
6467 {
6468 Mutex::Autolock l(mLock);
6469 if (mCurrentStream == nullptr) {
6470 // End thread if done with work
6471 if (mPendingStreams.empty()) {
6472 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6473 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6474 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6475 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006476 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006477 return false;
6478 }
6479
6480 // Get next stream to prepare
6481 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006482 mCurrentStream = it->second;
6483 mCurrentMaxCount = it->first;
6484 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006485 mPendingStreams.erase(it);
6486 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6487 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6488 } else if (mCancelNow) {
6489 mCurrentStream->cancelPrepare();
6490 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6491 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6492 mCurrentStream.clear();
6493 mCancelNow = false;
6494 return true;
6495 }
6496 }
6497
6498 res = mCurrentStream->prepareNextBuffer();
6499 if (res == NOT_ENOUGH_DATA) return true;
6500 if (res != OK) {
6501 // Something bad happened; try to recover by cancelling prepare and
6502 // signalling listener anyway
6503 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6504 mCurrentStream->getId(), res, strerror(-res));
6505 mCurrentStream->cancelPrepare();
6506 }
6507
6508 // This stream has finished, notify listener
6509 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006510 sp<NotificationListener> listener = mListener.promote();
6511 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006512 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6513 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006514 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006515 }
6516
6517 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6518 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006519 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006520
6521 return true;
6522}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006523
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006524status_t Camera3Device::RequestBufferStateMachine::initialize(
6525 sp<camera3::StatusTracker> statusTracker) {
6526 if (statusTracker == nullptr) {
6527 ALOGE("%s: statusTracker is null", __FUNCTION__);
6528 return BAD_VALUE;
6529 }
6530
6531 std::lock_guard<std::mutex> lock(mLock);
6532 mStatusTracker = statusTracker;
6533 mRequestBufferStatusId = statusTracker->addComponent();
6534 return OK;
6535}
6536
6537bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6538 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006539 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006540 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006541 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006542 return true;
6543 }
6544 return false;
6545}
6546
6547void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6548 std::lock_guard<std::mutex> lock(mLock);
6549 if (!mRequestBufferOngoing) {
6550 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6551 return;
6552 }
6553 mRequestBufferOngoing = false;
6554 if (mStatus == RB_STATUS_PENDING_STOP) {
6555 checkSwitchToStopLocked();
6556 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006557 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006558}
6559
6560void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6561 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006562 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006563 return;
6564}
6565
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006566void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006567 std::lock_guard<std::mutex> lock(mLock);
6568 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006569 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6570 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006571 mInflightMapEmpty = false;
6572 if (mStatus == RB_STATUS_STOPPED) {
6573 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006574 }
6575 return;
6576}
6577
6578void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6579 std::lock_guard<std::mutex> lock(mLock);
6580 mRequestThreadPaused = true;
6581 if (mStatus == RB_STATUS_PENDING_STOP) {
6582 checkSwitchToStopLocked();
6583 }
6584 return;
6585}
6586
6587void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6588 std::lock_guard<std::mutex> lock(mLock);
6589 mInflightMapEmpty = true;
6590 if (mStatus == RB_STATUS_PENDING_STOP) {
6591 checkSwitchToStopLocked();
6592 }
6593 return;
6594}
6595
6596void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6597 std::lock_guard<std::mutex> lock(mLock);
6598 if (!checkSwitchToStopLocked()) {
6599 mStatus = RB_STATUS_PENDING_STOP;
6600 }
6601 return;
6602}
6603
6604void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6605 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6606 if (statusTracker != nullptr) {
6607 if (active) {
6608 statusTracker->markComponentActive(mRequestBufferStatusId);
6609 } else {
6610 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6611 }
6612 }
6613}
6614
6615bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6616 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6617 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006618 return true;
6619 }
6620 return false;
6621}
6622
Shuzhen Wang268a1362018-10-16 16:32:59 -07006623status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6624 CameraMetadata& resultMetadata) {
6625 status_t res = OK;
6626 if (!mNeedFixupMonochromeTags) {
6627 return res;
6628 }
6629
6630 // Remove tags that are not applicable to monochrome camera.
6631 int32_t tagsToRemove[] = {
6632 ANDROID_SENSOR_GREEN_SPLIT,
6633 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6634 ANDROID_COLOR_CORRECTION_MODE,
6635 ANDROID_COLOR_CORRECTION_TRANSFORM,
6636 ANDROID_COLOR_CORRECTION_GAINS,
6637 };
6638 for (auto tag : tagsToRemove) {
6639 res = resultMetadata.erase(tag);
6640 if (res != OK) {
6641 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6642 return res;
6643 }
6644 }
6645
6646 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6647 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6648 for (size_t i = 1; i < blEntry.count; i++) {
6649 blEntry.data.f[i] = blEntry.data.f[0];
6650 }
6651
6652 // ANDROID_SENSOR_NOISE_PROFILE
6653 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6654 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6655 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6656 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6657 if (res != OK) {
6658 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6659 __FUNCTION__, strerror(-res), res);
6660 return res;
6661 }
6662 }
6663
6664 // ANDROID_STATISTICS_LENS_SHADING_MAP
6665 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6666 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6667 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6668 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6669 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6670 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6671 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6672 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6673 }
6674 }
6675
6676 // ANDROID_TONEMAP_CURVE_BLUE
6677 // ANDROID_TONEMAP_CURVE_GREEN
6678 // ANDROID_TONEMAP_CURVE_RED
6679 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6680 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6681 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6682 if (tcbEntry.count > 0
6683 && tcbEntry.count == tcgEntry.count
6684 && tcbEntry.count == tcrEntry.count) {
6685 for (size_t i = 0; i < tcbEntry.count; i++) {
6686 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6687 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6688 }
6689 }
6690
6691 return res;
6692}
6693
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006694}; // namespace android