blob: 1c5281d5eb29b3d9961e61f7289739a9d0e19d5e [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
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -070032#define CLOGW(fmt, ...) ALOGW("Camera %s: %s: " fmt, mId.string(), __FUNCTION__, \
33 ##__VA_ARGS__)
34
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -070035// Convenience macros for transitioning to the error state
36#define SET_ERR(fmt, ...) setErrorState( \
37 "%s: " fmt, __FUNCTION__, \
38 ##__VA_ARGS__)
39#define SET_ERR_L(fmt, ...) setErrorStateLocked( \
40 "%s: " fmt, __FUNCTION__, \
41 ##__VA_ARGS__)
42
Colin Crosse5729fa2014-03-21 15:04:25 -070043#include <inttypes.h>
44
Shuzhen Wang5c22c152017-12-31 17:12:25 -080045#include <utility>
46
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080047#include <utils/Log.h>
48#include <utils/Trace.h>
49#include <utils/Timers.h>
Zhijun He90f7c372016-08-16 16:19:43 -070050#include <cutils/properties.h>
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070051
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -080052#include <android/hardware/camera2/ICameraDeviceUser.h>
53
Igor Murashkinff3e31d2013-10-23 16:40:06 -070054#include "utils/CameraTraces.h"
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -070055#include "mediautils/SchedulingPolicyService.h"
Eino-Ville Talvala7b82efe2013-07-25 17:12:35 -070056#include "device3/Camera3Device.h"
57#include "device3/Camera3OutputStream.h"
58#include "device3/Camera3InputStream.h"
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -070059#include "device3/Camera3DummyStream.h"
Shuzhen Wang0129d522016-10-30 22:43:41 -070060#include "device3/Camera3SharedOutputStream.h"
Yin-Chia Yehb978c382019-10-30 00:22:37 -070061#include "device3/Camera3OfflineSession.h"
Eino-Ville Talvalaf67e23e2014-07-23 17:17:59 -070062#include "CameraService.h"
Jayant Chowdhary12361932018-08-27 14:46:13 -070063#include "utils/CameraThreadState.h"
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080064
Yin-Chia Yeh84be5782019-03-01 11:47:02 -080065#include <tuple>
66
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -080067using namespace android::camera3;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080068using namespace android::hardware::camera;
69using namespace android::hardware::camera::device::V3_2;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080070
71namespace android {
72
Eino-Ville Talvala2f09bac2016-12-13 11:29:54 -080073Camera3Device::Camera3Device(const String8 &id):
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080074 mId(id),
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -080075 mOperatingMode(NO_MODE),
Eino-Ville Talvala9a179412015-06-09 13:15:16 -070076 mIsConstrainedHighSpeedConfiguration(false),
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -070077 mStatus(STATUS_UNINITIALIZED),
Ruben Brunk183f0562015-08-12 12:55:02 -070078 mStatusWaiters(0),
Zhijun He204e3292014-07-14 17:09:23 -070079 mUsePartialResult(false),
80 mNumPartialResults(1),
Shuzhen Wangc28dccc2016-02-11 23:48:46 -080081 mTimestampOffset(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070082 mNextResultFrameNumber(0),
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -070083 mNextReprocessResultFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070084 mNextZslStillResultFrameNumber(0),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -070085 mNextShutterFrameNumber(0),
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -070086 mNextReprocessShutterFrameNumber(0),
Shuzhen Wang5ee99842019-04-12 11:55:48 -070087 mNextZslStillShutterFrameNumber(0),
Emilian Peev71c73a22017-03-21 16:35:51 +000088 mListener(NULL),
Emilian Peev811d2952018-05-25 11:08:40 +010089 mVendorTagId(CAMERA_METADATA_INVALID_VENDOR_ID),
Shuzhen Wang268a1362018-10-16 16:32:59 -070090 mLastTemplateId(-1),
91 mNeedFixupMonochromeTags(false)
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080092{
93 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -080094 ALOGV("%s: Created device for camera %s", __FUNCTION__, mId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -080095}
96
97Camera3Device::~Camera3Device()
98{
99 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800100 ALOGV("%s: Tearing down for camera id %s", __FUNCTION__, mId.string());
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700101 disconnectImpl();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800102}
103
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800104const String8& Camera3Device::getId() const {
Igor Murashkin71381052013-03-04 14:53:08 -0800105 return mId;
106}
107
Emilian Peevbd8c5032018-02-14 23:05:40 +0000108status_t Camera3Device::initialize(sp<CameraProviderManager> manager, const String8& monitorTags) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800109 ATRACE_CALL();
110 Mutex::Autolock il(mInterfaceLock);
111 Mutex::Autolock l(mLock);
112
113 ALOGV("%s: Initializing HIDL device for camera %s", __FUNCTION__, mId.string());
114 if (mStatus != STATUS_UNINITIALIZED) {
115 CLOGE("Already initialized!");
116 return INVALID_OPERATION;
117 }
118 if (manager == nullptr) return INVALID_OPERATION;
119
120 sp<ICameraDeviceSession> session;
121 ATRACE_BEGIN("CameraHal::openSession");
Steven Moreland5ff9c912017-03-09 23:13:00 -0800122 status_t res = manager->openSession(mId.string(), this,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800123 /*out*/ &session);
124 ATRACE_END();
125 if (res != OK) {
126 SET_ERR_L("Could not open camera session: %s (%d)", strerror(-res), res);
127 return res;
128 }
129
Steven Moreland5ff9c912017-03-09 23:13:00 -0800130 res = manager->getCameraCharacteristics(mId.string(), &mDeviceInfo);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800131 if (res != OK) {
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700132 SET_ERR_L("Could not retrieve camera characteristics: %s (%d)", strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800133 session->close();
134 return res;
135 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800136 mSupportNativeZoomRatio = manager->supportNativeZoomRatio(mId.string());
Yin-Chia Yeh52778d42016-12-22 18:20:43 -0800137
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700138 std::vector<std::string> physicalCameraIds;
Shuzhen Wang03d8cc12018-09-12 14:17:09 -0700139 bool isLogical = manager->isLogicalCamera(mId.string(), &physicalCameraIds);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700140 if (isLogical) {
141 for (auto& physicalId : physicalCameraIds) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700142 res = manager->getCameraCharacteristics(
143 physicalId, &mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700144 if (res != OK) {
145 SET_ERR_L("Could not retrieve camera %s characteristics: %s (%d)",
146 physicalId.c_str(), strerror(-res), res);
147 session->close();
148 return res;
149 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700150
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800151 bool usePrecorrectArray =
152 DistortionMapper::isDistortionSupported(mPhysicalDeviceInfoMap[physicalId]);
153 if (usePrecorrectArray) {
154 res = mDistortionMappers[physicalId].setupStaticInfo(
155 mPhysicalDeviceInfoMap[physicalId]);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700156 if (res != OK) {
157 SET_ERR_L("Unable to read camera %s's calibration fields for distortion "
158 "correction", physicalId.c_str());
159 session->close();
160 return res;
161 }
162 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800163
164 res = mZoomRatioMappers[physicalId].initZoomRatioTags(
165 &mPhysicalDeviceInfoMap[physicalId],
166 mSupportNativeZoomRatio, usePrecorrectArray);
167 if (res != OK) {
168 SET_ERR_L("Failed to initialize camera %s's zoomRatio tags: %s (%d)",
169 physicalId.c_str(), strerror(-res), res);
170 return res;
171 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700172 }
173 }
174
Yifan Hongf79b5542017-04-11 14:44:25 -0700175 std::shared_ptr<RequestMetadataQueue> queue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700176 auto requestQueueRet = session->getCaptureRequestMetadataQueue(
177 [&queue](const auto& descriptor) {
178 queue = std::make_shared<RequestMetadataQueue>(descriptor);
179 if (!queue->isValid() || queue->availableToWrite() <= 0) {
180 ALOGE("HAL returns empty request metadata fmq, not use it");
181 queue = nullptr;
182 // don't use the queue onwards.
183 }
184 });
185 if (!requestQueueRet.isOk()) {
186 ALOGE("Transaction error when getting request metadata fmq: %s, not use it",
187 requestQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700188 return DEAD_OBJECT;
Yifan Hongf79b5542017-04-11 14:44:25 -0700189 }
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700190
191 std::unique_ptr<ResultMetadataQueue>& resQueue = mResultMetadataQueue;
Yifan Honga640c5a2017-04-12 16:30:31 -0700192 auto resultQueueRet = session->getCaptureResultMetadataQueue(
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700193 [&resQueue](const auto& descriptor) {
194 resQueue = std::make_unique<ResultMetadataQueue>(descriptor);
195 if (!resQueue->isValid() || resQueue->availableToWrite() <= 0) {
Yifan Honga640c5a2017-04-12 16:30:31 -0700196 ALOGE("HAL returns empty result metadata fmq, not use it");
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700197 resQueue = nullptr;
198 // Don't use the resQueue onwards.
Yifan Honga640c5a2017-04-12 16:30:31 -0700199 }
200 });
201 if (!resultQueueRet.isOk()) {
202 ALOGE("Transaction error when getting result metadata queue from camera session: %s",
203 resultQueueRet.description().c_str());
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -0700204 return DEAD_OBJECT;
Yifan Honga640c5a2017-04-12 16:30:31 -0700205 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700206 IF_ALOGV() {
207 session->interfaceChain([](
208 ::android::hardware::hidl_vec<::android::hardware::hidl_string> interfaceChain) {
209 ALOGV("Session interface chain:");
Chih-Hung Hsieh3ef324d2018-12-11 11:48:12 -0800210 for (const auto& iface : interfaceChain) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700211 ALOGV(" %s", iface.c_str());
212 }
213 });
214 }
Yifan Hongf79b5542017-04-11 14:44:25 -0700215
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800216 camera_metadata_entry bufMgrMode =
217 mDeviceInfo.find(ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION);
218 if (bufMgrMode.count > 0) {
219 mUseHalBufManager = (bufMgrMode.data.u8[0] ==
220 ANDROID_INFO_SUPPORTED_BUFFER_MANAGEMENT_VERSION_HIDL_DEVICE_3_5);
221 }
222
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700223 camera_metadata_entry_t capabilities = mDeviceInfo.find(ANDROID_REQUEST_AVAILABLE_CAPABILITIES);
224 for (size_t i = 0; i < capabilities.count; i++) {
225 uint8_t capability = capabilities.data.u8[i];
226 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_OFFLINE_PROCESSING) {
227 mSupportOfflineProcessing = true;
228 }
229 }
230
231 mInterface = new HalInterface(session, queue, mUseHalBufManager, mSupportOfflineProcessing);
Emilian Peev71c73a22017-03-21 16:35:51 +0000232 std::string providerType;
233 mVendorTagId = manager->getProviderTagIdLocked(mId.string());
Emilian Peevbd8c5032018-02-14 23:05:40 +0000234 mTagMonitor.initialize(mVendorTagId);
235 if (!monitorTags.isEmpty()) {
236 mTagMonitor.parseTagsToMonitor(String8(monitorTags));
237 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800238
Shuzhen Wang268a1362018-10-16 16:32:59 -0700239 // Metadata tags needs fixup for monochrome camera device version less
240 // than 3.5.
241 hardware::hidl_version maxVersion{0,0};
242 res = manager->getHighestSupportedVersion(mId.string(), &maxVersion);
243 if (res != OK) {
244 ALOGE("%s: Error in getting camera device version id: %s (%d)",
245 __FUNCTION__, strerror(-res), res);
246 return res;
247 }
248 int deviceVersion = HARDWARE_DEVICE_API_VERSION(
249 maxVersion.get_major(), maxVersion.get_minor());
250
251 bool isMonochrome = false;
Yin-Chia Yehb978c382019-10-30 00:22:37 -0700252 for (size_t i = 0; i < capabilities.count; i++) {
253 uint8_t capability = capabilities.data.u8[i];
Shuzhen Wang268a1362018-10-16 16:32:59 -0700254 if (capability == ANDROID_REQUEST_AVAILABLE_CAPABILITIES_MONOCHROME) {
255 isMonochrome = true;
256 }
257 }
258 mNeedFixupMonochromeTags = (isMonochrome && deviceVersion < CAMERA_DEVICE_API_VERSION_3_5);
259
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800260 return initializeCommonLocked();
261}
262
263status_t Camera3Device::initializeCommonLocked() {
264
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700265 /** Start up status tracker thread */
266 mStatusTracker = new StatusTracker(this);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800267 status_t res = mStatusTracker->run(String8::format("C3Dev-%s-Status", mId.string()).string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700268 if (res != OK) {
269 SET_ERR_L("Unable to start status tracking thread: %s (%d)",
270 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800271 mInterface->close();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700272 mStatusTracker.clear();
273 return res;
274 }
275
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -0700276 /** Register in-flight map to the status tracker */
277 mInFlightStatusId = mStatusTracker->addComponent();
278
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -0700279 if (mUseHalBufManager) {
280 res = mRequestBufferSM.initialize(mStatusTracker);
281 if (res != OK) {
282 SET_ERR_L("Unable to start request buffer state machine: %s (%d)",
283 strerror(-res), res);
284 mInterface->close();
285 mStatusTracker.clear();
286 return res;
287 }
288 }
289
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -0800290 /** Create buffer manager */
291 mBufferManager = new Camera3BufferManager();
292
293 Vector<int32_t> sessionParamKeys;
294 camera_metadata_entry_t sessionKeysEntry = mDeviceInfo.find(
295 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
296 if (sessionKeysEntry.count > 0) {
297 sessionParamKeys.insertArrayAt(sessionKeysEntry.data.i32, 0, sessionKeysEntry.count);
298 }
299
Chien-Yu Chenab5135b2015-06-30 11:20:58 -0700300 /** Start up request queue thread */
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -0700301 mRequestThread = new RequestThread(
302 this, mStatusTracker, mInterface, sessionParamKeys, mUseHalBufManager);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800303 res = mRequestThread->run(String8::format("C3Dev-%s-ReqQueue", mId.string()).string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800304 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700305 SET_ERR_L("Unable to start request queue thread: %s (%d)",
306 strerror(-res), res);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800307 mInterface->close();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800308 mRequestThread.clear();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800309 return res;
310 }
311
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -0700312 mPreparerThread = new PreparerThread();
313
Ruben Brunk183f0562015-08-12 12:55:02 -0700314 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800315 mNextStreamId = 0;
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -0700316 mDummyStreamId = NO_STREAM;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -0700317 mNeedConfig = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700318 mPauseStateNotify = false;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800319
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800320 // Measure the clock domain offset between camera and video/hw_composer
321 camera_metadata_entry timestampSource =
322 mDeviceInfo.find(ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE);
323 if (timestampSource.count > 0 && timestampSource.data.u8[0] ==
324 ANDROID_SENSOR_INFO_TIMESTAMP_SOURCE_REALTIME) {
325 mTimestampOffset = getMonoToBoottimeOffset();
326 }
327
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700328 // Will the HAL be sending in early partial result metadata?
Emilian Peev08dd2452017-04-06 16:55:14 +0100329 camera_metadata_entry partialResultsCount =
330 mDeviceInfo.find(ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
331 if (partialResultsCount.count > 0) {
332 mNumPartialResults = partialResultsCount.data.i32[0];
333 mUsePartialResult = (mNumPartialResults > 1);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -0700334 }
335
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -0700336 camera_metadata_entry configs =
337 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
338 for (uint32_t i = 0; i < configs.count; i += 4) {
339 if (configs.data.i32[i] == HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED &&
340 configs.data.i32[i + 3] ==
341 ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_INPUT) {
342 mSupportedOpaqueInputSizes.add(Size(configs.data.i32[i + 1],
343 configs.data.i32[i + 2]));
344 }
345 }
346
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800347 bool usePrecorrectArray = DistortionMapper::isDistortionSupported(mDeviceInfo);
348 if (usePrecorrectArray) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -0700349 res = mDistortionMappers[mId.c_str()].setupStaticInfo(mDeviceInfo);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -0700350 if (res != OK) {
351 SET_ERR_L("Unable to read necessary calibration fields for distortion correction");
352 return res;
353 }
354 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -0800355
356 res = mZoomRatioMappers[mId.c_str()].initZoomRatioTags(&mDeviceInfo,
357 mSupportNativeZoomRatio, usePrecorrectArray);
358 if (res != OK) {
359 SET_ERR_L("Failed to initialize zoomRatio tags: %s (%d)",
360 strerror(-res), res);
361 return res;
362 }
363
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800364 return OK;
365}
366
367status_t Camera3Device::disconnect() {
Yin-Chia Yehc5248132018-08-15 12:19:20 -0700368 return disconnectImpl();
369}
370
371status_t Camera3Device::disconnectImpl() {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800372 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700373 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800374
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700375 ALOGI("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800376
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700377 status_t res = OK;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700378 std::vector<wp<Camera3StreamInterface>> streams;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -0700379 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700380 {
381 Mutex::Autolock l(mLock);
382 if (mStatus == STATUS_UNINITIALIZED) return res;
383
384 if (mStatus == STATUS_ACTIVE ||
385 (mStatus == STATUS_ERROR && mRequestThread != NULL)) {
386 res = mRequestThread->clearRepeatingRequests();
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700387 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700388 SET_ERR_L("Can't stop streaming");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700389 // Continue to close device even in case of error
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700390 } else {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700391 res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700392 if (res != OK) {
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -0700393 SET_ERR_L("Timeout waiting for HAL to drain (% " PRIi64 " ns)",
394 maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700395 // Continue to close device even in case of error
396 }
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700397 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800398 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800399
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700400 if (mStatus == STATUS_ERROR) {
401 CLOGE("Shutting down in an error state");
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700402 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700403
404 if (mStatusTracker != NULL) {
405 mStatusTracker->requestExit();
406 }
407
408 if (mRequestThread != NULL) {
409 mRequestThread->requestExit();
410 }
411
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700412 streams.reserve(mOutputStreams.size() + (mInputStream != nullptr ? 1 : 0));
413 for (size_t i = 0; i < mOutputStreams.size(); i++) {
414 streams.push_back(mOutputStreams[i]);
415 }
416 if (mInputStream != nullptr) {
417 streams.push_back(mInputStream);
418 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700419 }
420
421 // Joining done without holding mLock, otherwise deadlocks may ensue
422 // as the threads try to access parent state
423 if (mRequestThread != NULL && mStatus != STATUS_ERROR) {
424 // HAL may be in a bad state, so waiting for request thread
425 // (which may be stuck in the HAL processCaptureRequest call)
426 // could be dangerous.
427 mRequestThread->join();
428 }
429
430 if (mStatusTracker != NULL) {
431 mStatusTracker->join();
432 }
433
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800434 HalInterface* interface;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700435 {
436 Mutex::Autolock l(mLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800437 mRequestThread.clear();
Emilian Peev2843c362018-09-26 08:49:40 +0100438 Mutex::Autolock stLock(mTrackerLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700439 mStatusTracker.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800440 interface = mInterface.get();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700441 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800442
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700443 // Call close without internal mutex held, as the HAL close may need to
444 // wait on assorted callbacks,etc, to complete before it can return.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800445 interface->close();
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700446
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700447 flushInflightRequests();
448
Eino-Ville Talvalaefff1c42015-08-28 16:27:27 -0700449 {
450 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800451 mInterface->clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700452 mOutputStreams.clear();
453 mInputStream.clear();
Yin-Chia Yeh5090c732017-07-20 16:05:29 -0700454 mDeletedStreams.clear();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700455 mBufferManager.clear();
Ruben Brunk183f0562015-08-12 12:55:02 -0700456 internalUpdateStatusLocked(STATUS_UNINITIALIZED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700457 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800458
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -0700459 for (auto& weakStream : streams) {
460 sp<Camera3StreamInterface> stream = weakStream.promote();
461 if (stream != nullptr) {
462 ALOGE("%s: Stream %d leaked! strong reference (%d)!",
463 __FUNCTION__, stream->getId(), stream->getStrongCount() - 1);
464 }
465 }
466
Yin-Chia Yehe1c80632016-08-08 14:48:05 -0700467 ALOGI("%s: X", __FUNCTION__);
Eino-Ville Talvala214a17f2013-06-13 12:20:02 -0700468 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800469}
470
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700471// For dumping/debugging only -
472// try to acquire a lock a few times, eventually give up to proceed with
473// debug/dump operations
474bool Camera3Device::tryLockSpinRightRound(Mutex& lock) {
475 bool gotLock = false;
476 for (size_t i = 0; i < kDumpLockAttempts; ++i) {
477 if (lock.tryLock() == NO_ERROR) {
478 gotLock = true;
479 break;
480 } else {
481 usleep(kDumpSleepDuration);
482 }
483 }
484 return gotLock;
485}
486
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700487Camera3Device::Size Camera3Device::getMaxJpegResolution() const {
488 int32_t maxJpegWidth = 0, maxJpegHeight = 0;
Emilian Peev08dd2452017-04-06 16:55:14 +0100489 const int STREAM_CONFIGURATION_SIZE = 4;
490 const int STREAM_FORMAT_OFFSET = 0;
491 const int STREAM_WIDTH_OFFSET = 1;
492 const int STREAM_HEIGHT_OFFSET = 2;
493 const int STREAM_IS_INPUT_OFFSET = 3;
494 camera_metadata_ro_entry_t availableStreamConfigs =
495 mDeviceInfo.find(ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS);
496 if (availableStreamConfigs.count == 0 ||
497 availableStreamConfigs.count % STREAM_CONFIGURATION_SIZE != 0) {
498 return Size(0, 0);
499 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700500
Emilian Peev08dd2452017-04-06 16:55:14 +0100501 // Get max jpeg size (area-wise).
502 for (size_t i=0; i < availableStreamConfigs.count; i+= STREAM_CONFIGURATION_SIZE) {
503 int32_t format = availableStreamConfigs.data.i32[i + STREAM_FORMAT_OFFSET];
504 int32_t width = availableStreamConfigs.data.i32[i + STREAM_WIDTH_OFFSET];
505 int32_t height = availableStreamConfigs.data.i32[i + STREAM_HEIGHT_OFFSET];
506 int32_t isInput = availableStreamConfigs.data.i32[i + STREAM_IS_INPUT_OFFSET];
507 if (isInput == ANDROID_SCALER_AVAILABLE_STREAM_CONFIGURATIONS_OUTPUT
508 && format == HAL_PIXEL_FORMAT_BLOB &&
509 (width * height > maxJpegWidth * maxJpegHeight)) {
510 maxJpegWidth = width;
511 maxJpegHeight = height;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700512 }
513 }
Emilian Peev08dd2452017-04-06 16:55:14 +0100514
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700515 return Size(maxJpegWidth, maxJpegHeight);
516}
517
Shuzhen Wangc28dccc2016-02-11 23:48:46 -0800518nsecs_t Camera3Device::getMonoToBoottimeOffset() {
519 // try three times to get the clock offset, choose the one
520 // with the minimum gap in measurements.
521 const int tries = 3;
522 nsecs_t bestGap, measured;
523 for (int i = 0; i < tries; ++i) {
524 const nsecs_t tmono = systemTime(SYSTEM_TIME_MONOTONIC);
525 const nsecs_t tbase = systemTime(SYSTEM_TIME_BOOTTIME);
526 const nsecs_t tmono2 = systemTime(SYSTEM_TIME_MONOTONIC);
527 const nsecs_t gap = tmono2 - tmono;
528 if (i == 0 || gap < bestGap) {
529 bestGap = gap;
530 measured = tbase - ((tmono + tmono2) >> 1);
531 }
532 }
533 return measured;
534}
535
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800536hardware::graphics::common::V1_0::PixelFormat Camera3Device::mapToPixelFormat(
537 int frameworkFormat) {
538 return (hardware::graphics::common::V1_0::PixelFormat) frameworkFormat;
539}
540
541DataspaceFlags Camera3Device::mapToHidlDataspace(
542 android_dataspace dataSpace) {
543 return dataSpace;
544}
545
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700546BufferUsageFlags Camera3Device::mapToConsumerUsage(
Emilian Peev050f5dc2017-05-18 14:43:56 +0100547 uint64_t usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700548 return usage;
549}
550
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800551StreamRotation Camera3Device::mapToStreamRotation(camera3_stream_rotation_t rotation) {
552 switch (rotation) {
553 case CAMERA3_STREAM_ROTATION_0:
554 return StreamRotation::ROTATION_0;
555 case CAMERA3_STREAM_ROTATION_90:
556 return StreamRotation::ROTATION_90;
557 case CAMERA3_STREAM_ROTATION_180:
558 return StreamRotation::ROTATION_180;
559 case CAMERA3_STREAM_ROTATION_270:
560 return StreamRotation::ROTATION_270;
561 }
562 ALOGE("%s: Unknown stream rotation %d", __FUNCTION__, rotation);
563 return StreamRotation::ROTATION_0;
564}
565
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800566status_t Camera3Device::mapToStreamConfigurationMode(
567 camera3_stream_configuration_mode_t operationMode, StreamConfigurationMode *mode) {
568 if (mode == nullptr) return BAD_VALUE;
569 if (operationMode < CAMERA3_VENDOR_STREAM_CONFIGURATION_MODE_START) {
570 switch(operationMode) {
571 case CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE:
572 *mode = StreamConfigurationMode::NORMAL_MODE;
573 break;
574 case CAMERA3_STREAM_CONFIGURATION_CONSTRAINED_HIGH_SPEED_MODE:
575 *mode = StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE;
576 break;
577 default:
578 ALOGE("%s: Unknown stream configuration mode %d", __FUNCTION__, operationMode);
579 return BAD_VALUE;
580 }
581 } else {
582 *mode = static_cast<StreamConfigurationMode>(operationMode);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800583 }
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800584 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800585}
586
587camera3_buffer_status_t Camera3Device::mapHidlBufferStatus(BufferStatus status) {
588 switch (status) {
589 case BufferStatus::OK: return CAMERA3_BUFFER_STATUS_OK;
590 case BufferStatus::ERROR: return CAMERA3_BUFFER_STATUS_ERROR;
591 }
592 return CAMERA3_BUFFER_STATUS_ERROR;
593}
594
595int Camera3Device::mapToFrameworkFormat(
596 hardware::graphics::common::V1_0::PixelFormat pixelFormat) {
597 return static_cast<uint32_t>(pixelFormat);
598}
599
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -0700600android_dataspace Camera3Device::mapToFrameworkDataspace(
601 DataspaceFlags dataSpace) {
602 return static_cast<android_dataspace>(dataSpace);
603}
604
Emilian Peev050f5dc2017-05-18 14:43:56 +0100605uint64_t Camera3Device::mapConsumerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700606 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700607 return usage;
608}
609
Emilian Peev050f5dc2017-05-18 14:43:56 +0100610uint64_t Camera3Device::mapProducerToFrameworkUsage(
Chia-I Wu67a0c0e2017-04-06 13:37:01 -0700611 BufferUsageFlags usage) {
Yin-Chia Yeh47cf8e62017-04-04 13:00:03 -0700612 return usage;
613}
614
Zhijun Hef7da0962014-04-24 13:27:56 -0700615ssize_t Camera3Device::getJpegBufferSize(uint32_t width, uint32_t height) const {
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700616 // Get max jpeg size (area-wise).
617 Size maxJpegResolution = getMaxJpegResolution();
618 if (maxJpegResolution.width == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800619 ALOGE("%s: Camera %s: Can't find valid available jpeg sizes in static metadata!",
620 __FUNCTION__, mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700621 return BAD_VALUE;
622 }
623
Zhijun Hef7da0962014-04-24 13:27:56 -0700624 // Get max jpeg buffer size
625 ssize_t maxJpegBufferSize = 0;
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700626 camera_metadata_ro_entry jpegBufMaxSize = mDeviceInfo.find(ANDROID_JPEG_MAX_SIZE);
627 if (jpegBufMaxSize.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800628 ALOGE("%s: Camera %s: Can't find maximum JPEG size in static metadata!", __FUNCTION__,
629 mId.string());
Zhijun Hef7da0962014-04-24 13:27:56 -0700630 return BAD_VALUE;
631 }
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700632 maxJpegBufferSize = jpegBufMaxSize.data.i32[0];
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800633 assert(kMinJpegBufferSize < maxJpegBufferSize);
Zhijun Hef7da0962014-04-24 13:27:56 -0700634
635 // Calculate final jpeg buffer size for the given resolution.
Yin-Chia Yehcd8fce82014-06-18 10:51:34 -0700636 float scaleFactor = ((float) (width * height)) /
637 (maxJpegResolution.width * maxJpegResolution.height);
Yin-Chia Yeh0c4e56d2015-01-09 15:21:27 -0800638 ssize_t jpegBufferSize = scaleFactor * (maxJpegBufferSize - kMinJpegBufferSize) +
639 kMinJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700640 if (jpegBufferSize > maxJpegBufferSize) {
641 jpegBufferSize = maxJpegBufferSize;
Zhijun Hef7da0962014-04-24 13:27:56 -0700642 }
643
644 return jpegBufferSize;
645}
646
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700647ssize_t Camera3Device::getPointCloudBufferSize() const {
648 const int FLOATS_PER_POINT=4;
649 camera_metadata_ro_entry maxPointCount = mDeviceInfo.find(ANDROID_DEPTH_MAX_DEPTH_SAMPLES);
650 if (maxPointCount.count == 0) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800651 ALOGE("%s: Camera %s: Can't find maximum depth point cloud size in static metadata!",
652 __FUNCTION__, mId.string());
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700653 return BAD_VALUE;
654 }
655 ssize_t maxBytesForPointCloud = sizeof(android_depth_points) +
656 maxPointCount.data.i32[0] * sizeof(float) * FLOATS_PER_POINT;
657 return maxBytesForPointCloud;
658}
659
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -0800660ssize_t Camera3Device::getRawOpaqueBufferSize(int32_t width, int32_t height) const {
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800661 const int PER_CONFIGURATION_SIZE = 3;
662 const int WIDTH_OFFSET = 0;
663 const int HEIGHT_OFFSET = 1;
664 const int SIZE_OFFSET = 2;
665 camera_metadata_ro_entry rawOpaqueSizes =
666 mDeviceInfo.find(ANDROID_SENSOR_OPAQUE_RAW_SIZE);
Aurimas Liutikasbc57b122016-02-16 09:59:16 -0800667 size_t count = rawOpaqueSizes.count;
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800668 if (count == 0 || (count % PER_CONFIGURATION_SIZE)) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800669 ALOGE("%s: Camera %s: bad opaque RAW size static metadata length(%zu)!",
670 __FUNCTION__, mId.string(), count);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800671 return BAD_VALUE;
672 }
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700673
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800674 for (size_t i = 0; i < count; i += PER_CONFIGURATION_SIZE) {
675 if (width == rawOpaqueSizes.data.i32[i + WIDTH_OFFSET] &&
676 height == rawOpaqueSizes.data.i32[i + HEIGHT_OFFSET]) {
677 return rawOpaqueSizes.data.i32[i + SIZE_OFFSET];
678 }
679 }
680
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800681 ALOGE("%s: Camera %s: cannot find size for %dx%d opaque RAW image!",
682 __FUNCTION__, mId.string(), width, height);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -0800683 return BAD_VALUE;
684}
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -0700685
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800686status_t Camera3Device::dump(int fd, const Vector<String16> &args) {
687 ATRACE_CALL();
688 (void)args;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700689
690 // Try to lock, but continue in case of failure (to avoid blocking in
691 // deadlocks)
692 bool gotInterfaceLock = tryLockSpinRightRound(mInterfaceLock);
693 bool gotLock = tryLockSpinRightRound(mLock);
694
695 ALOGW_IF(!gotInterfaceLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800696 "Camera %s: %s: Unable to lock interface lock, proceeding anyway",
697 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700698 ALOGW_IF(!gotLock,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800699 "Camera %s: %s: Unable to lock main lock, proceeding anyway",
700 mId.string(), __FUNCTION__);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700701
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800702 bool dumpTemplates = false;
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700703
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800704 String16 templatesOption("-t");
705 int n = args.size();
706 for (int i = 0; i < n; i++) {
707 if (args[i] == templatesOption) {
708 dumpTemplates = true;
709 }
Emilian Peevbd8c5032018-02-14 23:05:40 +0000710 if (args[i] == TagMonitor::kMonitorOption) {
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700711 if (i + 1 < n) {
712 String8 monitorTags = String8(args[i + 1]);
713 if (monitorTags == "off") {
714 mTagMonitor.disableMonitoring();
715 } else {
716 mTagMonitor.parseTagsToMonitor(monitorTags);
717 }
718 } else {
719 mTagMonitor.disableMonitoring();
720 }
721 }
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800722 }
723
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800724 String8 lines;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800725
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800726 const char *status =
727 mStatus == STATUS_ERROR ? "ERROR" :
728 mStatus == STATUS_UNINITIALIZED ? "UNINITIALIZED" :
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700729 mStatus == STATUS_UNCONFIGURED ? "UNCONFIGURED" :
730 mStatus == STATUS_CONFIGURED ? "CONFIGURED" :
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800731 mStatus == STATUS_ACTIVE ? "ACTIVE" :
732 "Unknown";
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700733
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800734 lines.appendFormat(" Device status: %s\n", status);
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700735 if (mStatus == STATUS_ERROR) {
736 lines.appendFormat(" Error cause: %s\n", mErrorCause.string());
737 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800738 lines.appendFormat(" Stream configuration:\n");
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -0800739 const char *mode =
740 mOperatingMode == static_cast<int>(StreamConfigurationMode::NORMAL_MODE) ? "NORMAL" :
741 mOperatingMode == static_cast<int>(
742 StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ? "CONSTRAINED_HIGH_SPEED" :
743 "CUSTOM";
744 lines.appendFormat(" Operation mode: %s (%d) \n", mode, mOperatingMode);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800745
746 if (mInputStream != NULL) {
747 write(fd, lines.string(), lines.size());
748 mInputStream->dump(fd, args);
749 } else {
750 lines.appendFormat(" No input stream.\n");
751 write(fd, lines.string(), lines.size());
752 }
753 for (size_t i = 0; i < mOutputStreams.size(); i++) {
754 mOutputStreams[i]->dump(fd,args);
755 }
756
Zhijun He431503c2016-03-07 17:30:16 -0800757 if (mBufferManager != NULL) {
758 lines = String8(" Camera3 Buffer Manager:\n");
759 write(fd, lines.string(), lines.size());
760 mBufferManager->dump(fd, args);
761 }
Zhijun He125684a2015-12-26 15:07:30 -0800762
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700763 lines = String8(" In-flight requests:\n");
764 if (mInFlightMap.size() == 0) {
765 lines.append(" None\n");
766 } else {
767 for (size_t i = 0; i < mInFlightMap.size(); i++) {
768 InFlightRequest r = mInFlightMap.valueAt(i);
Colin Crosse5729fa2014-03-21 15:04:25 -0700769 lines.appendFormat(" Frame %d | Timestamp: %" PRId64 ", metadata"
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700770 " arrived: %s, buffers left: %d\n", mInFlightMap.keyAt(i),
Chien-Yu Chen43e69a62014-11-25 16:38:33 -0800771 r.shutterTimestamp, r.haveResultMetadata ? "true" : "false",
Eino-Ville Talvala42368d92013-04-09 14:13:50 -0700772 r.numBuffersLeft);
773 }
774 }
775 write(fd, lines.string(), lines.size());
776
Shuzhen Wang686f6442017-06-20 16:16:04 -0700777 if (mRequestThread != NULL) {
778 mRequestThread->dumpCaptureRequestLatency(fd,
779 " ProcessCaptureRequest latency histogram:");
780 }
781
Igor Murashkin1e479c02013-09-06 16:55:14 -0700782 {
783 lines = String8(" Last request sent:\n");
784 write(fd, lines.string(), lines.size());
785
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700786 CameraMetadata lastRequest = getLatestRequestLocked();
Igor Murashkin1e479c02013-09-06 16:55:14 -0700787 lastRequest.dump(fd, /*verbosity*/2, /*indentation*/6);
788 }
789
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800790 if (dumpTemplates) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800791 const char *templateNames[CAMERA3_TEMPLATE_COUNT] = {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800792 "TEMPLATE_PREVIEW",
793 "TEMPLATE_STILL_CAPTURE",
794 "TEMPLATE_VIDEO_RECORD",
795 "TEMPLATE_VIDEO_SNAPSHOT",
796 "TEMPLATE_ZERO_SHUTTER_LAG",
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -0800797 "TEMPLATE_MANUAL",
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800798 };
799
800 for (int i = 1; i < CAMERA3_TEMPLATE_COUNT; i++) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800801 camera_metadata_t *templateRequest = nullptr;
802 mInterface->constructDefaultRequestSettings(
803 (camera3_request_template_t) i, &templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800804 lines = String8::format(" HAL Request %s:\n", templateNames[i-1]);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800805 if (templateRequest == nullptr) {
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800806 lines.append(" Not supported\n");
807 write(fd, lines.string(), lines.size());
808 } else {
809 write(fd, lines.string(), lines.size());
810 dump_indented_camera_metadata(templateRequest,
811 fd, /*verbosity*/2, /*indentation*/8);
812 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800813 free_camera_metadata(templateRequest);
Eino-Ville Talvala7e7a62d2015-11-04 14:49:43 -0800814 }
815 }
816
Eino-Ville Talvala4d453832016-07-15 11:56:53 -0700817 mTagMonitor.dumpMonitoredMetadata(fd);
818
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800819 if (mInterface->valid()) {
Eino-Ville Talvalad00111e2017-01-31 11:59:12 -0800820 lines = String8(" HAL device dump:\n");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800821 write(fd, lines.string(), lines.size());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -0800822 mInterface->dump(fd);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800823 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800824
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -0700825 if (gotLock) mLock.unlock();
826 if (gotInterfaceLock) mInterfaceLock.unlock();
827
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800828 return OK;
829}
830
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700831const CameraMetadata& Camera3Device::info(const String8& physicalId) const {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800832 ALOGVV("%s: E", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800833 if (CC_UNLIKELY(mStatus == STATUS_UNINITIALIZED ||
834 mStatus == STATUS_ERROR)) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -0700835 ALOGW("%s: Access to static info %s!", __FUNCTION__,
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -0800836 mStatus == STATUS_ERROR ?
837 "when in error state" : "before init");
838 }
Shuzhen Wang2e7f58f2018-07-11 14:00:29 -0700839 if (physicalId.isEmpty()) {
840 return mDeviceInfo;
841 } else {
842 std::string id(physicalId.c_str());
843 if (mPhysicalDeviceInfoMap.find(id) != mPhysicalDeviceInfoMap.end()) {
844 return mPhysicalDeviceInfoMap.at(id);
845 } else {
846 ALOGE("%s: Invalid physical camera id %s", __FUNCTION__, physicalId.c_str());
847 return mDeviceInfo;
848 }
849 }
850}
851
852const CameraMetadata& Camera3Device::info() const {
853 String8 emptyId;
854 return info(emptyId);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800855}
856
Jianing Wei90e59c92014-03-12 18:29:36 -0700857status_t Camera3Device::checkStatusOkToCaptureLocked() {
858 switch (mStatus) {
859 case STATUS_ERROR:
860 CLOGE("Device has encountered a serious error");
861 return INVALID_OPERATION;
862 case STATUS_UNINITIALIZED:
863 CLOGE("Device not initialized");
864 return INVALID_OPERATION;
865 case STATUS_UNCONFIGURED:
866 case STATUS_CONFIGURED:
867 case STATUS_ACTIVE:
868 // OK
869 break;
870 default:
871 SET_ERR_L("Unexpected status: %d", mStatus);
872 return INVALID_OPERATION;
873 }
874 return OK;
875}
876
877status_t Camera3Device::convertMetadataListToRequestListLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +0000878 const List<const PhysicalCameraSettingsList> &metadataList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700879 const std::list<const SurfaceMap> &surfaceMaps,
880 bool repeating,
Shuzhen Wang9d066012016-09-30 11:30:20 -0700881 RequestList *requestList) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700882 if (requestList == NULL) {
883 CLOGE("requestList cannot be NULL.");
884 return BAD_VALUE;
885 }
886
Jianing Weicb0652e2014-03-12 18:29:36 -0700887 int32_t burstId = 0;
Emilian Peevaebbe412018-01-15 13:53:24 +0000888 List<const PhysicalCameraSettingsList>::const_iterator metadataIt = metadataList.begin();
Shuzhen Wang0129d522016-10-30 22:43:41 -0700889 std::list<const SurfaceMap>::const_iterator surfaceMapIt = surfaceMaps.begin();
890 for (; metadataIt != metadataList.end() && surfaceMapIt != surfaceMaps.end();
891 ++metadataIt, ++surfaceMapIt) {
892 sp<CaptureRequest> newRequest = setUpRequestLocked(*metadataIt, *surfaceMapIt);
Jianing Wei90e59c92014-03-12 18:29:36 -0700893 if (newRequest == 0) {
894 CLOGE("Can't create capture request");
895 return BAD_VALUE;
896 }
Jianing Weicb0652e2014-03-12 18:29:36 -0700897
Shuzhen Wang9d066012016-09-30 11:30:20 -0700898 newRequest->mRepeating = repeating;
899
Jianing Weicb0652e2014-03-12 18:29:36 -0700900 // Setup burst Id and request Id
901 newRequest->mResultExtras.burstId = burstId++;
Emilian Peevaebbe412018-01-15 13:53:24 +0000902 if (metadataIt->begin()->metadata.exists(ANDROID_REQUEST_ID)) {
903 if (metadataIt->begin()->metadata.find(ANDROID_REQUEST_ID).count == 0) {
Jianing Weicb0652e2014-03-12 18:29:36 -0700904 CLOGE("RequestID entry exists; but must not be empty in metadata");
905 return BAD_VALUE;
906 }
Emilian Peevaebbe412018-01-15 13:53:24 +0000907 newRequest->mResultExtras.requestId = metadataIt->begin()->metadata.find(
908 ANDROID_REQUEST_ID).data.i32[0];
Jianing Weicb0652e2014-03-12 18:29:36 -0700909 } else {
910 CLOGE("RequestID does not exist in metadata");
911 return BAD_VALUE;
912 }
913
Jianing Wei90e59c92014-03-12 18:29:36 -0700914 requestList->push_back(newRequest);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700915
916 ALOGV("%s: requestId = %" PRId32, __FUNCTION__, newRequest->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -0700917 }
Shuzhen Wang0129d522016-10-30 22:43:41 -0700918 if (metadataIt != metadataList.end() || surfaceMapIt != surfaceMaps.end()) {
919 ALOGE("%s: metadataList and surfaceMaps are not the same size!", __FUNCTION__);
920 return BAD_VALUE;
921 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -0700922
923 // Setup batch size if this is a high speed video recording request.
924 if (mIsConstrainedHighSpeedConfiguration && requestList->size() > 0) {
925 auto firstRequest = requestList->begin();
926 for (auto& outputStream : (*firstRequest)->mOutputStreams) {
927 if (outputStream->isVideoStream()) {
928 (*firstRequest)->mBatchSize = requestList->size();
929 break;
930 }
931 }
932 }
933
Jianing Wei90e59c92014-03-12 18:29:36 -0700934 return OK;
935}
936
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800937status_t Camera3Device::capture(CameraMetadata &request, int64_t* lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800938 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800939
Emilian Peevaebbe412018-01-15 13:53:24 +0000940 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -0700941 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +0000942 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700943
Yin-Chia Yeh7e5a2042019-02-06 16:01:06 -0800944 return captureList(requestsList, surfaceMaps, lastFrameNumber);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700945}
946
Emilian Peevaebbe412018-01-15 13:53:24 +0000947void Camera3Device::convertToRequestList(List<const PhysicalCameraSettingsList>& requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700948 std::list<const SurfaceMap>& surfaceMaps,
949 const CameraMetadata& request) {
Emilian Peevaebbe412018-01-15 13:53:24 +0000950 PhysicalCameraSettingsList requestList;
951 requestList.push_back({std::string(getId().string()), request});
952 requestsList.push_back(requestList);
Shuzhen Wang0129d522016-10-30 22:43:41 -0700953
954 SurfaceMap surfaceMap;
955 camera_metadata_ro_entry streams = request.find(ANDROID_REQUEST_OUTPUT_STREAMS);
956 // With no surface list passed in, stream and surface will have 1-to-1
957 // mapping. So the surface index is 0 for each stream in the surfaceMap.
958 for (size_t i = 0; i < streams.count; i++) {
959 surfaceMap[streams.data.i32[i]].push_back(0);
960 }
961 surfaceMaps.push_back(surfaceMap);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -0800962}
963
Jianing Wei90e59c92014-03-12 18:29:36 -0700964status_t Camera3Device::submitRequestsHelper(
Emilian Peevaebbe412018-01-15 13:53:24 +0000965 const List<const PhysicalCameraSettingsList> &requests,
Shuzhen Wang0129d522016-10-30 22:43:41 -0700966 const std::list<const SurfaceMap> &surfaceMaps,
967 bool repeating,
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700968 /*out*/
969 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -0700970 ATRACE_CALL();
971 Mutex::Autolock il(mInterfaceLock);
972 Mutex::Autolock l(mLock);
973
974 status_t res = checkStatusOkToCaptureLocked();
975 if (res != OK) {
976 // error logged by previous call
977 return res;
978 }
979
980 RequestList requestList;
981
Shuzhen Wang0129d522016-10-30 22:43:41 -0700982 res = convertMetadataListToRequestListLocked(requests, surfaceMaps,
983 repeating, /*out*/&requestList);
Jianing Wei90e59c92014-03-12 18:29:36 -0700984 if (res != OK) {
985 // error logged by previous call
986 return res;
987 }
988
989 if (repeating) {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700990 res = mRequestThread->setRepeatingRequests(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700991 } else {
Jianing Wei2d6bb3f2014-04-11 10:00:31 -0700992 res = mRequestThread->queueRequestList(requestList, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -0700993 }
994
995 if (res == OK) {
996 waitUntilStateThenRelock(/*active*/true, kActiveTimeout);
997 if (res != OK) {
998 SET_ERR_L("Can't transition to active in %f seconds!",
999 kActiveTimeout/1e9);
1000 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001001 ALOGV("Camera %s: Capture request %" PRId32 " enqueued", mId.string(),
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001002 (*(requestList.begin()))->mResultExtras.requestId);
Jianing Wei90e59c92014-03-12 18:29:36 -07001003 } else {
1004 CLOGE("Cannot queue request. Impossible.");
1005 return BAD_VALUE;
1006 }
1007
1008 return res;
1009}
1010
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001011hardware::Return<void> Camera3Device::requestStreamBuffers(
1012 const hardware::hidl_vec<hardware::camera::device::V3_5::BufferRequest>& bufReqs,
1013 requestStreamBuffers_cb _hidl_cb) {
1014 using hardware::camera::device::V3_5::BufferRequestStatus;
1015 using hardware::camera::device::V3_5::StreamBufferRet;
1016 using hardware::camera::device::V3_5::StreamBufferRequestError;
1017
1018 std::lock_guard<std::mutex> lock(mRequestBufferInterfaceLock);
1019
1020 hardware::hidl_vec<StreamBufferRet> bufRets;
1021 if (!mUseHalBufManager) {
1022 ALOGE("%s: Camera %s does not support HAL buffer management",
1023 __FUNCTION__, mId.string());
1024 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1025 return hardware::Void();
1026 }
1027
1028 SortedVector<int32_t> streamIds;
1029 ssize_t sz = streamIds.setCapacity(bufReqs.size());
1030 if (sz < 0 || static_cast<size_t>(sz) != bufReqs.size()) {
1031 ALOGE("%s: failed to allocate memory for %zu buffer requests",
1032 __FUNCTION__, bufReqs.size());
1033 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1034 return hardware::Void();
1035 }
1036
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001037 if (bufReqs.size() > mOutputStreams.size()) {
1038 ALOGE("%s: too many buffer requests (%zu > # of output streams %zu)",
1039 __FUNCTION__, bufReqs.size(), mOutputStreams.size());
1040 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1041 return hardware::Void();
1042 }
1043
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001044 // Check for repeated streamId
1045 for (const auto& bufReq : bufReqs) {
1046 if (streamIds.indexOf(bufReq.streamId) != NAME_NOT_FOUND) {
1047 ALOGE("%s: Stream %d appear multiple times in buffer requests",
1048 __FUNCTION__, bufReq.streamId);
1049 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, bufRets);
1050 return hardware::Void();
1051 }
1052 streamIds.add(bufReq.streamId);
1053 }
1054
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001055 if (!mRequestBufferSM.startRequestBuffer()) {
1056 ALOGE("%s: request buffer disallowed while camera service is configuring",
1057 __FUNCTION__);
1058 _hidl_cb(BufferRequestStatus::FAILED_CONFIGURING, bufRets);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001059 return hardware::Void();
1060 }
1061
1062 bufRets.resize(bufReqs.size());
1063
1064 bool allReqsSucceeds = true;
1065 bool oneReqSucceeds = false;
1066 for (size_t i = 0; i < bufReqs.size(); i++) {
1067 const auto& bufReq = bufReqs[i];
1068 auto& bufRet = bufRets[i];
1069 int32_t streamId = bufReq.streamId;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001070 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams.get(streamId);
1071 if (outputStream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001072 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
1073 hardware::hidl_vec<StreamBufferRet> emptyBufRets;
1074 _hidl_cb(BufferRequestStatus::FAILED_ILLEGAL_ARGUMENTS, emptyBufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001075 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001076 return hardware::Void();
1077 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001078
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001079 if (outputStream->isAbandoned()) {
1080 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
1081 allReqsSucceeds = false;
1082 continue;
1083 }
1084
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001085 bufRet.streamId = streamId;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001086 size_t handOutBufferCount = outputStream->getOutstandingBuffersCount();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001087 uint32_t numBuffersRequested = bufReq.numBuffersRequested;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001088 size_t totalHandout = handOutBufferCount + numBuffersRequested;
1089 uint32_t maxBuffers = outputStream->asHalStream()->max_buffers;
1090 if (totalHandout > maxBuffers) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001091 // Not able to allocate enough buffer. Exit early for this stream
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08001092 ALOGE("%s: request too much buffers for stream %d: at HAL: %zu + requesting: %d"
1093 " > max: %d", __FUNCTION__, streamId, handOutBufferCount,
1094 numBuffersRequested, maxBuffers);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001095 bufRet.val.error(StreamBufferRequestError::MAX_BUFFER_EXCEEDED);
1096 allReqsSucceeds = false;
1097 continue;
1098 }
1099
1100 hardware::hidl_vec<StreamBuffer> tmpRetBuffers(numBuffersRequested);
1101 bool currentReqSucceeds = true;
1102 std::vector<camera3_stream_buffer_t> streamBuffers(numBuffersRequested);
1103 size_t numAllocatedBuffers = 0;
1104 size_t numPushedInflightBuffers = 0;
1105 for (size_t b = 0; b < numBuffersRequested; b++) {
1106 camera3_stream_buffer_t& sb = streamBuffers[b];
1107 // Since this method can run concurrently with request thread
1108 // We need to update the wait duration everytime we call getbuffer
1109 nsecs_t waitDuration = kBaseGetBufferWait + getExpectedInFlightDuration();
1110 status_t res = outputStream->getBuffer(&sb, waitDuration);
1111 if (res != OK) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001112 if (res == NO_INIT || res == DEAD_OBJECT) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001113 ALOGV("%s: Can't get output buffer for stream %d: %s (%d)",
1114 __FUNCTION__, streamId, strerror(-res), res);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001115 bufRet.val.error(StreamBufferRequestError::STREAM_DISCONNECTED);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001116 } else {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07001117 ALOGE("%s: Can't get output buffer for stream %d: %s (%d)",
1118 __FUNCTION__, streamId, strerror(-res), res);
1119 if (res == TIMED_OUT || res == NO_MEMORY) {
1120 bufRet.val.error(StreamBufferRequestError::NO_BUFFER_AVAILABLE);
1121 } else {
1122 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1123 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001124 }
1125 currentReqSucceeds = false;
1126 break;
1127 }
1128 numAllocatedBuffers++;
1129
1130 buffer_handle_t *buffer = sb.buffer;
1131 auto pair = mInterface->getBufferId(*buffer, streamId);
1132 bool isNewBuffer = pair.first;
1133 uint64_t bufferId = pair.second;
1134 StreamBuffer& hBuf = tmpRetBuffers[b];
1135
1136 hBuf.streamId = streamId;
1137 hBuf.bufferId = bufferId;
1138 hBuf.buffer = (isNewBuffer) ? *buffer : nullptr;
1139 hBuf.status = BufferStatus::OK;
1140 hBuf.releaseFence = nullptr;
1141
1142 native_handle_t *acquireFence = nullptr;
1143 if (sb.acquire_fence != -1) {
1144 acquireFence = native_handle_create(1,0);
1145 acquireFence->data[0] = sb.acquire_fence;
1146 }
1147 hBuf.acquireFence.setTo(acquireFence, /*shouldOwn*/true);
1148 hBuf.releaseFence = nullptr;
1149
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08001150 res = mInterface->pushInflightRequestBuffer(bufferId, buffer, streamId);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001151 if (res != OK) {
1152 ALOGE("%s: Can't get register request buffers for stream %d: %s (%d)",
1153 __FUNCTION__, streamId, strerror(-res), res);
1154 bufRet.val.error(StreamBufferRequestError::UNKNOWN_ERROR);
1155 currentReqSucceeds = false;
1156 break;
1157 }
1158 numPushedInflightBuffers++;
1159 }
1160 if (currentReqSucceeds) {
1161 bufRet.val.buffers(std::move(tmpRetBuffers));
1162 oneReqSucceeds = true;
1163 } else {
1164 allReqsSucceeds = false;
1165 for (size_t b = 0; b < numPushedInflightBuffers; b++) {
1166 StreamBuffer& hBuf = tmpRetBuffers[b];
1167 buffer_handle_t* buffer;
1168 status_t res = mInterface->popInflightRequestBuffer(hBuf.bufferId, &buffer);
1169 if (res != OK) {
1170 SET_ERR("%s: popInflightRequestBuffer failed for stream %d: %s (%d)",
1171 __FUNCTION__, streamId, strerror(-res), res);
1172 }
1173 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001174 for (size_t b = 0; b < numAllocatedBuffers; b++) {
1175 camera3_stream_buffer_t& sb = streamBuffers[b];
1176 sb.acquire_fence = -1;
1177 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
1178 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001179 returnOutputBuffers(streamBuffers.data(), numAllocatedBuffers, 0);
1180 }
1181 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001182
1183 _hidl_cb(allReqsSucceeds ? BufferRequestStatus::OK :
1184 oneReqSucceeds ? BufferRequestStatus::FAILED_PARTIAL :
1185 BufferRequestStatus::FAILED_UNKNOWN,
1186 bufRets);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07001187 mRequestBufferSM.endRequestBuffer();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001188 return hardware::Void();
1189}
1190
1191hardware::Return<void> Camera3Device::returnStreamBuffers(
1192 const hardware::hidl_vec<hardware::camera::device::V3_2::StreamBuffer>& buffers) {
1193 if (!mUseHalBufManager) {
1194 ALOGE("%s: Camera %s does not support HAL buffer managerment",
1195 __FUNCTION__, mId.string());
1196 return hardware::Void();
1197 }
1198
1199 for (const auto& buf : buffers) {
1200 if (buf.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
1201 ALOGE("%s: cannot return a buffer without bufferId", __FUNCTION__);
1202 continue;
1203 }
1204
1205 buffer_handle_t* buffer;
1206 status_t res = mInterface->popInflightRequestBuffer(buf.bufferId, &buffer);
1207
1208 if (res != OK) {
1209 ALOGE("%s: cannot find in-flight buffer %" PRIu64 " for stream %d",
1210 __FUNCTION__, buf.bufferId, buf.streamId);
1211 continue;
1212 }
1213
1214 camera3_stream_buffer_t streamBuffer;
1215 streamBuffer.buffer = buffer;
1216 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
1217 streamBuffer.acquire_fence = -1;
1218 streamBuffer.release_fence = -1;
1219
1220 if (buf.releaseFence == nullptr) {
1221 streamBuffer.release_fence = -1;
1222 } else if (buf.releaseFence->numFds == 1) {
1223 streamBuffer.release_fence = dup(buf.releaseFence->data[0]);
1224 } else {
1225 ALOGE("%s: Invalid release fence, fd count is %d, not 1",
1226 __FUNCTION__, buf.releaseFence->numFds);
1227 continue;
1228 }
1229
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001230 sp<Camera3StreamInterface> stream = mOutputStreams.get(buf.streamId);
1231 if (stream == nullptr) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001232 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, buf.streamId);
1233 continue;
1234 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001235 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001236 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
1237 }
1238 return hardware::Void();
1239}
1240
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001241hardware::Return<void> Camera3Device::processCaptureResult_3_4(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001242 const hardware::hidl_vec<
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001243 hardware::camera::device::V3_4::CaptureResult>& results) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001244 // Ideally we should grab mLock, but that can lead to deadlock, and
1245 // it's not super important to get up to date value of mStatus for this
1246 // warning print, hence skipping the lock here
1247 if (mStatus == STATUS_ERROR) {
1248 // Per API contract, HAL should act as closed after device error
1249 // But mStatus can be set to error by framework as well, so just log
1250 // a warning here.
1251 ALOGW("%s: received capture result in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001252 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001253
1254 if (mProcessCaptureResultLock.tryLock() != OK) {
1255 // This should never happen; it indicates a wrong client implementation
1256 // that doesn't follow the contract. But, we can be tolerant here.
1257 ALOGE("%s: callback overlapped! waiting 1s...",
1258 __FUNCTION__);
1259 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1260 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1261 __FUNCTION__);
1262 // really don't know what to do, so bail out.
1263 return hardware::Void();
1264 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001265 }
Yifan Honga640c5a2017-04-12 16:30:31 -07001266 for (const auto& result : results) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001267 processOneCaptureResultLocked(result.v3_2, result.physicalCameraMetadata);
Yifan Honga640c5a2017-04-12 16:30:31 -07001268 }
1269 mProcessCaptureResultLock.unlock();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001270 return hardware::Void();
1271}
1272
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001273// Only one processCaptureResult should be called at a time, so
1274// the locks won't block. The locks are present here simply to enforce this.
1275hardware::Return<void> Camera3Device::processCaptureResult(
1276 const hardware::hidl_vec<
1277 hardware::camera::device::V3_2::CaptureResult>& results) {
1278 hardware::hidl_vec<hardware::camera::device::V3_4::PhysicalCameraMetadata> noPhysMetadata;
1279
1280 // Ideally we should grab mLock, but that can lead to deadlock, and
1281 // it's not super important to get up to date value of mStatus for this
1282 // warning print, hence skipping the lock here
1283 if (mStatus == STATUS_ERROR) {
1284 // Per API contract, HAL should act as closed after device error
1285 // But mStatus can be set to error by framework as well, so just log
1286 // a warning here.
1287 ALOGW("%s: received capture result in error state.", __FUNCTION__);
1288 }
1289
1290 if (mProcessCaptureResultLock.tryLock() != OK) {
1291 // This should never happen; it indicates a wrong client implementation
1292 // that doesn't follow the contract. But, we can be tolerant here.
1293 ALOGE("%s: callback overlapped! waiting 1s...",
1294 __FUNCTION__);
1295 if (mProcessCaptureResultLock.timedLock(1000000000 /* 1s */) != OK) {
1296 ALOGE("%s: cannot acquire lock in 1s, dropping results",
1297 __FUNCTION__);
1298 // really don't know what to do, so bail out.
1299 return hardware::Void();
1300 }
1301 }
1302 for (const auto& result : results) {
1303 processOneCaptureResultLocked(result, noPhysMetadata);
1304 }
1305 mProcessCaptureResultLock.unlock();
1306 return hardware::Void();
1307}
1308
1309status_t Camera3Device::readOneCameraMetadataLocked(
1310 uint64_t fmqResultSize, hardware::camera::device::V3_2::CameraMetadata& resultMetadata,
1311 const hardware::camera::device::V3_2::CameraMetadata& result) {
1312 if (fmqResultSize > 0) {
1313 resultMetadata.resize(fmqResultSize);
1314 if (mResultMetadataQueue == nullptr) {
1315 return NO_MEMORY; // logged in initialize()
1316 }
1317 if (!mResultMetadataQueue->read(resultMetadata.data(), fmqResultSize)) {
1318 ALOGE("%s: Cannot read camera metadata from fmq, size = %" PRIu64,
1319 __FUNCTION__, fmqResultSize);
1320 return INVALID_OPERATION;
1321 }
1322 } else {
1323 resultMetadata.setToExternal(const_cast<uint8_t *>(result.data()),
1324 result.size());
1325 }
1326
1327 if (resultMetadata.size() != 0) {
1328 status_t res;
1329 const camera_metadata_t* metadata =
1330 reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
1331 size_t expected_metadata_size = resultMetadata.size();
1332 if ((res = validate_camera_metadata_structure(metadata, &expected_metadata_size)) != OK) {
1333 ALOGE("%s: Invalid camera metadata received by camera service from HAL: %s (%d)",
1334 __FUNCTION__, strerror(-res), res);
1335 return INVALID_OPERATION;
1336 }
1337 }
1338
1339 return OK;
1340}
1341
Yifan Honga640c5a2017-04-12 16:30:31 -07001342void Camera3Device::processOneCaptureResultLocked(
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001343 const hardware::camera::device::V3_2::CaptureResult& result,
1344 const hardware::hidl_vec<
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001345 hardware::camera::device::V3_4::PhysicalCameraMetadata> physicalCameraMetadata) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001346 camera3_capture_result r;
1347 status_t res;
1348 r.frame_number = result.frameNumber;
Yifan Honga640c5a2017-04-12 16:30:31 -07001349
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001350 // Read and validate the result metadata.
Yifan Honga640c5a2017-04-12 16:30:31 -07001351 hardware::camera::device::V3_2::CameraMetadata resultMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001352 res = readOneCameraMetadataLocked(result.fmqResultSize, resultMetadata, result.result);
1353 if (res != OK) {
1354 ALOGE("%s: Frame %d: Failed to read capture result metadata",
1355 __FUNCTION__, result.frameNumber);
1356 return;
Yifan Honga640c5a2017-04-12 16:30:31 -07001357 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001358 r.result = reinterpret_cast<const camera_metadata_t*>(resultMetadata.data());
Yifan Honga640c5a2017-04-12 16:30:31 -07001359
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001360 // Read and validate physical camera metadata
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001361 size_t physResultCount = physicalCameraMetadata.size();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001362 std::vector<const char*> physCamIds(physResultCount);
1363 std::vector<const camera_metadata_t *> phyCamMetadatas(physResultCount);
1364 std::vector<hardware::camera::device::V3_2::CameraMetadata> physResultMetadata;
1365 physResultMetadata.resize(physResultCount);
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001366 for (size_t i = 0; i < physicalCameraMetadata.size(); i++) {
1367 res = readOneCameraMetadataLocked(physicalCameraMetadata[i].fmqMetadataSize,
1368 physResultMetadata[i], physicalCameraMetadata[i].metadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001369 if (res != OK) {
1370 ALOGE("%s: Frame %d: Failed to read capture result metadata for camera %s",
1371 __FUNCTION__, result.frameNumber,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001372 physicalCameraMetadata[i].physicalCameraId.c_str());
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001373 return;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001374 }
Shuzhen Wangc2cba122018-05-17 18:10:24 -07001375 physCamIds[i] = physicalCameraMetadata[i].physicalCameraId.c_str();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001376 phyCamMetadatas[i] = reinterpret_cast<const camera_metadata_t*>(
1377 physResultMetadata[i].data());
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001378 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08001379 r.num_physcam_metadata = physResultCount;
1380 r.physcam_ids = physCamIds.data();
1381 r.physcam_metadata = phyCamMetadatas.data();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001382
1383 std::vector<camera3_stream_buffer_t> outputBuffers(result.outputBuffers.size());
1384 std::vector<buffer_handle_t> outputBufferHandles(result.outputBuffers.size());
1385 for (size_t i = 0; i < result.outputBuffers.size(); i++) {
1386 auto& bDst = outputBuffers[i];
1387 const StreamBuffer &bSrc = result.outputBuffers[i];
1388
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001389 sp<Camera3StreamInterface> stream = mOutputStreams.get(bSrc.streamId);
1390 if (stream == nullptr) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001391 ALOGE("%s: Frame %d: Buffer %zu: Invalid output stream id %d",
1392 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001393 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001394 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001395 bDst.stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001396
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001397 bool noBufferReturned = false;
1398 buffer_handle_t *buffer = nullptr;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001399 if (mUseHalBufManager) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001400 // This is suspicious most of the time but can be correct during flush where HAL
1401 // has to return capture result before a buffer is requested
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001402 if (bSrc.bufferId == HalInterface::BUFFER_ID_NO_BUFFER) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001403 if (bSrc.status == BufferStatus::OK) {
1404 ALOGE("%s: Frame %d: Buffer %zu: No bufferId for stream %d",
1405 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
1406 // Still proceeds so other buffers can be returned
1407 }
1408 noBufferReturned = true;
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001409 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001410 if (noBufferReturned) {
1411 res = OK;
1412 } else {
1413 res = mInterface->popInflightRequestBuffer(bSrc.bufferId, &buffer);
1414 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001415 } else {
1416 res = mInterface->popInflightBuffer(result.frameNumber, bSrc.streamId, &buffer);
1417 }
1418
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001419 if (res != OK) {
1420 ALOGE("%s: Frame %d: Buffer %zu: No in-flight buffer for stream %d",
1421 __FUNCTION__, result.frameNumber, i, bSrc.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001422 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001423 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07001424
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001425 bDst.buffer = buffer;
1426 bDst.status = mapHidlBufferStatus(bSrc.status);
1427 bDst.acquire_fence = -1;
1428 if (bSrc.releaseFence == nullptr) {
1429 bDst.release_fence = -1;
1430 } else if (bSrc.releaseFence->numFds == 1) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08001431 if (noBufferReturned) {
1432 ALOGE("%s: got releaseFence without output buffer!", __FUNCTION__);
1433 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001434 bDst.release_fence = dup(bSrc.releaseFence->data[0]);
1435 } else {
1436 ALOGE("%s: Frame %d: Invalid release fence for buffer %zu, fd count is %d, not 1",
1437 __FUNCTION__, result.frameNumber, i, bSrc.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001438 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001439 }
1440 }
1441 r.num_output_buffers = outputBuffers.size();
1442 r.output_buffers = outputBuffers.data();
1443
1444 camera3_stream_buffer_t inputBuffer;
Yin-Chia Yeh52778d42016-12-22 18:20:43 -08001445 if (result.inputBuffer.streamId == -1) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001446 r.input_buffer = nullptr;
1447 } else {
1448 if (mInputStream->getId() != result.inputBuffer.streamId) {
1449 ALOGE("%s: Frame %d: Invalid input stream id %d", __FUNCTION__,
1450 result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001451 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001452 }
1453 inputBuffer.stream = mInputStream->asHalStream();
1454 buffer_handle_t *buffer;
1455 res = mInterface->popInflightBuffer(result.frameNumber, result.inputBuffer.streamId,
1456 &buffer);
1457 if (res != OK) {
1458 ALOGE("%s: Frame %d: Input buffer: No in-flight buffer for stream %d",
1459 __FUNCTION__, result.frameNumber, result.inputBuffer.streamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001460 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001461 }
1462 inputBuffer.buffer = buffer;
1463 inputBuffer.status = mapHidlBufferStatus(result.inputBuffer.status);
1464 inputBuffer.acquire_fence = -1;
1465 if (result.inputBuffer.releaseFence == nullptr) {
1466 inputBuffer.release_fence = -1;
1467 } else if (result.inputBuffer.releaseFence->numFds == 1) {
1468 inputBuffer.release_fence = dup(result.inputBuffer.releaseFence->data[0]);
1469 } else {
1470 ALOGE("%s: Frame %d: Invalid release fence for input buffer, fd count is %d, not 1",
1471 __FUNCTION__, result.frameNumber, result.inputBuffer.releaseFence->numFds);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001472 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001473 }
1474 r.input_buffer = &inputBuffer;
1475 }
1476
1477 r.partial_result = result.partialResult;
1478
1479 processCaptureResult(&r);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001480}
1481
1482hardware::Return<void> Camera3Device::notify(
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001483 const hardware::hidl_vec<hardware::camera::device::V3_2::NotifyMsg>& msgs) {
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001484 // Ideally we should grab mLock, but that can lead to deadlock, and
1485 // it's not super important to get up to date value of mStatus for this
1486 // warning print, hence skipping the lock here
1487 if (mStatus == STATUS_ERROR) {
1488 // Per API contract, HAL should act as closed after device error
1489 // But mStatus can be set to error by framework as well, so just log
1490 // a warning here.
1491 ALOGW("%s: received notify message in error state.", __FUNCTION__);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07001492 }
Yin-Chia Yeh657c1872017-07-18 18:09:57 -07001493
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001494 for (const auto& msg : msgs) {
1495 notify(msg);
1496 }
1497 return hardware::Void();
1498}
1499
1500void Camera3Device::notify(
1501 const hardware::camera::device::V3_2::NotifyMsg& msg) {
1502
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001503 camera3_notify_msg m;
1504 switch (msg.type) {
1505 case MsgType::ERROR:
1506 m.type = CAMERA3_MSG_ERROR;
1507 m.message.error.frame_number = msg.msg.error.frameNumber;
1508 if (msg.msg.error.errorStreamId >= 0) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001509 sp<Camera3StreamInterface> stream = mOutputStreams.get(msg.msg.error.errorStreamId);
1510 if (stream == nullptr) {
1511 ALOGE("%s: Frame %d: Invalid error stream id %d", __FUNCTION__,
1512 m.message.error.frame_number, msg.msg.error.errorStreamId);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08001513 return;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001514 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001515 m.message.error.error_stream = stream->asHalStream();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001516 } else {
1517 m.message.error.error_stream = nullptr;
1518 }
1519 switch (msg.msg.error.errorCode) {
1520 case ErrorCode::ERROR_DEVICE:
1521 m.message.error.error_code = CAMERA3_MSG_ERROR_DEVICE;
1522 break;
1523 case ErrorCode::ERROR_REQUEST:
1524 m.message.error.error_code = CAMERA3_MSG_ERROR_REQUEST;
1525 break;
1526 case ErrorCode::ERROR_RESULT:
1527 m.message.error.error_code = CAMERA3_MSG_ERROR_RESULT;
1528 break;
1529 case ErrorCode::ERROR_BUFFER:
1530 m.message.error.error_code = CAMERA3_MSG_ERROR_BUFFER;
1531 break;
1532 }
1533 break;
1534 case MsgType::SHUTTER:
1535 m.type = CAMERA3_MSG_SHUTTER;
1536 m.message.shutter.frame_number = msg.msg.shutter.frameNumber;
1537 m.message.shutter.timestamp = msg.msg.shutter.timestamp;
1538 break;
1539 }
1540 notify(&m);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001541}
1542
Emilian Peevaebbe412018-01-15 13:53:24 +00001543status_t Camera3Device::captureList(const List<const PhysicalCameraSettingsList> &requestsList,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001544 const std::list<const SurfaceMap> &surfaceMaps,
Jianing Weicb0652e2014-03-12 18:29:36 -07001545 int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001546 ATRACE_CALL();
1547
Emilian Peevaebbe412018-01-15 13:53:24 +00001548 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/false, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001549}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001550
Jianing Weicb0652e2014-03-12 18:29:36 -07001551status_t Camera3Device::setStreamingRequest(const CameraMetadata &request,
1552 int64_t* /*lastFrameNumber*/) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001553 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001554
Emilian Peevaebbe412018-01-15 13:53:24 +00001555 List<const PhysicalCameraSettingsList> requestsList;
Shuzhen Wang0129d522016-10-30 22:43:41 -07001556 std::list<const SurfaceMap> surfaceMaps;
Emilian Peevaebbe412018-01-15 13:53:24 +00001557 convertToRequestList(requestsList, surfaceMaps, request);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001558
Emilian Peevaebbe412018-01-15 13:53:24 +00001559 return setStreamingRequestList(requestsList, /*surfaceMap*/surfaceMaps,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001560 /*lastFrameNumber*/NULL);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001561}
1562
Emilian Peevaebbe412018-01-15 13:53:24 +00001563status_t Camera3Device::setStreamingRequestList(
1564 const List<const PhysicalCameraSettingsList> &requestsList,
1565 const std::list<const SurfaceMap> &surfaceMaps, int64_t *lastFrameNumber) {
Jianing Wei90e59c92014-03-12 18:29:36 -07001566 ATRACE_CALL();
1567
Emilian Peevaebbe412018-01-15 13:53:24 +00001568 return submitRequestsHelper(requestsList, surfaceMaps, /*repeating*/true, lastFrameNumber);
Jianing Wei90e59c92014-03-12 18:29:36 -07001569}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001570
1571sp<Camera3Device::CaptureRequest> Camera3Device::setUpRequestLocked(
Emilian Peevaebbe412018-01-15 13:53:24 +00001572 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001573 status_t res;
1574
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001575 if (mStatus == STATUS_UNCONFIGURED || mNeedConfig) {
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08001576 // This point should only be reached via API1 (API2 must explicitly call configureStreams)
1577 // so unilaterally select normal operating mode.
Emilian Peevaebbe412018-01-15 13:53:24 +00001578 res = filterParamsAndConfigureLocked(request.begin()->metadata,
1579 CAMERA3_STREAM_CONFIGURATION_NORMAL_MODE);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001580 // Stream configuration failed. Client might try other configuraitons.
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001581 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001582 CLOGE("Can't set up streams: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001583 return NULL;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07001584 } else if (mStatus == STATUS_UNCONFIGURED) {
1585 // Stream configuration successfully configure to empty stream configuration.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001586 CLOGE("No streams configured");
1587 return NULL;
1588 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001589 }
1590
Shuzhen Wang0129d522016-10-30 22:43:41 -07001591 sp<CaptureRequest> newRequest = createCaptureRequest(request, surfaceMap);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001592 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001593}
1594
Jianing Weicb0652e2014-03-12 18:29:36 -07001595status_t Camera3Device::clearStreamingRequest(int64_t *lastFrameNumber) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001596 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001597 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001598 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001599
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001600 switch (mStatus) {
1601 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001602 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001603 return INVALID_OPERATION;
1604 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001605 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001606 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001607 case STATUS_UNCONFIGURED:
1608 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001609 case STATUS_ACTIVE:
1610 // OK
1611 break;
1612 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001613 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001614 return INVALID_OPERATION;
1615 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001616 ALOGV("Camera %s: Clearing repeating request", mId.string());
Jianing Weicb0652e2014-03-12 18:29:36 -07001617
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07001618 return mRequestThread->clearRepeatingRequests(lastFrameNumber);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001619}
1620
1621status_t Camera3Device::waitUntilRequestReceived(int32_t requestId, nsecs_t timeout) {
1622 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001623 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001624
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07001625 return mRequestThread->waitUntilRequestProcessed(requestId, timeout);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001626}
1627
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001628status_t Camera3Device::createInputStream(
1629 uint32_t width, uint32_t height, int format, int *id) {
1630 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001631 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001632 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001633 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001634 ALOGV("Camera %s: Creating new input stream %d: %d x %d, format %d",
1635 mId.string(), mNextStreamId, width, height, format);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001636
1637 status_t res;
1638 bool wasActive = false;
1639
1640 switch (mStatus) {
1641 case STATUS_ERROR:
1642 ALOGE("%s: Device has encountered a serious error", __FUNCTION__);
1643 return INVALID_OPERATION;
1644 case STATUS_UNINITIALIZED:
1645 ALOGE("%s: Device not initialized", __FUNCTION__);
1646 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001647 case STATUS_UNCONFIGURED:
1648 case STATUS_CONFIGURED:
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001649 // OK
1650 break;
1651 case STATUS_ACTIVE:
1652 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001653 res = internalPauseAndWaitLocked(maxExpectedDuration);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001654 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001655 SET_ERR_L("Can't pause captures to reconfigure streams!");
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001656 return res;
1657 }
1658 wasActive = true;
1659 break;
1660 default:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001661 SET_ERR_L("%s: Unexpected status: %d", mStatus);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001662 return INVALID_OPERATION;
1663 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001664 assert(mStatus != STATUS_ACTIVE);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001665
1666 if (mInputStream != 0) {
1667 ALOGE("%s: Cannot create more than 1 input stream", __FUNCTION__);
1668 return INVALID_OPERATION;
1669 }
1670
1671 sp<Camera3InputStream> newStream = new Camera3InputStream(mNextStreamId,
1672 width, height, format);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001673 newStream->setStatusTracker(mStatusTracker);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001674
1675 mInputStream = newStream;
1676
1677 *id = mNextStreamId++;
1678
1679 // Continue captures if active at start
1680 if (wasActive) {
1681 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001682 // Reuse current operating mode and session parameters for new stream config
1683 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001684 if (res != OK) {
1685 ALOGE("%s: Can't reconfigure device for new stream %d: %s (%d)",
1686 __FUNCTION__, mNextStreamId, strerror(-res), res);
1687 return res;
1688 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001689 internalResumeLocked();
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001690 }
1691
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001692 ALOGV("Camera %s: Created input stream", mId.string());
Igor Murashkin5a269fa2013-04-15 14:59:22 -07001693 return OK;
1694}
1695
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001696status_t Camera3Device::StreamSet::add(
1697 int streamId, sp<camera3::Camera3OutputStreamInterface> stream) {
1698 if (stream == nullptr) {
1699 ALOGE("%s: cannot add null stream", __FUNCTION__);
1700 return BAD_VALUE;
1701 }
1702 std::lock_guard<std::mutex> lock(mLock);
1703 return mData.add(streamId, stream);
1704}
1705
1706ssize_t Camera3Device::StreamSet::remove(int streamId) {
1707 std::lock_guard<std::mutex> lock(mLock);
1708 return mData.removeItem(streamId);
1709}
1710
1711sp<camera3::Camera3OutputStreamInterface>
1712Camera3Device::StreamSet::get(int streamId) {
1713 std::lock_guard<std::mutex> lock(mLock);
1714 ssize_t idx = mData.indexOfKey(streamId);
1715 if (idx == NAME_NOT_FOUND) {
1716 return nullptr;
1717 }
1718 return mData.editValueAt(idx);
1719}
1720
1721sp<camera3::Camera3OutputStreamInterface>
1722Camera3Device::StreamSet::operator[] (size_t index) {
1723 std::lock_guard<std::mutex> lock(mLock);
1724 return mData.editValueAt(index);
1725}
1726
1727size_t Camera3Device::StreamSet::size() const {
1728 std::lock_guard<std::mutex> lock(mLock);
1729 return mData.size();
1730}
1731
1732void Camera3Device::StreamSet::clear() {
1733 std::lock_guard<std::mutex> lock(mLock);
1734 return mData.clear();
1735}
1736
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07001737std::vector<int> Camera3Device::StreamSet::getStreamIds() {
1738 std::lock_guard<std::mutex> lock(mLock);
1739 std::vector<int> streamIds(mData.size());
1740 for (size_t i = 0; i < mData.size(); i++) {
1741 streamIds[i] = mData.keyAt(i);
1742 }
1743 return streamIds;
1744}
1745
Eino-Ville Talvala727d1722015-06-09 13:44:19 -07001746status_t Camera3Device::createStream(sp<Surface> consumer,
Shuzhen Wang0129d522016-10-30 22:43:41 -07001747 uint32_t width, uint32_t height, int format,
1748 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001749 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001750 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001751 ATRACE_CALL();
1752
1753 if (consumer == nullptr) {
1754 ALOGE("%s: consumer must not be null", __FUNCTION__);
1755 return BAD_VALUE;
1756 }
1757
1758 std::vector<sp<Surface>> consumers;
1759 consumers.push_back(consumer);
1760
1761 return createStream(consumers, /*hasDeferredConsumer*/ false, width, height,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001762 format, dataSpace, rotation, id, physicalCameraId, surfaceIds, streamSetId,
1763 isShared, consumerUsage);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001764}
1765
1766status_t Camera3Device::createStream(const std::vector<sp<Surface>>& consumers,
1767 bool hasDeferredConsumer, uint32_t width, uint32_t height, int format,
1768 android_dataspace dataSpace, camera3_stream_rotation_t rotation, int *id,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001769 const String8& physicalCameraId,
Emilian Peev40ead602017-09-26 15:46:36 +01001770 std::vector<int> *surfaceIds, int streamSetId, bool isShared, uint64_t consumerUsage) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001771 ATRACE_CALL();
Emilian Peev40ead602017-09-26 15:46:36 +01001772
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001773 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001774 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001775 Mutex::Autolock l(mLock);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001776 ALOGV("Camera %s: Creating new stream %d: %d x %d, format %d, dataspace %d rotation %d"
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001777 " consumer usage %" PRIu64 ", isShared %d, physicalCameraId %s", mId.string(),
1778 mNextStreamId, width, height, format, dataSpace, rotation, consumerUsage, isShared,
1779 physicalCameraId.string());
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001780
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001781 status_t res;
1782 bool wasActive = false;
1783
1784 switch (mStatus) {
1785 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001786 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001787 return INVALID_OPERATION;
1788 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001789 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001790 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001791 case STATUS_UNCONFIGURED:
1792 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001793 // OK
1794 break;
1795 case STATUS_ACTIVE:
1796 ALOGV("%s: Stopping activity to reconfigure streams", __FUNCTION__);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07001797 res = internalPauseAndWaitLocked(maxExpectedDuration);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001798 if (res != OK) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001799 SET_ERR_L("Can't pause captures to reconfigure streams!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001800 return res;
1801 }
1802 wasActive = true;
1803 break;
1804 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001805 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001806 return INVALID_OPERATION;
1807 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001808 assert(mStatus != STATUS_ACTIVE);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001809
1810 sp<Camera3OutputStream> newStream;
Zhijun He5d677d12016-05-29 16:52:39 -07001811
Shuzhen Wang0129d522016-10-30 22:43:41 -07001812 if (consumers.size() == 0 && !hasDeferredConsumer) {
1813 ALOGE("%s: Number of consumers cannot be smaller than 1", __FUNCTION__);
1814 return BAD_VALUE;
1815 }
Zhijun He5d677d12016-05-29 16:52:39 -07001816
Shuzhen Wang0129d522016-10-30 22:43:41 -07001817 if (hasDeferredConsumer && format != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Zhijun He5d677d12016-05-29 16:52:39 -07001818 ALOGE("Deferred consumer stream creation only support IMPLEMENTATION_DEFINED format");
1819 return BAD_VALUE;
1820 }
1821
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001822 if (format == HAL_PIXEL_FORMAT_BLOB) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001823 ssize_t blobBufferSize;
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001824 if (dataSpace == HAL_DATASPACE_DEPTH) {
Eino-Ville Talvala95a1d0f2015-08-11 15:08:53 -07001825 blobBufferSize = getPointCloudBufferSize();
1826 if (blobBufferSize <= 0) {
1827 SET_ERR_L("Invalid point cloud buffer size %zd", blobBufferSize);
1828 return BAD_VALUE;
1829 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08001830 } else if (dataSpace == static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
1831 blobBufferSize = width * height;
1832 } else {
1833 blobBufferSize = getJpegBufferSize(width, height);
1834 if (blobBufferSize <= 0) {
1835 SET_ERR_L("Invalid jpeg buffer size %zd", blobBufferSize);
1836 return BAD_VALUE;
1837 }
Zhijun Hef7da0962014-04-24 13:27:56 -07001838 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001839 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001840 width, height, blobBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001841 mTimestampOffset, physicalCameraId, streamSetId);
Yin-Chia Yehe9154ce2015-12-07 14:38:04 -08001842 } else if (format == HAL_PIXEL_FORMAT_RAW_OPAQUE) {
1843 ssize_t rawOpaqueBufferSize = getRawOpaqueBufferSize(width, height);
1844 if (rawOpaqueBufferSize <= 0) {
1845 SET_ERR_L("Invalid RAW opaque buffer size %zd", rawOpaqueBufferSize);
1846 return BAD_VALUE;
1847 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07001848 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001849 width, height, rawOpaqueBufferSize, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001850 mTimestampOffset, physicalCameraId, streamSetId);
Shuzhen Wang758c2152017-01-10 18:26:18 -08001851 } else if (isShared) {
1852 newStream = new Camera3SharedOutputStream(mNextStreamId, consumers,
1853 width, height, format, consumerUsage, dataSpace, rotation,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07001854 mTimestampOffset, physicalCameraId, streamSetId,
1855 mUseHalBufManager);
Shuzhen Wang0129d522016-10-30 22:43:41 -07001856 } else if (consumers.size() == 0 && hasDeferredConsumer) {
Zhijun He5d677d12016-05-29 16:52:39 -07001857 newStream = new Camera3OutputStream(mNextStreamId,
1858 width, height, format, consumerUsage, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001859 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001860 } else {
Shuzhen Wang0129d522016-10-30 22:43:41 -07001861 newStream = new Camera3OutputStream(mNextStreamId, consumers[0],
Shuzhen Wangc28dccc2016-02-11 23:48:46 -08001862 width, height, format, dataSpace, rotation,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08001863 mTimestampOffset, physicalCameraId, streamSetId);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001864 }
Emilian Peev40ead602017-09-26 15:46:36 +01001865
1866 size_t consumerCount = consumers.size();
1867 for (size_t i = 0; i < consumerCount; i++) {
1868 int id = newStream->getSurfaceId(consumers[i]);
1869 if (id < 0) {
1870 SET_ERR_L("Invalid surface id");
1871 return BAD_VALUE;
1872 }
1873 if (surfaceIds != nullptr) {
1874 surfaceIds->push_back(id);
1875 }
1876 }
1877
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001878 newStream->setStatusTracker(mStatusTracker);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001879
Emilian Peev08dd2452017-04-06 16:55:14 +01001880 newStream->setBufferManager(mBufferManager);
Zhijun He125684a2015-12-26 15:07:30 -08001881
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001882 res = mOutputStreams.add(mNextStreamId, newStream);
1883 if (res < 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001884 SET_ERR_L("Can't add new stream to set: %s (%d)", strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001885 return res;
1886 }
1887
1888 *id = mNextStreamId++;
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07001889 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001890
1891 // Continue captures if active at start
1892 if (wasActive) {
1893 ALOGV("%s: Restarting activity to reconfigure streams", __FUNCTION__);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01001894 // Reuse current operating mode and session parameters for new stream config
1895 res = configureStreamsLocked(mOperatingMode, mSessionParams);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001896 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001897 CLOGE("Can't reconfigure device for new stream %d: %s (%d)",
1898 mNextStreamId, strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001899 return res;
1900 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001901 internalResumeLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001902 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001903 ALOGV("Camera %s: Created new stream", mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001904 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001905}
1906
Emilian Peev710c1422017-08-30 11:19:38 +01001907status_t Camera3Device::getStreamInfo(int id, StreamInfo *streamInfo) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001908 ATRACE_CALL();
Emilian Peev710c1422017-08-30 11:19:38 +01001909 if (nullptr == streamInfo) {
1910 return BAD_VALUE;
1911 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001912 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001913 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001914
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001915 switch (mStatus) {
1916 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001917 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001918 return INVALID_OPERATION;
1919 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001920 CLOGE("Device not initialized!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001921 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001922 case STATUS_UNCONFIGURED:
1923 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001924 case STATUS_ACTIVE:
1925 // OK
1926 break;
1927 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001928 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001929 return INVALID_OPERATION;
1930 }
1931
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001932 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
1933 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001934 CLOGE("Stream %d is unknown", id);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001935 return BAD_VALUE;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001936 }
1937
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001938 streamInfo->width = stream->getWidth();
1939 streamInfo->height = stream->getHeight();
1940 streamInfo->format = stream->getFormat();
1941 streamInfo->dataSpace = stream->getDataSpace();
1942 streamInfo->formatOverridden = stream->isFormatOverridden();
1943 streamInfo->originalFormat = stream->getOriginalFormat();
1944 streamInfo->dataSpaceOverridden = stream->isDataSpaceOverridden();
1945 streamInfo->originalDataSpace = stream->getOriginalDataSpace();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001946 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001947}
1948
1949status_t Camera3Device::setStreamTransform(int id,
1950 int transform) {
1951 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001952 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001953 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001954
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001955 switch (mStatus) {
1956 case STATUS_ERROR:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001957 CLOGE("Device has encountered a serious error");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001958 return INVALID_OPERATION;
1959 case STATUS_UNINITIALIZED:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001960 CLOGE("Device not initialized");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001961 return INVALID_OPERATION;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001962 case STATUS_UNCONFIGURED:
1963 case STATUS_CONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001964 case STATUS_ACTIVE:
1965 // OK
1966 break;
1967 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07001968 SET_ERR_L("Unexpected status: %d", mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001969 return INVALID_OPERATION;
1970 }
1971
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001972 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(id);
1973 if (stream == nullptr) {
1974 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001975 return BAD_VALUE;
1976 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07001977 return stream->setTransform(transform);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001978}
1979
1980status_t Camera3Device::deleteStream(int id) {
1981 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001982 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001983 Mutex::Autolock l(mLock);
1984 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08001985
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08001986 ALOGV("%s: Camera %s: Deleting stream %d", __FUNCTION__, mId.string(), id);
Igor Murashkine2172be2013-05-28 15:31:39 -07001987
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001988 // CameraDevice semantics require device to already be idle before
1989 // deleteStream is called, unlike for createStream.
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07001990 if (mStatus == STATUS_ACTIVE) {
Yin-Chia Yeh693047d2018-03-08 12:14:19 -08001991 ALOGW("%s: Camera %s: Device not idle", __FUNCTION__, mId.string());
Igor Murashkin52827132013-05-13 14:53:44 -07001992 return -EBUSY;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08001993 }
1994
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07001995 if (mStatus == STATUS_ERROR) {
1996 ALOGW("%s: Camera %s: deleteStream not allowed in ERROR state",
1997 __FUNCTION__, mId.string());
1998 return -EBUSY;
1999 }
2000
Igor Murashkin2fba5842013-04-22 14:03:54 -07002001 sp<Camera3StreamInterface> deletedStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002002 sp<Camera3StreamInterface> stream = mOutputStreams.get(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002003 if (mInputStream != NULL && id == mInputStream->getId()) {
2004 deletedStream = mInputStream;
2005 mInputStream.clear();
2006 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002007 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002008 CLOGE("Stream %d does not exist", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002009 return BAD_VALUE;
2010 }
Zhijun He5f446352014-01-22 09:49:33 -08002011 }
2012
2013 // Delete output stream or the output part of a bi-directional stream.
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002014 if (stream != nullptr) {
2015 deletedStream = stream;
2016 mOutputStreams.remove(id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002017 }
2018
2019 // Free up the stream endpoint so that it can be used by some other stream
2020 res = deletedStream->disconnect();
2021 if (res != OK) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002022 SET_ERR_L("Can't disconnect deleted stream %d", id);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002023 // fall through since we want to still list the stream as deleted.
2024 }
2025 mDeletedStreams.add(deletedStream);
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002026 mNeedConfig = true;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002027
2028 return res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002029}
2030
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002031status_t Camera3Device::configureStreams(const CameraMetadata& sessionParams, int operatingMode) {
Igor Murashkine2d167e2014-08-19 16:19:59 -07002032 ATRACE_CALL();
2033 ALOGV("%s: E", __FUNCTION__);
2034
2035 Mutex::Autolock il(mInterfaceLock);
2036 Mutex::Autolock l(mLock);
Chien-Yu Chen17338fc2015-06-18 16:30:12 -07002037
Emilian Peev811d2952018-05-25 11:08:40 +01002038 // In case the client doesn't include any session parameter, try a
2039 // speculative configuration using the values from the last cached
2040 // default request.
2041 if (sessionParams.isEmpty() &&
2042 ((mLastTemplateId > 0) && (mLastTemplateId < CAMERA3_TEMPLATE_COUNT)) &&
2043 (!mRequestTemplateCache[mLastTemplateId].isEmpty())) {
2044 ALOGV("%s: Speculative session param configuration with template id: %d", __func__,
2045 mLastTemplateId);
2046 return filterParamsAndConfigureLocked(mRequestTemplateCache[mLastTemplateId],
2047 operatingMode);
2048 }
2049
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002050 return filterParamsAndConfigureLocked(sessionParams, operatingMode);
2051}
2052
2053status_t Camera3Device::filterParamsAndConfigureLocked(const CameraMetadata& sessionParams,
2054 int operatingMode) {
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002055 //Filter out any incoming session parameters
2056 const CameraMetadata params(sessionParams);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002057 camera_metadata_entry_t availableSessionKeys = mDeviceInfo.find(
2058 ANDROID_REQUEST_AVAILABLE_SESSION_KEYS);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002059 CameraMetadata filteredParams(availableSessionKeys.count);
2060 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
2061 filteredParams.getAndLock());
2062 set_camera_metadata_vendor_id(meta, mVendorTagId);
2063 filteredParams.unlock(meta);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002064 if (availableSessionKeys.count > 0) {
2065 for (size_t i = 0; i < availableSessionKeys.count; i++) {
2066 camera_metadata_ro_entry entry = params.find(
2067 availableSessionKeys.data.i32[i]);
2068 if (entry.count > 0) {
2069 filteredParams.update(entry);
2070 }
2071 }
2072 }
2073
2074 return configureStreamsLocked(operatingMode, filteredParams);
Igor Murashkine2d167e2014-08-19 16:19:59 -07002075}
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002076
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002077status_t Camera3Device::getInputBufferProducer(
2078 sp<IGraphicBufferProducer> *producer) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002079 ATRACE_CALL();
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002080 Mutex::Autolock il(mInterfaceLock);
2081 Mutex::Autolock l(mLock);
2082
2083 if (producer == NULL) {
2084 return BAD_VALUE;
2085 } else if (mInputStream == NULL) {
2086 return INVALID_OPERATION;
2087 }
2088
2089 return mInputStream->getInputBufferProducer(producer);
2090}
2091
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002092status_t Camera3Device::createDefaultRequest(int templateId,
2093 CameraMetadata *request) {
2094 ATRACE_CALL();
Alex Rayfe7e0c62013-05-30 00:12:13 -07002095 ALOGV("%s: for template %d", __FUNCTION__, templateId);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002096
2097 if (templateId <= 0 || templateId >= CAMERA3_TEMPLATE_COUNT) {
2098 android_errorWriteWithInfoLog(CameraService::SN_EVENT_LOG_ID, "26866110",
Jayant Chowdhary12361932018-08-27 14:46:13 -07002099 CameraThreadState::getCallingUid(), nullptr, 0);
Chien-Yu Chen9cd14022016-03-09 12:21:01 -08002100 return BAD_VALUE;
2101 }
2102
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002103 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002104
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002105 {
2106 Mutex::Autolock l(mLock);
2107 switch (mStatus) {
2108 case STATUS_ERROR:
2109 CLOGE("Device has encountered a serious error");
2110 return INVALID_OPERATION;
2111 case STATUS_UNINITIALIZED:
2112 CLOGE("Device is not initialized!");
2113 return INVALID_OPERATION;
2114 case STATUS_UNCONFIGURED:
2115 case STATUS_CONFIGURED:
2116 case STATUS_ACTIVE:
2117 // OK
2118 break;
2119 default:
2120 SET_ERR_L("Unexpected status: %d", mStatus);
2121 return INVALID_OPERATION;
2122 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002123
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002124 if (!mRequestTemplateCache[templateId].isEmpty()) {
2125 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002126 mLastTemplateId = templateId;
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002127 return OK;
2128 }
Zhijun Hea1530f12014-09-14 12:44:20 -07002129 }
2130
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002131 camera_metadata_t *rawRequest;
2132 status_t res = mInterface->constructDefaultRequestSettings(
2133 (camera3_request_template_t) templateId, &rawRequest);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002134
2135 {
2136 Mutex::Autolock l(mLock);
2137 if (res == BAD_VALUE) {
2138 ALOGI("%s: template %d is not supported on this camera device",
2139 __FUNCTION__, templateId);
2140 return res;
2141 } else if (res != OK) {
2142 CLOGE("Unable to construct request template %d: %s (%d)",
2143 templateId, strerror(-res), res);
2144 return res;
2145 }
2146
2147 set_camera_metadata_vendor_id(rawRequest, mVendorTagId);
2148 mRequestTemplateCache[templateId].acquire(rawRequest);
2149
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08002150 // Override the template request with zoomRatioMapper
2151 res = mZoomRatioMappers[mId.c_str()].initZoomRatioInTemplate(
2152 &mRequestTemplateCache[templateId]);
2153 if (res != OK) {
2154 CLOGE("Failed to update zoom ratio for template %d: %s (%d)",
2155 templateId, strerror(-res), res);
2156 return res;
2157 }
2158
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002159 *request = mRequestTemplateCache[templateId];
Emilian Peev811d2952018-05-25 11:08:40 +01002160 mLastTemplateId = templateId;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002161 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002162 return OK;
2163}
2164
2165status_t Camera3Device::waitUntilDrained() {
2166 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002167 Mutex::Autolock il(mInterfaceLock);
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002168 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002169 Mutex::Autolock l(mLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002170
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002171 return waitUntilDrainedLocked(maxExpectedDuration);
Zhijun He69a37482014-03-23 18:44:49 -07002172}
2173
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002174status_t Camera3Device::waitUntilDrainedLocked(nsecs_t maxExpectedDuration) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002175 switch (mStatus) {
2176 case STATUS_UNINITIALIZED:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002177 case STATUS_UNCONFIGURED:
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002178 ALOGV("%s: Already idle", __FUNCTION__);
2179 return OK;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002180 case STATUS_CONFIGURED:
2181 // To avoid race conditions, check with tracker to be sure
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002182 case STATUS_ERROR:
2183 case STATUS_ACTIVE:
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002184 // Need to verify shut down
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002185 break;
2186 default:
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002187 SET_ERR_L("Unexpected status: %d",mStatus);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002188 return INVALID_OPERATION;
2189 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002190 ALOGV("%s: Camera %s: Waiting until idle (%" PRIi64 "ns)", __FUNCTION__, mId.string(),
2191 maxExpectedDuration);
2192 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvala9c8a0912014-09-14 14:52:19 -07002193 if (res != OK) {
2194 SET_ERR_L("Error waiting for HAL to drain: %s (%d)", strerror(-res),
2195 res);
2196 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002197 return res;
2198}
2199
Ruben Brunk183f0562015-08-12 12:55:02 -07002200
2201void Camera3Device::internalUpdateStatusLocked(Status status) {
2202 mStatus = status;
2203 mRecentStatusUpdates.add(mStatus);
2204 mStatusChanged.broadcast();
2205}
2206
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002207void Camera3Device::pauseStateNotify(bool enable) {
2208 Mutex::Autolock il(mInterfaceLock);
2209 Mutex::Autolock l(mLock);
2210
2211 mPauseStateNotify = enable;
2212}
2213
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002214// Pause to reconfigure
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07002215status_t Camera3Device::internalPauseAndWaitLocked(nsecs_t maxExpectedDuration) {
Emilian Peeve86358b2019-02-15 13:51:39 -08002216 if (mRequestThread.get() != nullptr) {
2217 mRequestThread->setPaused(true);
2218 } else {
2219 return NO_INIT;
2220 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002221
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002222 ALOGV("%s: Camera %s: Internal wait until idle (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2223 maxExpectedDuration);
2224 status_t res = waitUntilStateThenRelock(/*active*/ false, maxExpectedDuration);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002225 if (res != OK) {
2226 SET_ERR_L("Can't idle device in %f seconds!",
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07002227 maxExpectedDuration/1e9);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002228 }
2229
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002230 return res;
2231}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002232
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002233// Resume after internalPauseAndWaitLocked
2234status_t Camera3Device::internalResumeLocked() {
2235 status_t res;
2236
2237 mRequestThread->setPaused(false);
2238
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002239 ALOGV("%s: Camera %s: Internal wait until active (% " PRIi64 " ns)", __FUNCTION__, mId.string(),
2240 kActiveTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002241 res = waitUntilStateThenRelock(/*active*/ true, kActiveTimeout);
2242 if (res != OK) {
2243 SET_ERR_L("Can't transition to active in %f seconds!",
2244 kActiveTimeout/1e9);
2245 }
2246 mPauseStateNotify = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002247 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002248}
2249
Ruben Brunk183f0562015-08-12 12:55:02 -07002250status_t Camera3Device::waitUntilStateThenRelock(bool active, nsecs_t timeout) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002251 status_t res = OK;
Ruben Brunk183f0562015-08-12 12:55:02 -07002252
2253 size_t startIndex = 0;
2254 if (mStatusWaiters == 0) {
2255 // Clear the list of recent statuses if there are no existing threads waiting on updates to
2256 // this status list
2257 mRecentStatusUpdates.clear();
2258 } else {
2259 // If other threads are waiting on updates to this status list, set the position of the
2260 // first element that this list will check rather than clearing the list.
2261 startIndex = mRecentStatusUpdates.size();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002262 }
2263
Ruben Brunk183f0562015-08-12 12:55:02 -07002264 mStatusWaiters++;
2265
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002266 if (!active && mUseHalBufManager) {
2267 auto streamIds = mOutputStreams.getStreamIds();
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08002268 if (mStatus == STATUS_ACTIVE) {
2269 mRequestThread->signalPipelineDrain(streamIds);
2270 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07002271 mRequestBufferSM.onWaitUntilIdle();
2272 }
2273
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002274 bool stateSeen = false;
2275 do {
Ruben Brunk183f0562015-08-12 12:55:02 -07002276 if (active == (mStatus == STATUS_ACTIVE)) {
2277 // Desired state is current
2278 break;
2279 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002280
2281 res = mStatusChanged.waitRelative(mLock, timeout);
2282 if (res != OK) break;
2283
Ruben Brunk183f0562015-08-12 12:55:02 -07002284 // This is impossible, but if not, could result in subtle deadlocks and invalid state
2285 // transitions.
2286 LOG_ALWAYS_FATAL_IF(startIndex > mRecentStatusUpdates.size(),
2287 "%s: Skipping status updates in Camera3Device, may result in deadlock.",
2288 __FUNCTION__);
2289
2290 // Encountered desired state since we began waiting
2291 for (size_t i = startIndex; i < mRecentStatusUpdates.size(); i++) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002292 if (active == (mRecentStatusUpdates[i] == STATUS_ACTIVE) ) {
2293 stateSeen = true;
2294 break;
2295 }
2296 }
2297 } while (!stateSeen);
2298
Ruben Brunk183f0562015-08-12 12:55:02 -07002299 mStatusWaiters--;
2300
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002301 return res;
2302}
2303
2304
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002305status_t Camera3Device::setNotifyCallback(wp<NotificationListener> listener) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002306 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002307 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002308
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002309 if (listener != NULL && mListener != NULL) {
2310 ALOGW("%s: Replacing old callback listener", __FUNCTION__);
2311 }
2312 mListener = listener;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002313 mRequestThread->setNotificationListener(listener);
2314 mPreparerThread->setNotificationListener(listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002315
2316 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002317}
2318
Eino-Ville Talvala46910bd2013-07-18 19:15:17 -07002319bool Camera3Device::willNotify3A() {
2320 return false;
2321}
2322
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002323status_t Camera3Device::waitForNextFrame(nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002324 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002325 status_t res;
2326 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002327
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002328 while (mResultQueue.empty()) {
2329 res = mResultSignal.waitRelative(mOutputLock, timeout);
2330 if (res == TIMED_OUT) {
2331 return res;
2332 } else if (res != OK) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002333 ALOGW("%s: Camera %s: No frame in %" PRId64 " ns: %s (%d)",
2334 __FUNCTION__, mId.string(), timeout, strerror(-res), res);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002335 return res;
2336 }
2337 }
2338 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002339}
2340
Jianing Weicb0652e2014-03-12 18:29:36 -07002341status_t Camera3Device::getNextResult(CaptureResult *frame) {
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002342 ATRACE_CALL();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002343 Mutex::Autolock l(mOutputLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002344
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002345 if (mResultQueue.empty()) {
2346 return NOT_ENOUGH_DATA;
2347 }
2348
Jianing Weicb0652e2014-03-12 18:29:36 -07002349 if (frame == NULL) {
2350 ALOGE("%s: argument cannot be NULL", __FUNCTION__);
2351 return BAD_VALUE;
2352 }
2353
2354 CaptureResult &result = *(mResultQueue.begin());
2355 frame->mResultExtras = result.mResultExtras;
2356 frame->mMetadata.acquire(result.mMetadata);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08002357 frame->mPhysicalMetadatas = std::move(result.mPhysicalMetadatas);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07002358 mResultQueue.erase(mResultQueue.begin());
2359
2360 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002361}
2362
2363status_t Camera3Device::triggerAutofocus(uint32_t id) {
2364 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002365 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002366
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002367 ALOGV("%s: Triggering autofocus, id %d", __FUNCTION__, id);
2368 // Mix-in this trigger into the next request and only the next request.
2369 RequestTrigger trigger[] = {
2370 {
2371 ANDROID_CONTROL_AF_TRIGGER,
2372 ANDROID_CONTROL_AF_TRIGGER_START
2373 },
2374 {
2375 ANDROID_CONTROL_AF_TRIGGER_ID,
2376 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002377 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002378 };
2379
2380 return mRequestThread->queueTrigger(trigger,
2381 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002382}
2383
2384status_t Camera3Device::triggerCancelAutofocus(uint32_t id) {
2385 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002386 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002387
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002388 ALOGV("%s: Triggering cancel autofocus, id %d", __FUNCTION__, id);
2389 // Mix-in this trigger into the next request and only the next request.
2390 RequestTrigger trigger[] = {
2391 {
2392 ANDROID_CONTROL_AF_TRIGGER,
2393 ANDROID_CONTROL_AF_TRIGGER_CANCEL
2394 },
2395 {
2396 ANDROID_CONTROL_AF_TRIGGER_ID,
2397 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002398 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002399 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002400
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002401 return mRequestThread->queueTrigger(trigger,
2402 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002403}
2404
2405status_t Camera3Device::triggerPrecaptureMetering(uint32_t id) {
2406 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002407 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002408
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002409 ALOGV("%s: Triggering precapture metering, id %d", __FUNCTION__, id);
2410 // Mix-in this trigger into the next request and only the next request.
2411 RequestTrigger trigger[] = {
2412 {
2413 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER,
2414 ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_START
2415 },
2416 {
2417 ANDROID_CONTROL_AE_PRECAPTURE_ID,
2418 static_cast<int32_t>(id)
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07002419 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002420 };
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002421
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07002422 return mRequestThread->queueTrigger(trigger,
2423 sizeof(trigger)/sizeof(trigger[0]));
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002424}
2425
Jianing Weicb0652e2014-03-12 18:29:36 -07002426status_t Camera3Device::flush(int64_t *frameNumber) {
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002427 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002428 ALOGV("%s: Camera %s: Flushing all requests", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002429 Mutex::Autolock il(mInterfaceLock);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002430
Zhijun He7ef20392014-04-21 16:04:17 -07002431 {
2432 Mutex::Autolock l(mLock);
Emilian Peeved2ebe42018-09-25 16:59:09 +01002433
2434 // b/116514106 "disconnect()" can get called twice for the same device. The
2435 // camera device will not be initialized during the second run.
2436 if (mStatus == STATUS_UNINITIALIZED) {
2437 return OK;
2438 }
2439
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002440 mRequestThread->clear(/*out*/frameNumber);
Zhijun He7ef20392014-04-21 16:04:17 -07002441 }
2442
Emilian Peev08dd2452017-04-06 16:55:14 +01002443 return mRequestThread->flush();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07002444}
2445
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002446status_t Camera3Device::prepare(int streamId) {
Ruben Brunkc78ac262015-08-13 17:58:46 -07002447 return prepare(camera3::Camera3StreamInterface::ALLOCATE_PIPELINE_MAX, streamId);
2448}
2449
2450status_t Camera3Device::prepare(int maxCount, int streamId) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002451 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002452 ALOGV("%s: Camera %s: Preparing stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002453 Mutex::Autolock il(mInterfaceLock);
2454 Mutex::Autolock l(mLock);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002455
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002456 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2457 if (stream == nullptr) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002458 CLOGE("Stream %d does not exist", streamId);
2459 return BAD_VALUE;
2460 }
2461
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002462 if (stream->isUnpreparable() || stream->hasOutstandingBuffers() ) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002463 CLOGE("Stream %d has already been a request target", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002464 return BAD_VALUE;
2465 }
2466
2467 if (mRequestThread->isStreamPending(stream)) {
Eino-Ville Talvala261394e2015-05-13 14:28:38 -07002468 CLOGE("Stream %d is already a target in a pending request", streamId);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002469 return BAD_VALUE;
2470 }
2471
Ruben Brunkc78ac262015-08-13 17:58:46 -07002472 return mPreparerThread->prepare(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002473}
2474
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002475status_t Camera3Device::tearDown(int streamId) {
2476 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002477 ALOGV("%s: Camera %s: Tearing down stream %d", __FUNCTION__, mId.string(), streamId);
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002478 Mutex::Autolock il(mInterfaceLock);
2479 Mutex::Autolock l(mLock);
2480
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002481 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2482 if (stream == nullptr) {
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002483 CLOGE("Stream %d does not exist", streamId);
2484 return BAD_VALUE;
2485 }
2486
Eino-Ville Talvalab25e3c82015-07-15 16:04:27 -07002487 if (stream->hasOutstandingBuffers() || mRequestThread->isStreamPending(stream)) {
2488 CLOGE("Stream %d is a target of a in-progress request", streamId);
2489 return BAD_VALUE;
2490 }
2491
2492 return stream->tearDown();
2493}
2494
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002495status_t Camera3Device::addBufferListenerForStream(int streamId,
2496 wp<Camera3StreamBufferListener> listener) {
2497 ATRACE_CALL();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002498 ALOGV("%s: Camera %s: Adding buffer listener for stream %d", __FUNCTION__, mId.string(), streamId);
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002499 Mutex::Autolock il(mInterfaceLock);
2500 Mutex::Autolock l(mLock);
2501
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002502 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
2503 if (stream == nullptr) {
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002504 CLOGE("Stream %d does not exist", streamId);
2505 return BAD_VALUE;
2506 }
Shuzhen Wangb0fdc1e2016-03-20 23:21:39 -07002507 stream->addBufferListener(listener);
2508
2509 return OK;
2510}
2511
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002512/**
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002513 * Methods called by subclasses
2514 */
2515
2516void Camera3Device::notifyStatus(bool idle) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07002517 ATRACE_CALL();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002518 {
2519 // Need mLock to safely update state and synchronize to current
2520 // state of methods in flight.
2521 Mutex::Autolock l(mLock);
2522 // We can get various system-idle notices from the status tracker
2523 // while starting up. Only care about them if we've actually sent
2524 // in some requests recently.
2525 if (mStatus != STATUS_ACTIVE && mStatus != STATUS_CONFIGURED) {
2526 return;
2527 }
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08002528 ALOGV("%s: Camera %s: Now %s, pauseState: %s", __FUNCTION__, mId.string(),
2529 idle ? "idle" : "active", mPauseStateNotify ? "true" : "false");
Ruben Brunk183f0562015-08-12 12:55:02 -07002530 internalUpdateStatusLocked(idle ? STATUS_CONFIGURED : STATUS_ACTIVE);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002531
2532 // Skip notifying listener if we're doing some user-transparent
2533 // state changes
2534 if (mPauseStateNotify) return;
2535 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002536
2537 sp<NotificationListener> listener;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002538 {
2539 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07002540 listener = mListener.promote();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002541 }
2542 if (idle && listener != NULL) {
2543 listener->notifyIdle();
2544 }
2545}
2546
Shuzhen Wang758c2152017-01-10 18:26:18 -08002547status_t Camera3Device::setConsumerSurfaces(int streamId,
Emilian Peev40ead602017-09-26 15:46:36 +01002548 const std::vector<sp<Surface>>& consumers, std::vector<int> *surfaceIds) {
Zhijun He5d677d12016-05-29 16:52:39 -07002549 ATRACE_CALL();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002550 ALOGV("%s: Camera %s: set consumer surface for stream %d",
2551 __FUNCTION__, mId.string(), streamId);
Emilian Peev40ead602017-09-26 15:46:36 +01002552
2553 if (surfaceIds == nullptr) {
2554 return BAD_VALUE;
2555 }
2556
Zhijun He5d677d12016-05-29 16:52:39 -07002557 Mutex::Autolock il(mInterfaceLock);
2558 Mutex::Autolock l(mLock);
2559
Shuzhen Wang758c2152017-01-10 18:26:18 -08002560 if (consumers.size() == 0) {
2561 CLOGE("No consumer is passed!");
Zhijun He5d677d12016-05-29 16:52:39 -07002562 return BAD_VALUE;
2563 }
2564
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002565 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2566 if (stream == nullptr) {
Zhijun He5d677d12016-05-29 16:52:39 -07002567 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002568 return BAD_VALUE;
Zhijun He5d677d12016-05-29 16:52:39 -07002569 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002570
2571 // isConsumerConfigurationDeferred will be off after setConsumers
2572 bool isDeferred = stream->isConsumerConfigurationDeferred();
Shuzhen Wang758c2152017-01-10 18:26:18 -08002573 status_t res = stream->setConsumers(consumers);
Zhijun He5d677d12016-05-29 16:52:39 -07002574 if (res != OK) {
2575 CLOGE("Stream %d set consumer failed (error %d %s) ", streamId, res, strerror(-res));
2576 return res;
2577 }
2578
Emilian Peev40ead602017-09-26 15:46:36 +01002579 for (auto &consumer : consumers) {
2580 int id = stream->getSurfaceId(consumer);
2581 if (id < 0) {
2582 CLOGE("Invalid surface id!");
2583 return BAD_VALUE;
2584 }
2585 surfaceIds->push_back(id);
2586 }
2587
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002588 if (isDeferred) {
Shuzhen Wang0129d522016-10-30 22:43:41 -07002589 if (!stream->isConfiguring()) {
2590 CLOGE("Stream %d was already fully configured.", streamId);
2591 return INVALID_OPERATION;
2592 }
Zhijun He5d677d12016-05-29 16:52:39 -07002593
Shuzhen Wang0129d522016-10-30 22:43:41 -07002594 res = stream->finishConfiguration();
2595 if (res != OK) {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002596 // If finishConfiguration fails due to abandoned surface, do not set
2597 // device to error state.
2598 bool isSurfaceAbandoned =
2599 (res == NO_INIT || res == DEAD_OBJECT) && stream->isAbandoned();
2600 if (!isSurfaceAbandoned) {
2601 SET_ERR_L("Can't finish configuring output stream %d: %s (%d)",
2602 stream->getId(), strerror(-res), res);
2603 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07002604 return res;
2605 }
Zhijun He5d677d12016-05-29 16:52:39 -07002606 }
2607
2608 return OK;
2609}
2610
Emilian Peev40ead602017-09-26 15:46:36 +01002611status_t Camera3Device::updateStream(int streamId, const std::vector<sp<Surface>> &newSurfaces,
2612 const std::vector<OutputStreamInfo> &outputInfo,
2613 const std::vector<size_t> &removedSurfaceIds, KeyedVector<sp<Surface>, size_t> *outputMap) {
2614 Mutex::Autolock il(mInterfaceLock);
2615 Mutex::Autolock l(mLock);
2616
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002617 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2618 if (stream == nullptr) {
Emilian Peev40ead602017-09-26 15:46:36 +01002619 CLOGE("Stream %d is unknown", streamId);
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002620 return BAD_VALUE;
Emilian Peev40ead602017-09-26 15:46:36 +01002621 }
2622
2623 for (const auto &it : removedSurfaceIds) {
2624 if (mRequestThread->isOutputSurfacePending(streamId, it)) {
2625 CLOGE("Shared surface still part of a pending request!");
2626 return -EBUSY;
2627 }
2628 }
2629
Emilian Peev40ead602017-09-26 15:46:36 +01002630 status_t res = stream->updateStream(newSurfaces, outputInfo, removedSurfaceIds, outputMap);
2631 if (res != OK) {
2632 CLOGE("Stream %d failed to update stream (error %d %s) ",
2633 streamId, res, strerror(-res));
2634 if (res == UNKNOWN_ERROR) {
2635 SET_ERR_L("%s: Stream update failed to revert to previous output configuration!",
2636 __FUNCTION__);
2637 }
2638 return res;
2639 }
2640
2641 return res;
2642}
2643
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002644status_t Camera3Device::dropStreamBuffers(bool dropping, int streamId) {
2645 Mutex::Autolock il(mInterfaceLock);
2646 Mutex::Autolock l(mLock);
2647
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002648 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streamId);
2649 if (stream == nullptr) {
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002650 ALOGE("%s: Stream %d is not found.", __FUNCTION__, streamId);
2651 return BAD_VALUE;
2652 }
Chien-Yu Chena936ac22017-10-23 15:59:49 -07002653 return stream->dropBuffers(dropping);
2654}
2655
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002656/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002657 * Camera3Device private methods
2658 */
2659
2660sp<Camera3Device::CaptureRequest> Camera3Device::createCaptureRequest(
Emilian Peevaebbe412018-01-15 13:53:24 +00002661 const PhysicalCameraSettingsList &request, const SurfaceMap &surfaceMap) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002662 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002663
2664 sp<CaptureRequest> newRequest = new CaptureRequest;
Emilian Peevaebbe412018-01-15 13:53:24 +00002665 newRequest->mSettingsList = request;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002666
2667 camera_metadata_entry_t inputStreams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002668 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002669 if (inputStreams.count > 0) {
2670 if (mInputStream == NULL ||
Zhijun Hed1d64672013-09-06 15:00:01 -07002671 mInputStream->getId() != inputStreams.data.i32[0]) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002672 CLOGE("Request references unknown input stream %d",
2673 inputStreams.data.u8[0]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002674 return NULL;
2675 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002676
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002677 if (mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002678 SET_ERR_L("%s: input stream %d is not configured!",
2679 __FUNCTION__, mInputStream->getId());
2680 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002681 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002682 // Check if stream prepare is blocking requests.
2683 if (mInputStream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002684 CLOGE("Request references an input stream that's being prepared!");
2685 return NULL;
2686 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002687
2688 newRequest->mInputStream = mInputStream;
Emilian Peevaebbe412018-01-15 13:53:24 +00002689 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_INPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002690 }
2691
2692 camera_metadata_entry_t streams =
Emilian Peevaebbe412018-01-15 13:53:24 +00002693 newRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_OUTPUT_STREAMS);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002694 if (streams.count == 0) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002695 CLOGE("Zero output streams specified!");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002696 return NULL;
2697 }
2698
2699 for (size_t i = 0; i < streams.count; i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002700 sp<Camera3OutputStreamInterface> stream = mOutputStreams.get(streams.data.i32[i]);
2701 if (stream == nullptr) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002702 CLOGE("Request references unknown stream %d",
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002703 streams.data.i32[i]);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002704 return NULL;
2705 }
Zhijun He5d677d12016-05-29 16:52:39 -07002706 // It is illegal to include a deferred consumer output stream into a request
Shuzhen Wang0129d522016-10-30 22:43:41 -07002707 auto iter = surfaceMap.find(streams.data.i32[i]);
2708 if (iter != surfaceMap.end()) {
2709 const std::vector<size_t>& surfaces = iter->second;
2710 for (const auto& surface : surfaces) {
2711 if (stream->isConsumerConfigurationDeferred(surface)) {
2712 CLOGE("Stream %d surface %zu hasn't finished configuration yet "
2713 "due to deferred consumer", stream->getId(), surface);
2714 return NULL;
2715 }
2716 }
Yin-Chia Yeh0b287572018-10-15 12:38:13 -07002717 newRequest->mOutputSurfaces[streams.data.i32[i]] = surfaces;
Zhijun He5d677d12016-05-29 16:52:39 -07002718 }
2719
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002720 if (stream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002721 SET_ERR_L("%s: stream %d is not configured!", __FUNCTION__, stream->getId());
2722 return NULL;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002723 }
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07002724 // Check if stream prepare is blocking requests.
2725 if (stream->isBlockedByPrepare()) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07002726 CLOGE("Request references an output stream that's being prepared!");
2727 return NULL;
2728 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002729
2730 newRequest->mOutputStreams.push(stream);
2731 }
Emilian Peevaebbe412018-01-15 13:53:24 +00002732 newRequest->mSettingsList.begin()->metadata.erase(ANDROID_REQUEST_OUTPUT_STREAMS);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07002733 newRequest->mBatchSize = 1;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002734
2735 return newRequest;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002736}
2737
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07002738bool Camera3Device::isOpaqueInputSizeSupported(uint32_t width, uint32_t height) {
2739 for (uint32_t i = 0; i < mSupportedOpaqueInputSizes.size(); i++) {
2740 Size size = mSupportedOpaqueInputSizes[i];
2741 if (size.width == width && size.height == height) {
2742 return true;
2743 }
2744 }
2745
2746 return false;
2747}
2748
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002749void Camera3Device::cancelStreamsConfigurationLocked() {
2750 int res = OK;
2751 if (mInputStream != NULL && mInputStream->isConfiguring()) {
2752 res = mInputStream->cancelConfiguration();
2753 if (res != OK) {
2754 CLOGE("Can't cancel configuring input stream %d: %s (%d)",
2755 mInputStream->getId(), strerror(-res), res);
2756 }
2757 }
2758
2759 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002760 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002761 if (outputStream->isConfiguring()) {
2762 res = outputStream->cancelConfiguration();
2763 if (res != OK) {
2764 CLOGE("Can't cancel configuring output stream %d: %s (%d)",
2765 outputStream->getId(), strerror(-res), res);
2766 }
2767 }
2768 }
2769
2770 // Return state to that at start of call, so that future configures
2771 // properly clean things up
2772 internalUpdateStatusLocked(STATUS_UNCONFIGURED);
2773 mNeedConfig = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002774
2775 res = mPreparerThread->resume();
2776 if (res != OK) {
2777 ALOGE("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
2778 }
2779}
2780
2781bool Camera3Device::reconfigureCamera(const CameraMetadata& sessionParams) {
2782 ATRACE_CALL();
2783 bool ret = false;
2784
2785 Mutex::Autolock il(mInterfaceLock);
2786 nsecs_t maxExpectedDuration = getExpectedInFlightDuration();
2787
2788 Mutex::Autolock l(mLock);
2789 auto rc = internalPauseAndWaitLocked(maxExpectedDuration);
2790 if (rc == NO_ERROR) {
2791 mNeedConfig = true;
2792 rc = configureStreamsLocked(mOperatingMode, sessionParams, /*notifyRequestThread*/ false);
2793 if (rc == NO_ERROR) {
2794 ret = true;
2795 mPauseStateNotify = false;
2796 //Moving to active state while holding 'mLock' is important.
2797 //There could be pending calls to 'create-/deleteStream' which
2798 //will trigger another stream configuration while the already
2799 //present streams end up with outstanding buffers that will
2800 //not get drained.
2801 internalUpdateStatusLocked(STATUS_ACTIVE);
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002802 } else if (rc == DEAD_OBJECT) {
2803 // DEAD_OBJECT can be returned if either the consumer surface is
2804 // abandoned, or the HAL has died.
2805 // - If the HAL has died, configureStreamsLocked call will set
2806 // device to error state,
2807 // - If surface is abandoned, we should not set device to error
2808 // state.
2809 ALOGE("Failed to re-configure camera due to abandoned surface");
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002810 } else {
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002811 SET_ERR_L("Failed to re-configure camera: %d", rc);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002812 }
2813 } else {
2814 ALOGE("%s: Failed to pause streaming: %d", __FUNCTION__, rc);
2815 }
2816
2817 return ret;
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002818}
2819
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002820status_t Camera3Device::configureStreamsLocked(int operatingMode,
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002821 const CameraMetadata& sessionParams, bool notifyRequestThread) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002822 ATRACE_CALL();
2823 status_t res;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08002824
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07002825 if (mStatus != STATUS_UNCONFIGURED && mStatus != STATUS_CONFIGURED) {
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002826 CLOGE("Not idle");
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002827 return INVALID_OPERATION;
2828 }
2829
Eino-Ville Talvalae7091aa2017-03-07 15:23:06 -08002830 if (operatingMode < 0) {
2831 CLOGE("Invalid operating mode: %d", operatingMode);
2832 return BAD_VALUE;
2833 }
2834
2835 bool isConstrainedHighSpeed =
2836 static_cast<int>(StreamConfigurationMode::CONSTRAINED_HIGH_SPEED_MODE) ==
2837 operatingMode;
2838
2839 if (mOperatingMode != operatingMode) {
2840 mNeedConfig = true;
2841 mIsConstrainedHighSpeedConfiguration = isConstrainedHighSpeed;
2842 mOperatingMode = operatingMode;
2843 }
2844
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07002845 // In case called from configureStreams, abort queued input buffers not belonging to
2846 // any pending requests.
2847 if (mInputStream != NULL && notifyRequestThread) {
2848 while (true) {
2849 camera3_stream_buffer_t inputBuffer;
2850 status_t res = mInputStream->getInputBuffer(&inputBuffer,
2851 /*respectHalLimit*/ false);
2852 if (res != OK) {
2853 // Exhausted acquiring all input buffers.
2854 break;
2855 }
2856
2857 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
2858 res = mInputStream->returnInputBuffer(inputBuffer);
2859 if (res != OK) {
2860 ALOGE("%s: %d: couldn't return input buffer while clearing input queue: "
2861 "%s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
2862 }
2863 }
2864 }
2865
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07002866 if (!mNeedConfig) {
2867 ALOGV("%s: Skipping config, no stream changes", __FUNCTION__);
2868 return OK;
2869 }
2870
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07002871 // Workaround for device HALv3.2 or older spec bug - zero streams requires
2872 // adding a dummy stream instead.
2873 // TODO: Bug: 17321404 for fixing the HAL spec and removing this workaround.
2874 if (mOutputStreams.size() == 0) {
2875 addDummyStreamLocked();
2876 } else {
2877 tryRemoveDummyStreamLocked();
2878 }
2879
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002880 // Start configuring the streams
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002881 ALOGV("%s: Camera %s: Starting stream configuration", __FUNCTION__, mId.string());
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002882
Emilian Peevac3ce6c2017-12-12 15:27:02 +00002883 mPreparerThread->pause();
2884
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002885 camera3_stream_configuration config;
Eino-Ville Talvalabbbbe842017-02-28 17:50:56 -08002886 config.operation_mode = mOperatingMode;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002887 config.num_streams = (mInputStream != NULL) + mOutputStreams.size();
2888
2889 Vector<camera3_stream_t*> streams;
2890 streams.setCapacity(config.num_streams);
Emilian Peev192ee832018-01-31 14:46:47 +00002891 std::vector<uint32_t> bufferSizes(config.num_streams, 0);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002892
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002893
2894 if (mInputStream != NULL) {
2895 camera3_stream_t *inputStream;
2896 inputStream = mInputStream->startConfiguration();
2897 if (inputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002898 CLOGE("Can't start input stream configuration");
2899 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002900 return INVALID_OPERATION;
2901 }
2902 streams.add(inputStream);
2903 }
2904
2905 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Igor Murashkin2fba5842013-04-22 14:03:54 -07002906
2907 // Don't configure bidi streams twice, nor add them twice to the list
2908 if (mOutputStreams[i].get() ==
2909 static_cast<Camera3StreamInterface*>(mInputStream.get())) {
2910
2911 config.num_streams--;
2912 continue;
2913 }
2914
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002915 camera3_stream_t *outputStream;
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002916 outputStream = mOutputStreams[i]->startConfiguration();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002917 if (outputStream == NULL) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002918 CLOGE("Can't start output stream configuration");
2919 cancelStreamsConfigurationLocked();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002920 return INVALID_OPERATION;
2921 }
2922 streams.add(outputStream);
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002923
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002924 if (outputStream->format == HAL_PIXEL_FORMAT_BLOB) {
Emilian Peev192ee832018-01-31 14:46:47 +00002925 size_t k = i + ((mInputStream != nullptr) ? 1 : 0); // Input stream if present should
2926 // always occupy the initial entry.
Shuzhen Wangb7ab1e42019-02-20 15:42:23 -08002927 if (outputStream->data_space == HAL_DATASPACE_V0_JFIF) {
2928 bufferSizes[k] = static_cast<uint32_t>(
2929 getJpegBufferSize(outputStream->width, outputStream->height));
2930 } else if (outputStream->data_space ==
2931 static_cast<android_dataspace>(HAL_DATASPACE_JPEG_APP_SEGMENTS)) {
2932 bufferSizes[k] = outputStream->width * outputStream->height;
2933 } else {
2934 ALOGW("%s: Blob dataSpace %d not supported",
2935 __FUNCTION__, outputStream->data_space);
2936 }
Yin-Chia Yehfb6e55b2018-01-25 10:50:26 -08002937 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002938 }
2939
2940 config.streams = streams.editArray();
2941
2942 // Do the HAL configuration; will potentially touch stream
Shuzhen Wang92653952019-05-07 15:11:43 -07002943 // max_buffers, usage, and priv fields, as well as data_space and format
2944 // fields for IMPLEMENTATION_DEFINED formats.
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08002945
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002946 const camera_metadata_t *sessionBuffer = sessionParams.getAndLock();
Emilian Peev192ee832018-01-31 14:46:47 +00002947 res = mInterface->configureStreams(sessionBuffer, &config, bufferSizes);
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01002948 sessionParams.unlock(sessionBuffer);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002949
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002950 if (res == BAD_VALUE) {
2951 // HAL rejected this set of streams as unsupported, clean up config
2952 // attempt and return to unconfigured state
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002953 CLOGE("Set of requested inputs/outputs not supported by HAL");
2954 cancelStreamsConfigurationLocked();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07002955 return BAD_VALUE;
2956 } else if (res != OK) {
2957 // Some other kind of error from configure_streams - this is not
2958 // expected
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07002959 SET_ERR_L("Unable to configure streams with HAL: %s (%d)",
2960 strerror(-res), res);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08002961 return res;
2962 }
2963
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002964 // Finish all stream configuration immediately.
2965 // TODO: Try to relax this later back to lazy completion, which should be
2966 // faster
2967
Igor Murashkin073f8572013-05-02 14:59:28 -07002968 if (mInputStream != NULL && mInputStream->isConfiguring()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002969 bool streamReConfigured = false;
2970 res = mInputStream->finishConfiguration(&streamReConfigured);
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002971 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002972 CLOGE("Can't finish configuring input stream %d: %s (%d)",
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002973 mInputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002974 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002975 if ((res == NO_INIT || res == DEAD_OBJECT) && mInputStream->isAbandoned()) {
2976 return DEAD_OBJECT;
2977 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002978 return BAD_VALUE;
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002979 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002980 if (streamReConfigured) {
2981 mInterface->onStreamReConfigured(mInputStream->getId());
2982 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07002983 }
2984
2985 for (size_t i = 0; i < mOutputStreams.size(); i++) {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07002986 sp<Camera3OutputStreamInterface> outputStream = mOutputStreams[i];
Zhijun He5d677d12016-05-29 16:52:39 -07002987 if (outputStream->isConfiguring() && !outputStream->isConsumerConfigurationDeferred()) {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002988 bool streamReConfigured = false;
2989 res = outputStream->finishConfiguration(&streamReConfigured);
Igor Murashkin073f8572013-05-02 14:59:28 -07002990 if (res != OK) {
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002991 CLOGE("Can't finish configuring output stream %d: %s (%d)",
Igor Murashkin073f8572013-05-02 14:59:28 -07002992 outputStream->getId(), strerror(-res), res);
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002993 cancelStreamsConfigurationLocked();
Shuzhen Wang210ba5c2018-07-25 16:47:40 -07002994 if ((res == NO_INIT || res == DEAD_OBJECT) && outputStream->isAbandoned()) {
2995 return DEAD_OBJECT;
2996 }
Chien-Yu Chen9b5860b2016-06-10 13:39:09 -07002997 return BAD_VALUE;
Igor Murashkin073f8572013-05-02 14:59:28 -07002998 }
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07002999 if (streamReConfigured) {
3000 mInterface->onStreamReConfigured(outputStream->getId());
3001 }
Eino-Ville Talvala4c956762013-04-19 17:26:13 -07003002 }
3003 }
3004
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003005 // Request thread needs to know to avoid using repeat-last-settings protocol
3006 // across configure_streams() calls
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003007 if (notifyRequestThread) {
3008 mRequestThread->configurationComplete(mIsConstrainedHighSpeedConfiguration, sessionParams);
3009 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003010
Zhijun He90f7c372016-08-16 16:19:43 -07003011 char value[PROPERTY_VALUE_MAX];
3012 property_get("camera.fifo.disable", value, "0");
3013 int32_t disableFifo = atoi(value);
3014 if (disableFifo != 1) {
3015 // Boost priority of request thread to SCHED_FIFO.
3016 pid_t requestThreadTid = mRequestThread->getTid();
3017 res = requestPriority(getpid(), requestThreadTid,
Mikhail Naganov83f04272017-02-07 10:45:09 -08003018 kRequestThreadPriority, /*isForApp*/ false, /*asynchronous*/ false);
Zhijun He90f7c372016-08-16 16:19:43 -07003019 if (res != OK) {
3020 ALOGW("Can't set realtime priority for request processing thread: %s (%d)",
3021 strerror(-res), res);
3022 } else {
3023 ALOGD("Set real time priority for request queue thread (tid %d)", requestThreadTid);
3024 }
Eino-Ville Talvalaf99498e2015-09-25 16:52:55 -07003025 }
3026
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003027 // Update device state
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01003028 const camera_metadata_t *newSessionParams = sessionParams.getAndLock();
3029 const camera_metadata_t *currentSessionParams = mSessionParams.getAndLock();
3030 bool updateSessionParams = (newSessionParams != currentSessionParams) ? true : false;
3031 sessionParams.unlock(newSessionParams);
3032 mSessionParams.unlock(currentSessionParams);
3033 if (updateSessionParams) {
3034 mSessionParams = sessionParams;
3035 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003036
Eino-Ville Talvalaea26c772013-06-11 16:04:06 -07003037 mNeedConfig = false;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003038
Ruben Brunk183f0562015-08-12 12:55:02 -07003039 internalUpdateStatusLocked((mDummyStreamId == NO_STREAM) ?
3040 STATUS_CONFIGURED : STATUS_UNCONFIGURED);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003041
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003042 ALOGV("%s: Camera %s: Stream configuration complete", __FUNCTION__, mId.string());
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07003043
Zhijun He0a210512014-07-24 13:45:15 -07003044 // tear down the deleted streams after configure streams.
3045 mDeletedStreams.clear();
3046
Emilian Peevac3ce6c2017-12-12 15:27:02 +00003047 auto rc = mPreparerThread->resume();
3048 if (rc != OK) {
3049 SET_ERR_L("%s: Camera %s: Preparer thread failed to resume!", __FUNCTION__, mId.string());
3050 return rc;
3051 }
3052
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003053 if (mDummyStreamId == NO_STREAM) {
3054 mRequestBufferSM.onStreamsConfigured();
3055 }
3056
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003057 return OK;
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003058}
3059
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003060status_t Camera3Device::addDummyStreamLocked() {
3061 ATRACE_CALL();
3062 status_t res;
3063
3064 if (mDummyStreamId != NO_STREAM) {
3065 // Should never be adding a second dummy stream when one is already
3066 // active
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003067 SET_ERR_L("%s: Camera %s: A dummy stream already exists!",
3068 __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003069 return INVALID_OPERATION;
3070 }
3071
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003072 ALOGV("%s: Camera %s: Adding a dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003073
3074 sp<Camera3OutputStreamInterface> dummyStream =
3075 new Camera3DummyStream(mNextStreamId);
3076
3077 res = mOutputStreams.add(mNextStreamId, dummyStream);
3078 if (res < 0) {
3079 SET_ERR_L("Can't add dummy stream to set: %s (%d)", strerror(-res), res);
3080 return res;
3081 }
3082
3083 mDummyStreamId = mNextStreamId;
3084 mNextStreamId++;
3085
3086 return OK;
3087}
3088
3089status_t Camera3Device::tryRemoveDummyStreamLocked() {
3090 ATRACE_CALL();
3091 status_t res;
3092
3093 if (mDummyStreamId == NO_STREAM) return OK;
3094 if (mOutputStreams.size() == 1) return OK;
3095
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003096 ALOGV("%s: Camera %s: Removing the dummy stream", __FUNCTION__, mId.string());
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003097
3098 // Ok, have a dummy stream and there's at least one other output stream,
3099 // so remove the dummy
3100
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003101 sp<Camera3StreamInterface> deletedStream = mOutputStreams.get(mDummyStreamId);
3102 if (deletedStream == nullptr) {
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003103 SET_ERR_L("Dummy stream %d does not appear to exist", mDummyStreamId);
3104 return INVALID_OPERATION;
3105 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003106 mOutputStreams.remove(mDummyStreamId);
Eino-Ville Talvala16a2ada2014-08-27 14:41:33 -07003107
3108 // Free up the stream endpoint so that it can be used by some other stream
3109 res = deletedStream->disconnect();
3110 if (res != OK) {
3111 SET_ERR_L("Can't disconnect deleted dummy stream %d", mDummyStreamId);
3112 // fall through since we want to still list the stream as deleted.
3113 }
3114 mDeletedStreams.add(deletedStream);
3115 mDummyStreamId = NO_STREAM;
3116
3117 return res;
3118}
3119
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003120void Camera3Device::setErrorState(const char *fmt, ...) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003121 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003122 Mutex::Autolock l(mLock);
3123 va_list args;
3124 va_start(args, fmt);
3125
3126 setErrorStateLockedV(fmt, args);
3127
3128 va_end(args);
3129}
3130
3131void Camera3Device::setErrorStateV(const char *fmt, va_list args) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003132 ATRACE_CALL();
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003133 Mutex::Autolock l(mLock);
3134 setErrorStateLockedV(fmt, args);
3135}
3136
3137void Camera3Device::setErrorStateLocked(const char *fmt, ...) {
3138 va_list args;
3139 va_start(args, fmt);
3140
3141 setErrorStateLockedV(fmt, args);
3142
3143 va_end(args);
3144}
3145
3146void Camera3Device::setErrorStateLockedV(const char *fmt, va_list args) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003147 // Print out all error messages to log
3148 String8 errorCause = String8::formatV(fmt, args);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003149 ALOGE("Camera %s: %s", mId.string(), errorCause.string());
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003150
3151 // But only do error state transition steps for the first error
Zhijun Heb05eeae2013-06-06 13:51:22 -07003152 if (mStatus == STATUS_ERROR || mStatus == STATUS_UNINITIALIZED) return;
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003153
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003154 mErrorCause = errorCause;
3155
Yin-Chia Yeh3d145ae2017-07-27 12:47:03 -07003156 if (mRequestThread != nullptr) {
3157 mRequestThread->setPaused(true);
3158 }
Ruben Brunk183f0562015-08-12 12:55:02 -07003159 internalUpdateStatusLocked(STATUS_ERROR);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003160
3161 // Notify upstream about a device error
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003162 sp<NotificationListener> listener = mListener.promote();
3163 if (listener != NULL) {
3164 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003165 CaptureResultExtras());
3166 }
3167
3168 // Save stack trace. View by dumping it later.
3169 CameraTraces::saveTrace();
3170 // TODO: consider adding errorCause and client pid/procname
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003171}
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003172
3173/**
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003174 * In-flight request management
3175 */
3176
Jianing Weicb0652e2014-03-12 18:29:36 -07003177status_t Camera3Device::registerInFlight(uint32_t frameNumber,
Chien-Yu Chend196d612015-06-22 19:49:01 -07003178 int32_t numBuffers, CaptureResultExtras resultExtras, bool hasInput,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003179 bool hasAppCallback, nsecs_t maxExpectedDuration,
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003180 std::set<String8>& physicalCameraIds, bool isStillCapture,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003181 bool isZslCapture, const std::set<std::string>& cameraIdsWithZoom,
3182 const SurfaceMap& outputSurfaces) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003183 ATRACE_CALL();
3184 Mutex::Autolock l(mInFlightLock);
3185
3186 ssize_t res;
Chien-Yu Chend196d612015-06-22 19:49:01 -07003187 res = mInFlightMap.add(frameNumber, InFlightRequest(numBuffers, resultExtras, hasInput,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003188 hasAppCallback, maxExpectedDuration, physicalCameraIds, isStillCapture, isZslCapture,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003189 cameraIdsWithZoom, outputSurfaces));
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003190 if (res < 0) return res;
3191
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003192 if (mInFlightMap.size() == 1) {
Emilian Peev26d975d2018-07-05 14:52:57 +01003193 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3194 // avoid a deadlock during reprocess requests.
3195 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003196 if (mStatusTracker != nullptr) {
3197 mStatusTracker->markComponentActive(mInFlightStatusId);
3198 }
Eino-Ville Talvala24b366e2016-07-21 12:53:07 -07003199 }
3200
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003201 mExpectedInflightDuration += maxExpectedDuration;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003202 return OK;
3203}
3204
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003205void Camera3Device::returnOutputBuffers(
3206 const camera3_stream_buffer_t *outputBuffers, size_t numBuffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003207 nsecs_t timestamp, bool timestampIncreasing,
3208 const SurfaceMap& outputSurfaces,
3209 const CaptureResultExtras &inResultExtras) {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003210
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003211 for (size_t i = 0; i < numBuffers; i++)
3212 {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08003213 if (outputBuffers[i].buffer == nullptr) {
3214 if (!mUseHalBufManager) {
3215 // With HAL buffer management API, HAL sometimes will have to return buffers that
3216 // has not got a output buffer handle filled yet. This is though illegal if HAL
3217 // buffer management API is not being used.
3218 ALOGE("%s: cannot return a null buffer!", __FUNCTION__);
3219 }
3220 continue;
3221 }
3222
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003223 Camera3StreamInterface *stream = Camera3Stream::cast(outputBuffers[i].stream);
3224 int streamId = stream->getId();
3225 const auto& it = outputSurfaces.find(streamId);
3226 status_t res = OK;
3227 if (it != outputSurfaces.end()) {
3228 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003229 outputBuffers[i], timestamp, timestampIncreasing, it->second,
3230 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003231 } else {
3232 res = stream->returnBuffer(
Emilian Peev538c90e2018-12-17 18:03:19 +00003233 outputBuffers[i], timestamp, timestampIncreasing, std::vector<size_t> (),
3234 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003235 }
3236
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003237 // Note: stream may be deallocated at this point, if this buffer was
3238 // the last reference to it.
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07003239 if (res == NO_INIT || res == DEAD_OBJECT) {
3240 ALOGV("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
3241 } else if (res != OK) {
3242 ALOGE("Can't return buffer to its stream: %s (%d)", strerror(-res), res);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003243 }
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003244
3245 // Long processing consumers can cause returnBuffer timeout for shared stream
3246 // If that happens, cancel the buffer and send a buffer error to client
3247 if (it != outputSurfaces.end() && res == TIMED_OUT &&
3248 outputBuffers[i].status == CAMERA3_BUFFER_STATUS_OK) {
3249 // cancel the buffer
3250 camera3_stream_buffer_t sb = outputBuffers[i];
3251 sb.status = CAMERA3_BUFFER_STATUS_ERROR;
Emilian Peev538c90e2018-12-17 18:03:19 +00003252 stream->returnBuffer(sb, /*timestamp*/0, timestampIncreasing, std::vector<size_t> (),
3253 inResultExtras.frameNumber);
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003254
3255 // notify client buffer error
3256 sp<NotificationListener> listener;
3257 {
3258 Mutex::Autolock l(mOutputLock);
3259 listener = mListener.promote();
3260 }
3261
3262 if (listener != nullptr) {
3263 CaptureResultExtras extras = inResultExtras;
3264 extras.errorStreamId = streamId;
3265 listener->notifyError(
3266 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER,
3267 extras);
3268 }
3269 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003270 }
3271}
3272
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003273void Camera3Device::removeInFlightMapEntryLocked(int idx) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003274 ATRACE_CALL();
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003275 nsecs_t duration = mInFlightMap.valueAt(idx).maxExpectedDuration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003276 mInFlightMap.removeItemsAt(idx, 1);
3277
3278 // Indicate idle inFlightMap to the status tracker
3279 if (mInFlightMap.size() == 0) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07003280 mRequestBufferSM.onInflightMapEmpty();
Emilian Peev26d975d2018-07-05 14:52:57 +01003281 // Hold a separate dedicated tracker lock to prevent race with disconnect and also
3282 // avoid a deadlock during reprocess requests.
3283 Mutex::Autolock l(mTrackerLock);
Yin-Chia Yeh38dfde52017-06-27 17:13:33 -07003284 if (mStatusTracker != nullptr) {
3285 mStatusTracker->markComponentIdle(mInFlightStatusId, Fence::NO_FENCE);
3286 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003287 }
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07003288 mExpectedInflightDuration -= duration;
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003289}
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003290
3291void Camera3Device::removeInFlightRequestIfReadyLocked(int idx) {
3292
3293 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3294 const uint32_t frameNumber = mInFlightMap.keyAt(idx);
3295
3296 nsecs_t sensorTimestamp = request.sensorTimestamp;
3297 nsecs_t shutterTimestamp = request.shutterTimestamp;
3298
3299 // Check if it's okay to remove the request from InFlightMap:
3300 // In the case of a successful request:
3301 // all input and output buffers, all result metadata, shutter callback
3302 // arrived.
3303 // In the case of a unsuccessful request:
3304 // all input and output buffers arrived.
3305 if (request.numBuffersLeft == 0 &&
Shuzhen Wang20f57342017-08-24 15:39:05 -07003306 (request.skipResultMetadata ||
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003307 (request.haveResultMetadata && shutterTimestamp != 0))) {
Emilian Peev9dd21f42018-08-03 13:39:29 +01003308 if (request.stillCapture) {
3309 ATRACE_ASYNC_END("still capture", frameNumber);
3310 }
3311
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003312 ATRACE_ASYNC_END("frame capture", frameNumber);
3313
Shuzhen Wang403044a2017-02-26 23:29:04 -08003314 // Sanity check - if sensor timestamp matches shutter timestamp in the
3315 // case of request having callback.
3316 if (request.hasCallback && request.requestStatus == OK &&
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003317 sensorTimestamp != shutterTimestamp) {
3318 SET_ERR("sensor timestamp (%" PRId64
3319 ") for frame %d doesn't match shutter timestamp (%" PRId64 ")",
3320 sensorTimestamp, frameNumber, shutterTimestamp);
3321 }
3322
3323 // for an unsuccessful request, it may have pending output buffers to
3324 // return.
3325 assert(request.requestStatus != OK ||
3326 request.pendingOutputBuffers.size() == 0);
3327 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003328 request.pendingOutputBuffers.size(), 0, /*timestampIncreasing*/true,
3329 request.outputSurfaces, request.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003330
Shuzhen Wangcadb3302016-11-04 14:17:56 -07003331 removeInFlightMapEntryLocked(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003332 ALOGVV("%s: removed frame %d from InFlightMap", __FUNCTION__, frameNumber);
3333 }
3334
Yin-Chia Yeh99fd0972019-06-27 14:22:44 -07003335 // Sanity check - if we have too many in-flight frames with long total inflight duration,
3336 // something has likely gone wrong. This might still be legit only if application send in
3337 // a long burst of long exposure requests.
3338 if (mExpectedInflightDuration > kMinWarnInflightDuration) {
3339 if (!mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() > kInFlightWarnLimit) {
3340 CLOGW("In-flight list too large: %zu, total inflight duration %" PRIu64,
3341 mInFlightMap.size(), mExpectedInflightDuration);
3342 } else if (mIsConstrainedHighSpeedConfiguration && mInFlightMap.size() >
3343 kInFlightWarnLimitHighSpeed) {
3344 CLOGW("In-flight list too large for high speed configuration: %zu,"
3345 "total inflight duration %" PRIu64,
3346 mInFlightMap.size(), mExpectedInflightDuration);
3347 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003348 }
3349}
3350
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003351void Camera3Device::flushInflightRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003352 ATRACE_CALL();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003353 { // First return buffers cached in mInFlightMap
3354 Mutex::Autolock l(mInFlightLock);
3355 for (size_t idx = 0; idx < mInFlightMap.size(); idx++) {
3356 const InFlightRequest &request = mInFlightMap.valueAt(idx);
3357 returnOutputBuffers(request.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003358 request.pendingOutputBuffers.size(), 0,
3359 /*timestampIncreasing*/true, request.outputSurfaces,
3360 request.resultExtras);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003361 }
3362 mInFlightMap.clear();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07003363 mExpectedInflightDuration = 0;
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003364 }
3365
3366 // Then return all inflight buffers not returned by HAL
3367 std::vector<std::pair<int32_t, int32_t>> inflightKeys;
3368 mInterface->getInflightBufferKeys(&inflightKeys);
3369
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003370 // Inflight buffers for HAL buffer manager
3371 std::vector<uint64_t> inflightRequestBufferKeys;
3372 mInterface->getInflightRequestBufferKeys(&inflightRequestBufferKeys);
3373
3374 // (streamId, frameNumber, buffer_handle_t*) tuple for all inflight buffers.
3375 // frameNumber will be -1 for buffers from HAL buffer manager
3376 std::vector<std::tuple<int32_t, int32_t, buffer_handle_t*>> inflightBuffers;
3377 inflightBuffers.reserve(inflightKeys.size() + inflightRequestBufferKeys.size());
3378
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003379 for (auto& pair : inflightKeys) {
3380 int32_t frameNumber = pair.first;
3381 int32_t streamId = pair.second;
3382 buffer_handle_t* buffer;
3383 status_t res = mInterface->popInflightBuffer(frameNumber, streamId, &buffer);
3384 if (res != OK) {
3385 ALOGE("%s: Frame %d: No in-flight buffer for stream %d",
3386 __FUNCTION__, frameNumber, streamId);
3387 continue;
3388 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08003389 inflightBuffers.push_back(std::make_tuple(streamId, frameNumber, buffer));
3390 }
3391
3392 for (auto& bufferId : inflightRequestBufferKeys) {
3393 int32_t streamId = -1;
3394 buffer_handle_t* buffer = nullptr;
3395 status_t res = mInterface->popInflightRequestBuffer(bufferId, &buffer, &streamId);
3396 if (res != OK) {
3397 ALOGE("%s: cannot find in-flight buffer %" PRIu64, __FUNCTION__, bufferId);
3398 continue;
3399 }
3400 inflightBuffers.push_back(std::make_tuple(streamId, /*frameNumber*/-1, buffer));
3401 }
3402
3403 int32_t inputStreamId = (mInputStream != nullptr) ? mInputStream->getId() : -1;
3404 for (auto& tuple : inflightBuffers) {
3405 status_t res = OK;
3406 int32_t streamId = std::get<0>(tuple);
3407 int32_t frameNumber = std::get<1>(tuple);
3408 buffer_handle_t* buffer = std::get<2>(tuple);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003409
3410 camera3_stream_buffer_t streamBuffer;
3411 streamBuffer.buffer = buffer;
3412 streamBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
3413 streamBuffer.acquire_fence = -1;
3414 streamBuffer.release_fence = -1;
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003415
3416 // First check if the buffer belongs to deleted stream
3417 bool streamDeleted = false;
3418 for (auto& stream : mDeletedStreams) {
3419 if (streamId == stream->getId()) {
3420 streamDeleted = true;
3421 // Return buffer to deleted stream
3422 camera3_stream* halStream = stream->asHalStream();
3423 streamBuffer.stream = halStream;
3424 switch (halStream->stream_type) {
3425 case CAMERA3_STREAM_OUTPUT:
Emilian Peev538c90e2018-12-17 18:03:19 +00003426 res = stream->returnBuffer(streamBuffer, /*timestamp*/ 0,
3427 /*timestampIncreasing*/true, std::vector<size_t> (), frameNumber);
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003428 if (res != OK) {
3429 ALOGE("%s: Can't return output buffer for frame %d to"
3430 " stream %d: %s (%d)", __FUNCTION__,
3431 frameNumber, streamId, strerror(-res), res);
3432 }
3433 break;
3434 case CAMERA3_STREAM_INPUT:
3435 res = stream->returnInputBuffer(streamBuffer);
3436 if (res != OK) {
3437 ALOGE("%s: Can't return input buffer for frame %d to"
3438 " stream %d: %s (%d)", __FUNCTION__,
3439 frameNumber, streamId, strerror(-res), res);
3440 }
3441 break;
3442 default: // Bi-direcitonal stream is deprecated
3443 ALOGE("%s: stream %d has unknown stream type %d",
3444 __FUNCTION__, streamId, halStream->stream_type);
3445 break;
3446 }
3447 break;
3448 }
3449 }
3450 if (streamDeleted) {
3451 continue;
3452 }
3453
3454 // Then check against configured streams
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003455 if (streamId == inputStreamId) {
3456 streamBuffer.stream = mInputStream->asHalStream();
3457 res = mInputStream->returnInputBuffer(streamBuffer);
3458 if (res != OK) {
3459 ALOGE("%s: Can't return input buffer for frame %d to"
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003460 " stream %d: %s (%d)", __FUNCTION__,
3461 frameNumber, streamId, strerror(-res), res);
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003462 }
3463 } else {
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003464 sp<Camera3StreamInterface> stream = mOutputStreams.get(streamId);
3465 if (stream == nullptr) {
Yin-Chia Yeh5090c732017-07-20 16:05:29 -07003466 ALOGE("%s: Output stream id %d not found!", __FUNCTION__, streamId);
3467 continue;
3468 }
Yin-Chia Yeh4ee35432018-10-10 13:52:31 -07003469 streamBuffer.stream = stream->asHalStream();
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07003470 returnOutputBuffers(&streamBuffer, /*size*/1, /*timestamp*/ 0);
3471 }
3472 }
3473}
3474
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003475void Camera3Device::insertResultLocked(CaptureResult *result,
3476 uint32_t frameNumber) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003477 if (result == nullptr) return;
3478
Emilian Peev71c73a22017-03-21 16:35:51 +00003479 camera_metadata_t *meta = const_cast<camera_metadata_t *>(
3480 result->mMetadata.getAndLock());
3481 set_camera_metadata_vendor_id(meta, mVendorTagId);
3482 result->mMetadata.unlock(meta);
3483
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003484 if (result->mMetadata.update(ANDROID_REQUEST_FRAME_COUNT,
3485 (int32_t*)&frameNumber, 1) != OK) {
3486 SET_ERR("Failed to set frame number %d in metadata", frameNumber);
3487 return;
3488 }
3489
3490 if (result->mMetadata.update(ANDROID_REQUEST_ID, &result->mResultExtras.requestId, 1) != OK) {
3491 SET_ERR("Failed to set request ID in metadata for frame %d", frameNumber);
3492 return;
3493 }
3494
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003495 // Update vendor tag id for physical metadata
3496 for (auto& physicalMetadata : result->mPhysicalMetadatas) {
3497 camera_metadata_t *pmeta = const_cast<camera_metadata_t *>(
3498 physicalMetadata.mPhysicalCameraMetadata.getAndLock());
3499 set_camera_metadata_vendor_id(pmeta, mVendorTagId);
3500 physicalMetadata.mPhysicalCameraMetadata.unlock(pmeta);
3501 }
3502
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003503 // Valid result, insert into queue
3504 List<CaptureResult>::iterator queuedResult =
3505 mResultQueue.insert(mResultQueue.end(), CaptureResult(*result));
3506 ALOGVV("%s: result requestId = %" PRId32 ", frameNumber = %" PRId64
3507 ", burstId = %" PRId32, __FUNCTION__,
3508 queuedResult->mResultExtras.requestId,
3509 queuedResult->mResultExtras.frameNumber,
3510 queuedResult->mResultExtras.burstId);
3511
3512 mResultSignal.signal();
3513}
3514
3515
3516void Camera3Device::sendPartialCaptureResult(const camera_metadata_t * partialResult,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003517 const CaptureResultExtras &resultExtras, uint32_t frameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003518 ATRACE_CALL();
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003519 Mutex::Autolock l(mOutputLock);
3520
3521 CaptureResult captureResult;
3522 captureResult.mResultExtras = resultExtras;
3523 captureResult.mMetadata = partialResult;
3524
Shuzhen Wang268a1362018-10-16 16:32:59 -07003525 // Fix up result metadata for monochrome camera.
3526 status_t res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3527 if (res != OK) {
3528 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3529 return;
3530 }
3531
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003532 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003533}
3534
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003535
3536void Camera3Device::sendCaptureResult(CameraMetadata &pendingMetadata,
3537 CaptureResultExtras &resultExtras,
3538 CameraMetadata &collectedPartialResult,
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003539 uint32_t frameNumber,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003540 bool reprocess, bool zslStillCapture, const std::set<std::string>& cameraIdsWithZoom,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003541 const std::vector<PhysicalCaptureResultInfo>& physicalMetadatas) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003542 ATRACE_CALL();
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003543 if (pendingMetadata.isEmpty())
3544 return;
3545
3546 Mutex::Autolock l(mOutputLock);
3547
3548 // TODO: need to track errors for tighter bounds on expected frame number
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003549 if (reprocess) {
3550 if (frameNumber < mNextReprocessResultFrameNumber) {
3551 SET_ERR("Out-of-order reprocess capture result metadata submitted! "
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003552 "(got frame number %d, expecting %d)",
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003553 frameNumber, mNextReprocessResultFrameNumber);
3554 return;
3555 }
3556 mNextReprocessResultFrameNumber = frameNumber + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003557 } else if (zslStillCapture) {
3558 if (frameNumber < mNextZslStillResultFrameNumber) {
3559 SET_ERR("Out-of-order ZSL still capture result metadata submitted! "
3560 "(got frame number %d, expecting %d)",
3561 frameNumber, mNextZslStillResultFrameNumber);
3562 return;
3563 }
3564 mNextZslStillResultFrameNumber = frameNumber + 1;
Chien-Yu Chen618ff8a2015-03-13 11:27:17 -07003565 } else {
3566 if (frameNumber < mNextResultFrameNumber) {
3567 SET_ERR("Out-of-order capture result metadata submitted! "
3568 "(got frame number %d, expecting %d)",
3569 frameNumber, mNextResultFrameNumber);
3570 return;
3571 }
3572 mNextResultFrameNumber = frameNumber + 1;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003573 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003574
3575 CaptureResult captureResult;
3576 captureResult.mResultExtras = resultExtras;
3577 captureResult.mMetadata = pendingMetadata;
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003578 captureResult.mPhysicalMetadatas = physicalMetadatas;
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003579
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003580 // Append any previous partials to form a complete result
3581 if (mUsePartialResult && !collectedPartialResult.isEmpty()) {
3582 captureResult.mMetadata.append(collectedPartialResult);
3583 }
3584
3585 captureResult.mMetadata.sort();
3586
3587 // Check that there's a timestamp in the result metadata
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003588 camera_metadata_entry timestamp = captureResult.mMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3589 if (timestamp.count == 0) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003590 SET_ERR("No timestamp provided by HAL for frame %d!",
3591 frameNumber);
3592 return;
3593 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003594 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3595 camera_metadata_entry timestamp =
3596 physicalMetadata.mPhysicalCameraMetadata.find(ANDROID_SENSOR_TIMESTAMP);
3597 if (timestamp.count == 0) {
3598 SET_ERR("No timestamp provided by HAL for physical camera %s frame %d!",
3599 String8(physicalMetadata.mPhysicalCameraId).c_str(), frameNumber);
3600 return;
3601 }
3602 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003603
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003604 // Fix up some result metadata to account for HAL-level distortion correction
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003605 status_t res =
3606 mDistortionMappers[mId.c_str()].correctCaptureResult(&captureResult.mMetadata);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003607 if (res != OK) {
3608 SET_ERR("Unable to correct capture result metadata for frame %d: %s (%d)",
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003609 frameNumber, strerror(-res), res);
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003610 return;
3611 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003612
3613 // Fix up result metadata to account for zoom ratio availabilities between
3614 // HAL and app.
3615 bool zoomRatioIs1 = cameraIdsWithZoom.find(mId.c_str()) == cameraIdsWithZoom.end();
3616 res = mZoomRatioMappers[mId.c_str()].updateCaptureResult(
3617 &captureResult.mMetadata, zoomRatioIs1);
3618 if (res != OK) {
3619 SET_ERR("Failed to update capture result zoom ratio metadata for frame %d: %s (%d)",
3620 frameNumber, strerror(-res), res);
3621 return;
3622 }
3623
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003624 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3625 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003626 if (mDistortionMappers.find(cameraId8.c_str()) != mDistortionMappers.end()) {
3627 res = mDistortionMappers[cameraId8.c_str()].correctCaptureResult(
3628 &physicalMetadata.mPhysicalCameraMetadata);
3629 if (res != OK) {
3630 SET_ERR("Unable to correct physical capture result metadata for frame %d: %s (%d)",
3631 frameNumber, strerror(-res), res);
3632 return;
3633 }
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003634 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003635
3636 zoomRatioIs1 = cameraIdsWithZoom.find(cameraId8.c_str()) == cameraIdsWithZoom.end();
3637 res = mZoomRatioMappers[cameraId8.c_str()].updateCaptureResult(
3638 &physicalMetadata.mPhysicalCameraMetadata, zoomRatioIs1);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003639 if (res != OK) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003640 SET_ERR("Failed to update camera %s's physical zoom ratio metadata for "
3641 "frame %d: %s(%d)", cameraId8.c_str(), frameNumber, strerror(-res), res);
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07003642 return;
3643 }
3644 }
3645
Shuzhen Wang268a1362018-10-16 16:32:59 -07003646 // Fix up result metadata for monochrome camera.
3647 res = fixupMonochromeTags(mDeviceInfo, captureResult.mMetadata);
3648 if (res != OK) {
3649 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3650 return;
3651 }
3652 for (auto& physicalMetadata : captureResult.mPhysicalMetadatas) {
3653 String8 cameraId8(physicalMetadata.mPhysicalCameraId);
3654 res = fixupMonochromeTags(mPhysicalDeviceInfoMap.at(cameraId8.c_str()),
3655 physicalMetadata.mPhysicalCameraMetadata);
3656 if (res != OK) {
3657 SET_ERR("Failed to override result metadata: %s (%d)", strerror(-res), res);
3658 return;
3659 }
3660 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07003661
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003662 std::unordered_map<std::string, CameraMetadata> monitoredPhysicalMetadata;
3663 for (auto& m : physicalMetadatas) {
3664 monitoredPhysicalMetadata.emplace(String8(m.mPhysicalCameraId).string(),
3665 CameraMetadata(m.mPhysicalCameraMetadata));
3666 }
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003667 mTagMonitor.monitorMetadata(TagMonitor::RESULT,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07003668 frameNumber, timestamp.data.i64[0], captureResult.mMetadata,
3669 monitoredPhysicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07003670
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003671 insertResultLocked(&captureResult, frameNumber);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003672}
3673
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003674/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08003675 * Camera HAL device callback methods
3676 */
3677
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003678void Camera3Device::processCaptureResult(const camera3_capture_result *result) {
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003679 ATRACE_CALL();
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003680
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003681 status_t res;
3682
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003683 uint32_t frameNumber = result->frame_number;
Zhijun Hef0d962a2014-06-30 10:24:11 -07003684 if (result->result == NULL && result->num_output_buffers == 0 &&
3685 result->input_buffer == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003686 SET_ERR("No result data provided by HAL for frame %d",
3687 frameNumber);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003688 return;
3689 }
Zhijun He204e3292014-07-14 17:09:23 -07003690
Zhijun He204e3292014-07-14 17:09:23 -07003691 if (!mUsePartialResult &&
Zhijun He204e3292014-07-14 17:09:23 -07003692 result->result != NULL &&
3693 result->partial_result != 1) {
3694 SET_ERR("Result is malformed for frame %d: partial_result %u must be 1"
3695 " if partial result is not supported",
3696 frameNumber, result->partial_result);
3697 return;
3698 }
3699
3700 bool isPartialResult = false;
3701 CameraMetadata collectedPartialResult;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003702 bool hasInputBufferInRequest = false;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003703
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003704 // Get shutter timestamp and resultExtras from list of in-flight requests,
3705 // where it was added by the shutter notification for this frame. If the
3706 // shutter timestamp isn't received yet, append the output buffers to the
3707 // in-flight request and they will be returned when the shutter timestamp
3708 // arrives. Update the in-flight status and remove the in-flight entry if
3709 // all result data and shutter timestamp have been received.
3710 nsecs_t shutterTimestamp = 0;
3711
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003712 {
3713 Mutex::Autolock l(mInFlightLock);
3714 ssize_t idx = mInFlightMap.indexOfKey(frameNumber);
3715 if (idx == NAME_NOT_FOUND) {
3716 SET_ERR("Unknown frame number for capture result: %d",
3717 frameNumber);
3718 return;
3719 }
3720 InFlightRequest &request = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003721 ALOGVV("%s: got InFlightRequest requestId = %" PRId32
3722 ", frameNumber = %" PRId64 ", burstId = %" PRId32
Shuzhen Wang4a472662017-02-26 23:29:04 -08003723 ", partialResultCount = %d, hasCallback = %d",
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003724 __FUNCTION__, request.resultExtras.requestId,
3725 request.resultExtras.frameNumber, request.resultExtras.burstId,
Shuzhen Wang4a472662017-02-26 23:29:04 -08003726 result->partial_result, request.hasCallback);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003727 // Always update the partial count to the latest one if it's not 0
3728 // (buffers only). When framework aggregates adjacent partial results
3729 // into one, the latest partial count will be used.
3730 if (result->partial_result != 0)
3731 request.resultExtras.partialResultCount = result->partial_result;
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003732
3733 // Check if this result carries only partial metadata
Zhijun He204e3292014-07-14 17:09:23 -07003734 if (mUsePartialResult && result->result != NULL) {
Emilian Peev08dd2452017-04-06 16:55:14 +01003735 if (result->partial_result > mNumPartialResults || result->partial_result < 1) {
3736 SET_ERR("Result is malformed for frame %d: partial_result %u must be in"
3737 " the range of [1, %d] when metadata is included in the result",
3738 frameNumber, result->partial_result, mNumPartialResults);
3739 return;
3740 }
3741 isPartialResult = (result->partial_result < mNumPartialResults);
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003742 if (isPartialResult && result->num_physcam_metadata) {
3743 SET_ERR("Result is malformed for frame %d: partial_result not allowed for"
3744 " physical camera result", frameNumber);
3745 return;
3746 }
Emilian Peev08dd2452017-04-06 16:55:14 +01003747 if (isPartialResult) {
3748 request.collectedPartialResult.append(result->result);
Zhijun He204e3292014-07-14 17:09:23 -07003749 }
3750
Shuzhen Wang4a472662017-02-26 23:29:04 -08003751 if (isPartialResult && request.hasCallback) {
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003752 // Send partial capture result
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003753 sendPartialCaptureResult(result->result, request.resultExtras,
3754 frameNumber);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003755 }
3756 }
3757
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003758 shutterTimestamp = request.shutterTimestamp;
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003759 hasInputBufferInRequest = request.hasInputBuffer;
Jianing Weicb0652e2014-03-12 18:29:36 -07003760
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003761 // Did we get the (final) result metadata for this capture?
Zhijun He204e3292014-07-14 17:09:23 -07003762 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003763 if (request.physicalCameraIds.size() != result->num_physcam_metadata) {
Shuzhen Wang468dbb82019-07-31 11:35:33 -07003764 SET_ERR("Expected physical Camera metadata count %d not equal to actual count %d",
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003765 request.physicalCameraIds.size(), result->num_physcam_metadata);
3766 return;
3767 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003768 if (request.haveResultMetadata) {
3769 SET_ERR("Called multiple times with metadata for frame %d",
3770 frameNumber);
3771 return;
3772 }
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003773 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3774 String8 physicalId(result->physcam_ids[i]);
3775 std::set<String8>::iterator cameraIdIter =
3776 request.physicalCameraIds.find(physicalId);
3777 if (cameraIdIter != request.physicalCameraIds.end()) {
3778 request.physicalCameraIds.erase(cameraIdIter);
3779 } else {
3780 SET_ERR("Total result for frame %d has already returned for camera %s",
3781 frameNumber, physicalId.c_str());
3782 return;
3783 }
3784 }
Zhijun He204e3292014-07-14 17:09:23 -07003785 if (mUsePartialResult &&
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003786 !request.collectedPartialResult.isEmpty()) {
Zhijun He204e3292014-07-14 17:09:23 -07003787 collectedPartialResult.acquire(
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003788 request.collectedPartialResult);
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003789 }
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003790 request.haveResultMetadata = true;
3791 }
3792
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003793 uint32_t numBuffersReturned = result->num_output_buffers;
3794 if (result->input_buffer != NULL) {
3795 if (hasInputBufferInRequest) {
3796 numBuffersReturned += 1;
3797 } else {
3798 ALOGW("%s: Input buffer should be NULL if there is no input"
3799 " buffer sent in the request",
3800 __FUNCTION__);
3801 }
3802 }
3803 request.numBuffersLeft -= numBuffersReturned;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003804 if (request.numBuffersLeft < 0) {
3805 SET_ERR("Too many buffers returned for frame %d",
3806 frameNumber);
3807 return;
3808 }
3809
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003810 camera_metadata_ro_entry_t entry;
3811 res = find_camera_metadata_ro_entry(result->result,
3812 ANDROID_SENSOR_TIMESTAMP, &entry);
3813 if (res == OK && entry.count == 1) {
3814 request.sensorTimestamp = entry.data.i64[0];
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003815 }
3816
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003817 // If shutter event isn't received yet, append the output buffers to
3818 // the in-flight request. Otherwise, return the output buffers to
3819 // streams.
3820 if (shutterTimestamp == 0) {
3821 request.pendingOutputBuffers.appendArray(result->output_buffers,
3822 result->num_output_buffers);
Igor Murashkind2c90692013-04-02 12:32:32 -07003823 } else {
Shuzhen Wang26abaf42018-08-28 15:41:20 -07003824 bool timestampIncreasing = !(request.zslCapture || request.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003825 returnOutputBuffers(result->output_buffers,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003826 result->num_output_buffers, shutterTimestamp, timestampIncreasing,
3827 request.outputSurfaces, request.resultExtras);
Igor Murashkind2c90692013-04-02 12:32:32 -07003828 }
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003829
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003830 if (result->result != NULL && !isPartialResult) {
Shuzhen Wang5c22c152017-12-31 17:12:25 -08003831 for (uint32_t i = 0; i < result->num_physcam_metadata; i++) {
3832 CameraMetadata physicalMetadata;
3833 physicalMetadata.append(result->physcam_metadata[i]);
3834 request.physicalMetadatas.push_back({String16(result->physcam_ids[i]),
3835 physicalMetadata});
3836 }
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003837 if (shutterTimestamp == 0) {
3838 request.pendingMetadata = result->result;
Chien-Yu Chen5cd8d642016-03-08 14:46:58 -08003839 request.collectedPartialResult = collectedPartialResult;
Shuzhen Wang268a1362018-10-16 16:32:59 -07003840 } else if (request.hasCallback) {
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003841 CameraMetadata metadata;
3842 metadata = result->result;
3843 sendCaptureResult(metadata, request.resultExtras,
Emilian Peev7e25e5e2017-04-07 15:48:49 +01003844 collectedPartialResult, frameNumber,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07003845 hasInputBufferInRequest, request.zslCapture && request.stillCapture,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08003846 request.cameraIdsWithZoom, request.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003847 }
Eino-Ville Talvalafd6ecdd2013-10-11 09:51:09 -07003848 }
3849
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08003850 removeInFlightRequestIfReadyLocked(idx);
3851 } // scope for mInFlightLock
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003852
Zhijun Hef0d962a2014-06-30 10:24:11 -07003853 if (result->input_buffer != NULL) {
Zhijun Hec98bd8d2014-07-07 12:44:10 -07003854 if (hasInputBufferInRequest) {
3855 Camera3Stream *stream =
3856 Camera3Stream::cast(result->input_buffer->stream);
3857 res = stream->returnInputBuffer(*(result->input_buffer));
3858 // Note: stream may be deallocated at this point, if this buffer was the
3859 // last reference to it.
3860 if (res != OK) {
3861 ALOGE("%s: RequestThread: Can't return input buffer for frame %d to"
3862 " its stream:%s (%d)", __FUNCTION__,
3863 frameNumber, strerror(-res), res);
Zhijun He0ea8fa42014-07-07 17:05:38 -07003864 }
3865 } else {
3866 ALOGW("%s: Input buffer should be NULL if there is no input"
3867 " buffer sent in the request, skipping input buffer return.",
3868 __FUNCTION__);
Zhijun Hef0d962a2014-06-30 10:24:11 -07003869 }
3870 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003871}
3872
3873void Camera3Device::notify(const camera3_notify_msg *msg) {
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07003874 ATRACE_CALL();
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003875 sp<NotificationListener> listener;
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003876 {
3877 Mutex::Autolock l(mOutputLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003878 listener = mListener.promote();
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003879 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003880
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003881 if (msg == NULL) {
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003882 SET_ERR("HAL sent NULL notify message!");
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003883 return;
3884 }
3885
3886 switch (msg->type) {
3887 case CAMERA3_MSG_ERROR: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003888 notifyError(msg->message.error, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003889 break;
3890 }
3891 case CAMERA3_MSG_SHUTTER: {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003892 notifyShutter(msg->message.shutter, listener);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003893 break;
3894 }
3895 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07003896 SET_ERR("Unknown notify message from HAL: %d",
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07003897 msg->type);
Eino-Ville Talvala7d346fa2013-03-11 14:13:50 -07003898 }
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08003899}
3900
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003901void Camera3Device::notifyError(const camera3_error_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07003902 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07003903 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003904 // Map camera HAL error codes to ICameraDeviceCallback error codes
3905 // Index into this with the HAL error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003906 static const int32_t halErrorMap[CAMERA3_MSG_NUM_ERRORS] = {
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003907 // 0 = Unused error code
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003908 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003909 // 1 = CAMERA3_MSG_ERROR_DEVICE
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003910 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003911 // 2 = CAMERA3_MSG_ERROR_REQUEST
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003912 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003913 // 3 = CAMERA3_MSG_ERROR_RESULT
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003914 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003915 // 4 = CAMERA3_MSG_ERROR_BUFFER
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003916 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003917 };
3918
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003919 int32_t errorCode =
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003920 ((msg.error_code >= 0) &&
3921 (msg.error_code < CAMERA3_MSG_NUM_ERRORS)) ?
3922 halErrorMap[msg.error_code] :
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003923 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_INVALID_ERROR;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003924
3925 int streamId = 0;
Emilian Peevedec62d2019-03-19 17:59:24 -07003926 String16 physicalCameraId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003927 if (msg.error_stream != NULL) {
3928 Camera3Stream *stream =
3929 Camera3Stream::cast(msg.error_stream);
3930 streamId = stream->getId();
Emilian Peevedec62d2019-03-19 17:59:24 -07003931 physicalCameraId = String16(stream->physicalCameraId());
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003932 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003933 ALOGV("Camera %s: %s: HAL error, frame %d, stream %d: %d",
3934 mId.string(), __FUNCTION__, msg.frame_number,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003935 streamId, msg.error_code);
3936
3937 CaptureResultExtras resultExtras;
3938 switch (errorCode) {
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003939 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_DEVICE:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003940 // SET_ERR calls notifyError
3941 SET_ERR("Camera HAL reported serious device error");
3942 break;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08003943 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST:
3944 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT:
3945 case hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_BUFFER:
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003946 {
3947 Mutex::Autolock l(mInFlightLock);
3948 ssize_t idx = mInFlightMap.indexOfKey(msg.frame_number);
3949 if (idx >= 0) {
3950 InFlightRequest &r = mInFlightMap.editValueAt(idx);
3951 r.requestStatus = msg.error_code;
3952 resultExtras = r.resultExtras;
Emilian Peevedec62d2019-03-19 17:59:24 -07003953 bool logicalDeviceResultError = false;
3954 if (hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_RESULT ==
3955 errorCode) {
3956 if (physicalCameraId.size() > 0) {
3957 String8 cameraId(physicalCameraId);
Shuzhen Wang468dbb82019-07-31 11:35:33 -07003958 auto iter = r.physicalCameraIds.find(cameraId);
3959 if (iter == r.physicalCameraIds.end()) {
Emilian Peevedec62d2019-03-19 17:59:24 -07003960 ALOGE("%s: Reported result failure for physical camera device: %s "
3961 " which is not part of the respective request!",
3962 __FUNCTION__, cameraId.string());
3963 break;
3964 }
Shuzhen Wang468dbb82019-07-31 11:35:33 -07003965 r.physicalCameraIds.erase(iter);
Emilian Peevedec62d2019-03-19 17:59:24 -07003966 resultExtras.errorPhysicalCameraId = physicalCameraId;
3967 } else {
3968 logicalDeviceResultError = true;
3969 }
3970 }
3971
3972 if (logicalDeviceResultError
Shuzhen Wang20f57342017-08-24 15:39:05 -07003973 || hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST ==
3974 errorCode) {
3975 r.skipResultMetadata = true;
3976 }
Emilian Peevedec62d2019-03-19 17:59:24 -07003977 if (logicalDeviceResultError) {
Emilian Peevba0fac32017-03-30 09:05:34 +01003978 // In case of missing result check whether the buffers
3979 // returned. If they returned, then remove inflight
3980 // request.
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07003981 // TODO: should we call this for ERROR_CAMERA_REQUEST as well?
3982 // otherwise we are depending on HAL to send the buffers back after
3983 // calling notifyError. Not sure if that's in the spec.
Emilian Peevba0fac32017-03-30 09:05:34 +01003984 removeInFlightRequestIfReadyLocked(idx);
3985 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003986 } else {
3987 resultExtras.frameNumber = msg.frame_number;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003988 ALOGE("Camera %s: %s: cannot find in-flight request on "
3989 "frame %" PRId64 " error", mId.string(), __FUNCTION__,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003990 resultExtras.frameNumber);
3991 }
3992 }
Eino-Ville Talvalae95bb632016-03-06 19:55:44 -08003993 resultExtras.errorStreamId = streamId;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003994 if (listener != NULL) {
3995 listener->notifyError(errorCode, resultExtras);
3996 } else {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08003997 ALOGE("Camera %s: %s: no listener available", mId.string(), __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07003998 }
3999 break;
4000 default:
4001 // SET_ERR calls notifyError
4002 SET_ERR("Unknown error message from HAL: %d", msg.error_code);
4003 break;
4004 }
4005}
4006
4007void Camera3Device::notifyShutter(const camera3_shutter_msg_t &msg,
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07004008 sp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004009 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004010 ssize_t idx;
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004011
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004012 // Set timestamp for the request in the in-flight tracking
4013 // and get the request ID to send upstream
4014 {
4015 Mutex::Autolock l(mInFlightLock);
4016 idx = mInFlightMap.indexOfKey(msg.frame_number);
4017 if (idx >= 0) {
4018 InFlightRequest &r = mInFlightMap.editValueAt(idx);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004019
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07004020 // Verify ordering of shutter notifications
4021 {
4022 Mutex::Autolock l(mOutputLock);
4023 // TODO: need to track errors for tighter bounds on expected frame number.
4024 if (r.hasInputBuffer) {
4025 if (msg.frame_number < mNextReprocessShutterFrameNumber) {
Shuzhen Wang5ee99842019-04-12 11:55:48 -07004026 SET_ERR("Reprocess shutter notification out-of-order. Expected "
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07004027 "notification for frame %d, got frame %d",
4028 mNextReprocessShutterFrameNumber, msg.frame_number);
4029 return;
4030 }
4031 mNextReprocessShutterFrameNumber = msg.frame_number + 1;
Shuzhen Wang5ee99842019-04-12 11:55:48 -07004032 } else if (r.zslCapture && r.stillCapture) {
4033 if (msg.frame_number < mNextZslStillShutterFrameNumber) {
4034 SET_ERR("ZSL still capture shutter notification out-of-order. Expected "
4035 "notification for frame %d, got frame %d",
4036 mNextZslStillShutterFrameNumber, msg.frame_number);
4037 return;
4038 }
4039 mNextZslStillShutterFrameNumber = msg.frame_number + 1;
Chien-Yu Chen3df11ce2015-09-30 14:13:30 -07004040 } else {
4041 if (msg.frame_number < mNextShutterFrameNumber) {
4042 SET_ERR("Shutter notification out-of-order. Expected "
4043 "notification for frame %d, got frame %d",
4044 mNextShutterFrameNumber, msg.frame_number);
4045 return;
4046 }
4047 mNextShutterFrameNumber = msg.frame_number + 1;
4048 }
4049 }
4050
Shuzhen Wang4a472662017-02-26 23:29:04 -08004051 r.shutterTimestamp = msg.timestamp;
4052 if (r.hasCallback) {
4053 ALOGVV("Camera %s: %s: Shutter fired for frame %d (id %d) at %" PRId64,
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004054 mId.string(), __FUNCTION__,
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004055 msg.frame_number, r.resultExtras.requestId, msg.timestamp);
Shuzhen Wang4a472662017-02-26 23:29:04 -08004056 // Call listener, if any
4057 if (listener != NULL) {
4058 listener->notifyShutter(r.resultExtras, msg.timestamp);
4059 }
4060 // send pending result and buffers
4061 sendCaptureResult(r.pendingMetadata, r.resultExtras,
4062 r.collectedPartialResult, msg.frame_number,
Shuzhen Wang5ee99842019-04-12 11:55:48 -07004063 r.hasInputBuffer, r.zslCapture && r.stillCapture,
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08004064 r.cameraIdsWithZoom, r.physicalMetadatas);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004065 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07004066 bool timestampIncreasing = !(r.zslCapture || r.hasInputBuffer);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004067 returnOutputBuffers(r.pendingOutputBuffers.array(),
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07004068 r.pendingOutputBuffers.size(), r.shutterTimestamp, timestampIncreasing,
4069 r.outputSurfaces, r.resultExtras);
Chien-Yu Chen43e69a62014-11-25 16:38:33 -08004070 r.pendingOutputBuffers.clear();
4071
4072 removeInFlightRequestIfReadyLocked(idx);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004073 }
4074 }
4075 if (idx < 0) {
4076 SET_ERR("Shutter notification for non-existent frame number %d",
4077 msg.frame_number);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07004078 }
4079}
4080
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07004081CameraMetadata Camera3Device::getLatestRequestLocked() {
Igor Murashkin1e479c02013-09-06 16:55:14 -07004082 ALOGV("%s", __FUNCTION__);
4083
Igor Murashkin1e479c02013-09-06 16:55:14 -07004084 CameraMetadata retVal;
4085
4086 if (mRequestThread != NULL) {
4087 retVal = mRequestThread->getLatestRequest();
4088 }
4089
Igor Murashkin1e479c02013-09-06 16:55:14 -07004090 return retVal;
4091}
4092
Jianing Weicb0652e2014-03-12 18:29:36 -07004093
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004094void Camera3Device::monitorMetadata(TagMonitor::eventSource source,
Shuzhen Wangc2cba122018-05-17 18:10:24 -07004095 int64_t frameNumber, nsecs_t timestamp, const CameraMetadata& metadata,
4096 const std::unordered_map<std::string, CameraMetadata>& physicalMetadata) {
4097
4098 mTagMonitor.monitorMetadata(source, frameNumber, timestamp, metadata,
4099 physicalMetadata);
Eino-Ville Talvala4d453832016-07-15 11:56:53 -07004100}
4101
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08004102/**
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004103 * HalInterface inner class methods
4104 */
4105
Yifan Hongf79b5542017-04-11 14:44:25 -07004106Camera3Device::HalInterface::HalInterface(
4107 sp<ICameraDeviceSession> &session,
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004108 std::shared_ptr<RequestMetadataQueue> queue,
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004109 bool useHalBufManager, bool supportOfflineProcessing) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004110 mHidlSession(session),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004111 mRequestMetadataQueue(queue),
Emilian Peev4ec17882019-01-24 17:16:58 -08004112 mUseHalBufManager(useHalBufManager),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004113 mIsReconfigurationQuerySupported(true),
4114 mSupportOfflineProcessing(supportOfflineProcessing) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004115 // Check with hardware service manager if we can downcast these interfaces
4116 // Somewhat expensive, so cache the results at startup
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004117 auto castResult_3_6 = device::V3_6::ICameraDeviceSession::castFrom(mHidlSession);
4118 if (castResult_3_6.isOk()) {
4119 mHidlSession_3_6 = castResult_3_6;
4120 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004121 auto castResult_3_5 = device::V3_5::ICameraDeviceSession::castFrom(mHidlSession);
4122 if (castResult_3_5.isOk()) {
4123 mHidlSession_3_5 = castResult_3_5;
4124 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004125 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4126 if (castResult_3_4.isOk()) {
4127 mHidlSession_3_4 = castResult_3_4;
4128 }
4129 auto castResult_3_3 = device::V3_3::ICameraDeviceSession::castFrom(mHidlSession);
4130 if (castResult_3_3.isOk()) {
4131 mHidlSession_3_3 = castResult_3_3;
4132 }
4133}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004134
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004135Camera3Device::HalInterface::HalInterface() :
4136 mUseHalBufManager(false),
4137 mSupportOfflineProcessing(false) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004138
4139Camera3Device::HalInterface::HalInterface(const HalInterface& other) :
Yifan Hongf79b5542017-04-11 14:44:25 -07004140 mHidlSession(other.mHidlSession),
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004141 mRequestMetadataQueue(other.mRequestMetadataQueue),
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004142 mUseHalBufManager(other.mUseHalBufManager),
4143 mSupportOfflineProcessing(other.mSupportOfflineProcessing) {}
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004144
4145bool Camera3Device::HalInterface::valid() {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004146 return (mHidlSession != nullptr);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004147}
4148
4149void Camera3Device::HalInterface::clear() {
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004150 mHidlSession_3_6.clear();
Emilian Peev644a3e12018-11-23 13:52:39 +00004151 mHidlSession_3_5.clear();
Emilian Peev9e740b02018-01-30 18:28:03 +00004152 mHidlSession_3_4.clear();
4153 mHidlSession_3_3.clear();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004154 mHidlSession.clear();
4155}
4156
4157status_t Camera3Device::HalInterface::constructDefaultRequestSettings(
4158 camera3_request_template_t templateId,
4159 /*out*/ camera_metadata_t **requestTemplate) {
4160 ATRACE_NAME("CameraHal::constructDefaultRequestSettings");
4161 if (!valid()) return INVALID_OPERATION;
4162 status_t res = OK;
4163
Emilian Peev31abd0a2017-05-11 18:37:46 +01004164 common::V1_0::Status status;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004165
4166 auto requestCallback = [&status, &requestTemplate]
Emilian Peev31abd0a2017-05-11 18:37:46 +01004167 (common::V1_0::Status s, const device::V3_2::CameraMetadata& request) {
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004168 status = s;
4169 if (status == common::V1_0::Status::OK) {
4170 const camera_metadata *r =
4171 reinterpret_cast<const camera_metadata_t*>(request.data());
4172 size_t expectedSize = request.size();
4173 int ret = validate_camera_metadata_structure(r, &expectedSize);
4174 if (ret == OK || ret == CAMERA_METADATA_VALIDATION_SHIFTED) {
4175 *requestTemplate = clone_camera_metadata(r);
4176 if (*requestTemplate == nullptr) {
4177 ALOGE("%s: Unable to clone camera metadata received from HAL",
4178 __FUNCTION__);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004179 status = common::V1_0::Status::INTERNAL_ERROR;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004180 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004181 } else {
4182 ALOGE("%s: Malformed camera metadata received from HAL", __FUNCTION__);
4183 status = common::V1_0::Status::INTERNAL_ERROR;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004184 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004185 }
4186 };
4187 hardware::Return<void> err;
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004188 RequestTemplate id;
4189 switch (templateId) {
4190 case CAMERA3_TEMPLATE_PREVIEW:
4191 id = RequestTemplate::PREVIEW;
4192 break;
4193 case CAMERA3_TEMPLATE_STILL_CAPTURE:
4194 id = RequestTemplate::STILL_CAPTURE;
4195 break;
4196 case CAMERA3_TEMPLATE_VIDEO_RECORD:
4197 id = RequestTemplate::VIDEO_RECORD;
4198 break;
4199 case CAMERA3_TEMPLATE_VIDEO_SNAPSHOT:
4200 id = RequestTemplate::VIDEO_SNAPSHOT;
4201 break;
4202 case CAMERA3_TEMPLATE_ZERO_SHUTTER_LAG:
4203 id = RequestTemplate::ZERO_SHUTTER_LAG;
4204 break;
4205 case CAMERA3_TEMPLATE_MANUAL:
4206 id = RequestTemplate::MANUAL;
4207 break;
4208 default:
4209 // Unknown template ID, or this HAL is too old to support it
4210 return BAD_VALUE;
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004211 }
Eino-Ville Talvala96441462018-02-06 11:41:55 -08004212 err = mHidlSession->constructDefaultRequestSettings(id, requestCallback);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004213
Emilian Peev31abd0a2017-05-11 18:37:46 +01004214 if (!err.isOk()) {
4215 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4216 res = DEAD_OBJECT;
4217 } else {
4218 res = CameraProviderManager::mapToStatusT(status);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004219 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004220
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004221 return res;
4222}
4223
Emilian Peev4ec17882019-01-24 17:16:58 -08004224bool Camera3Device::HalInterface::isReconfigurationRequired(CameraMetadata& oldSessionParams,
4225 CameraMetadata& newSessionParams) {
4226 // We do reconfiguration by default;
4227 bool ret = true;
4228 if ((mHidlSession_3_5 != nullptr) && mIsReconfigurationQuerySupported) {
4229 android::hardware::hidl_vec<uint8_t> oldParams, newParams;
4230 camera_metadata_t* oldSessioMeta = const_cast<camera_metadata_t*>(
4231 oldSessionParams.getAndLock());
4232 camera_metadata_t* newSessioMeta = const_cast<camera_metadata_t*>(
4233 newSessionParams.getAndLock());
4234 oldParams.setToExternal(reinterpret_cast<uint8_t*>(oldSessioMeta),
4235 get_camera_metadata_size(oldSessioMeta));
4236 newParams.setToExternal(reinterpret_cast<uint8_t*>(newSessioMeta),
4237 get_camera_metadata_size(newSessioMeta));
4238 hardware::camera::common::V1_0::Status callStatus;
4239 bool required;
4240 auto hidlCb = [&callStatus, &required] (hardware::camera::common::V1_0::Status s,
4241 bool requiredFlag) {
4242 callStatus = s;
4243 required = requiredFlag;
4244 };
4245 auto err = mHidlSession_3_5->isReconfigurationRequired(oldParams, newParams, hidlCb);
4246 oldSessionParams.unlock(oldSessioMeta);
4247 newSessionParams.unlock(newSessioMeta);
4248 if (err.isOk()) {
4249 switch (callStatus) {
4250 case hardware::camera::common::V1_0::Status::OK:
4251 ret = required;
4252 break;
4253 case hardware::camera::common::V1_0::Status::METHOD_NOT_SUPPORTED:
4254 mIsReconfigurationQuerySupported = false;
4255 ret = true;
4256 break;
4257 default:
4258 ALOGV("%s: Reconfiguration query failed: %d", __FUNCTION__, callStatus);
4259 ret = true;
4260 }
4261 } else {
4262 ALOGE("%s: Unexpected binder error: %s", __FUNCTION__, err.description().c_str());
4263 ret = true;
4264 }
4265 }
4266
4267 return ret;
4268}
4269
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004270status_t Camera3Device::HalInterface::configureStreams(const camera_metadata_t *sessionParams,
Emilian Peev192ee832018-01-31 14:46:47 +00004271 camera3_stream_configuration *config, const std::vector<uint32_t>& bufferSizes) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004272 ATRACE_NAME("CameraHal::configureStreams");
4273 if (!valid()) return INVALID_OPERATION;
4274 status_t res = OK;
4275
Emilian Peev31abd0a2017-05-11 18:37:46 +01004276 // Convert stream config to HIDL
4277 std::set<int> activeStreams;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004278 device::V3_2::StreamConfiguration requestedConfiguration3_2;
4279 device::V3_4::StreamConfiguration requestedConfiguration3_4;
4280 requestedConfiguration3_2.streams.resize(config->num_streams);
4281 requestedConfiguration3_4.streams.resize(config->num_streams);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004282 for (size_t i = 0; i < config->num_streams; i++) {
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004283 device::V3_2::Stream &dst3_2 = requestedConfiguration3_2.streams[i];
4284 device::V3_4::Stream &dst3_4 = requestedConfiguration3_4.streams[i];
Emilian Peev31abd0a2017-05-11 18:37:46 +01004285 camera3_stream_t *src = config->streams[i];
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004286
Emilian Peev31abd0a2017-05-11 18:37:46 +01004287 Camera3Stream* cam3stream = Camera3Stream::cast(src);
4288 cam3stream->setBufferFreedListener(this);
4289 int streamId = cam3stream->getId();
4290 StreamType streamType;
4291 switch (src->stream_type) {
4292 case CAMERA3_STREAM_OUTPUT:
4293 streamType = StreamType::OUTPUT;
4294 break;
4295 case CAMERA3_STREAM_INPUT:
4296 streamType = StreamType::INPUT;
4297 break;
4298 default:
4299 ALOGE("%s: Stream %d: Unsupported stream type %d",
4300 __FUNCTION__, streamId, config->streams[i]->stream_type);
4301 return BAD_VALUE;
4302 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004303 dst3_2.id = streamId;
4304 dst3_2.streamType = streamType;
4305 dst3_2.width = src->width;
4306 dst3_2.height = src->height;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004307 dst3_2.usage = mapToConsumerUsage(cam3stream->getUsage());
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004308 dst3_2.rotation = mapToStreamRotation((camera3_stream_rotation_t) src->rotation);
Shuzhen Wang92653952019-05-07 15:11:43 -07004309 // For HidlSession version 3.5 or newer, the format and dataSpace sent
4310 // to HAL are original, not the overriden ones.
4311 if (mHidlSession_3_5 != nullptr) {
4312 dst3_2.format = mapToPixelFormat(cam3stream->isFormatOverridden() ?
4313 cam3stream->getOriginalFormat() : src->format);
4314 dst3_2.dataSpace = mapToHidlDataspace(cam3stream->isDataSpaceOverridden() ?
4315 cam3stream->getOriginalDataSpace() : src->data_space);
4316 } else {
4317 dst3_2.format = mapToPixelFormat(src->format);
4318 dst3_2.dataSpace = mapToHidlDataspace(src->data_space);
4319 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004320 dst3_4.v3_2 = dst3_2;
Emilian Peev192ee832018-01-31 14:46:47 +00004321 dst3_4.bufferSize = bufferSizes[i];
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004322 if (src->physical_camera_id != nullptr) {
4323 dst3_4.physicalCameraId = src->physical_camera_id;
4324 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004325
4326 activeStreams.insert(streamId);
4327 // Create Buffer ID map if necessary
4328 if (mBufferIdMaps.count(streamId) == 0) {
4329 mBufferIdMaps.emplace(streamId, BufferIdMap{});
4330 }
4331 }
4332 // remove BufferIdMap for deleted streams
4333 for(auto it = mBufferIdMaps.begin(); it != mBufferIdMaps.end();) {
4334 int streamId = it->first;
4335 bool active = activeStreams.count(streamId) > 0;
4336 if (!active) {
4337 it = mBufferIdMaps.erase(it);
4338 } else {
4339 ++it;
4340 }
4341 }
4342
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004343 StreamConfigurationMode operationMode;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004344 res = mapToStreamConfigurationMode(
4345 (camera3_stream_configuration_mode_t) config->operation_mode,
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004346 /*out*/ &operationMode);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004347 if (res != OK) {
4348 return res;
4349 }
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004350 requestedConfiguration3_2.operationMode = operationMode;
4351 requestedConfiguration3_4.operationMode = operationMode;
4352 requestedConfiguration3_4.sessionParams.setToExternal(
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004353 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(sessionParams)),
4354 get_camera_metadata_size(sessionParams));
4355
Emilian Peev31abd0a2017-05-11 18:37:46 +01004356 // Invoke configureStreams
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004357 device::V3_3::HalStreamConfiguration finalConfiguration;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004358 device::V3_4::HalStreamConfiguration finalConfiguration3_4;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004359 common::V1_0::Status status;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004360
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004361 auto configStream34Cb = [&status, &finalConfiguration3_4]
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004362 (common::V1_0::Status s, const device::V3_4::HalStreamConfiguration& halConfiguration) {
4363 finalConfiguration3_4 = halConfiguration;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004364 status = s;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004365 };
4366
4367 auto postprocConfigStream34 = [&finalConfiguration, &finalConfiguration3_4]
4368 (hardware::Return<void>& err) -> status_t {
4369 if (!err.isOk()) {
4370 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4371 return DEAD_OBJECT;
4372 }
4373 finalConfiguration.streams.resize(finalConfiguration3_4.streams.size());
4374 for (size_t i = 0; i < finalConfiguration3_4.streams.size(); i++) {
4375 finalConfiguration.streams[i] = finalConfiguration3_4.streams[i].v3_3;
4376 }
4377 return OK;
4378 };
4379
Shuzhen Wang92653952019-05-07 15:11:43 -07004380 // See which version of HAL we have
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004381 if (mHidlSession_3_5 != nullptr) {
4382 ALOGV("%s: v3.5 device found", __FUNCTION__);
4383 device::V3_5::StreamConfiguration requestedConfiguration3_5;
4384 requestedConfiguration3_5.v3_4 = requestedConfiguration3_4;
4385 requestedConfiguration3_5.streamConfigCounter = mNextStreamConfigCounter++;
4386 auto err = mHidlSession_3_5->configureStreams_3_5(
4387 requestedConfiguration3_5, configStream34Cb);
4388 res = postprocConfigStream34(err);
4389 if (res != OK) {
4390 return res;
Emilian Peev5fbe0ba2017-10-20 15:45:45 +01004391 }
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004392 } else if (mHidlSession_3_4 != nullptr) {
4393 // We do; use v3.4 for the call
4394 ALOGV("%s: v3.4 device found", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004395 auto err = mHidlSession_3_4->configureStreams_3_4(
4396 requestedConfiguration3_4, configStream34Cb);
4397 res = postprocConfigStream34(err);
4398 if (res != OK) {
4399 return res;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004400 }
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004401 } else if (mHidlSession_3_3 != nullptr) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004402 // We do; use v3.3 for the call
4403 ALOGV("%s: v3.3 device found", __FUNCTION__);
Eino-Ville Talvala1a86df52018-01-17 16:00:35 -08004404 auto err = mHidlSession_3_3->configureStreams_3_3(requestedConfiguration3_2,
Emilian Peev31abd0a2017-05-11 18:37:46 +01004405 [&status, &finalConfiguration]
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004406 (common::V1_0::Status s, const device::V3_3::HalStreamConfiguration& halConfiguration) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004407 finalConfiguration = halConfiguration;
4408 status = s;
4409 });
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004410 if (!err.isOk()) {
4411 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4412 return DEAD_OBJECT;
4413 }
4414 } else {
4415 // We don't; use v3.2 call and construct a v3.3 HalStreamConfiguration
4416 ALOGV("%s: v3.2 device found", __FUNCTION__);
4417 HalStreamConfiguration finalConfiguration_3_2;
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004418 auto err = mHidlSession->configureStreams(requestedConfiguration3_2,
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004419 [&status, &finalConfiguration_3_2]
4420 (common::V1_0::Status s, const HalStreamConfiguration& halConfiguration) {
4421 finalConfiguration_3_2 = halConfiguration;
4422 status = s;
4423 });
4424 if (!err.isOk()) {
4425 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4426 return DEAD_OBJECT;
4427 }
4428 finalConfiguration.streams.resize(finalConfiguration_3_2.streams.size());
4429 for (size_t i = 0; i < finalConfiguration_3_2.streams.size(); i++) {
4430 finalConfiguration.streams[i].v3_2 = finalConfiguration_3_2.streams[i];
4431 finalConfiguration.streams[i].overrideDataSpace =
Shuzhen Wangc28189a2017-11-27 23:05:10 -08004432 requestedConfiguration3_2.streams[i].dataSpace;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004433 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004434 }
4435
4436 if (status != common::V1_0::Status::OK ) {
4437 return CameraProviderManager::mapToStatusT(status);
4438 }
4439
4440 // And convert output stream configuration from HIDL
4441
4442 for (size_t i = 0; i < config->num_streams; i++) {
4443 camera3_stream_t *dst = config->streams[i];
4444 int streamId = Camera3Stream::cast(dst)->getId();
4445
4446 // Start scan at i, with the assumption that the stream order matches
4447 size_t realIdx = i;
4448 bool found = false;
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004449 size_t halStreamCount = finalConfiguration.streams.size();
4450 for (size_t idx = 0; idx < halStreamCount; idx++) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004451 if (finalConfiguration.streams[realIdx].v3_2.id == streamId) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004452 found = true;
4453 break;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004454 }
Eino-Ville Talvala370875f2019-04-12 12:40:27 -07004455 realIdx = (realIdx >= halStreamCount - 1) ? 0 : realIdx + 1;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004456 }
4457 if (!found) {
4458 ALOGE("%s: Stream %d not found in stream configuration response from HAL",
4459 __FUNCTION__, streamId);
4460 return INVALID_OPERATION;
4461 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004462 device::V3_3::HalStream &src = finalConfiguration.streams[realIdx];
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004463
Emilian Peev710c1422017-08-30 11:19:38 +01004464 Camera3Stream* dstStream = Camera3Stream::cast(dst);
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004465 int overrideFormat = mapToFrameworkFormat(src.v3_2.overrideFormat);
4466 android_dataspace overrideDataSpace = mapToFrameworkDataspace(src.overrideDataSpace);
4467
Yin-Chia Yeh90667662019-07-01 15:45:00 -07004468 if (dstStream->getOriginalFormat() != HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED) {
Shuzhen Wang92653952019-05-07 15:11:43 -07004469 dstStream->setFormatOverride(false);
4470 dstStream->setDataSpaceOverride(false);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004471 if (dst->format != overrideFormat) {
4472 ALOGE("%s: Stream %d: Format override not allowed for format 0x%x", __FUNCTION__,
4473 streamId, dst->format);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004474 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004475 if (dst->data_space != overrideDataSpace) {
4476 ALOGE("%s: Stream %d: DataSpace override not allowed for format 0x%x", __FUNCTION__,
4477 streamId, dst->format);
4478 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004479 } else {
Shuzhen Wang92653952019-05-07 15:11:43 -07004480 bool needFormatOverride =
4481 requestedConfiguration3_2.streams[i].format != src.v3_2.overrideFormat;
4482 bool needDataspaceOverride =
4483 requestedConfiguration3_2.streams[i].dataSpace != src.overrideDataSpace;
Emilian Peev31abd0a2017-05-11 18:37:46 +01004484 // Override allowed with IMPLEMENTATION_DEFINED
Shuzhen Wang92653952019-05-07 15:11:43 -07004485 dstStream->setFormatOverride(needFormatOverride);
4486 dstStream->setDataSpaceOverride(needDataspaceOverride);
Emilian Peev31abd0a2017-05-11 18:37:46 +01004487 dst->format = overrideFormat;
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004488 dst->data_space = overrideDataSpace;
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004489 }
4490
Emilian Peev31abd0a2017-05-11 18:37:46 +01004491 if (dst->stream_type == CAMERA3_STREAM_INPUT) {
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004492 if (src.v3_2.producerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004493 ALOGE("%s: Stream %d: INPUT streams must have 0 for producer usage",
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004494 __FUNCTION__, streamId);
4495 return INVALID_OPERATION;
4496 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004497 dstStream->setUsage(
4498 mapConsumerToFrameworkUsage(src.v3_2.consumerUsage));
Emilian Peev31abd0a2017-05-11 18:37:46 +01004499 } else {
4500 // OUTPUT
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004501 if (src.v3_2.consumerUsage != 0) {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004502 ALOGE("%s: Stream %d: OUTPUT streams must have 0 for consumer usage",
4503 __FUNCTION__, streamId);
4504 return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004505 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004506 dstStream->setUsage(
4507 mapProducerToFrameworkUsage(src.v3_2.producerUsage));
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004508 }
Eino-Ville Talvala91cd3f82017-08-21 16:12:50 -07004509 dst->max_buffers = src.v3_2.maxBuffers;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004510 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004511
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004512 return res;
4513}
4514
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004515status_t Camera3Device::HalInterface::wrapAsHidlRequest(camera3_capture_request_t* request,
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004516 /*out*/device::V3_2::CaptureRequest* captureRequest,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004517 /*out*/std::vector<native_handle_t*>* handlesCreated,
4518 /*out*/std::vector<std::pair<int32_t, int32_t>>* inflightBuffers) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07004519 ATRACE_CALL();
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004520 if (captureRequest == nullptr || handlesCreated == nullptr || inflightBuffers == nullptr) {
4521 ALOGE("%s: captureRequest (%p), handlesCreated (%p), and inflightBuffers(%p) "
4522 "must not be null", __FUNCTION__, captureRequest, handlesCreated, inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004523 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004524 }
4525
4526 captureRequest->frameNumber = request->frame_number;
Yifan Hongf79b5542017-04-11 14:44:25 -07004527
4528 captureRequest->fmqSettingsSize = 0;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004529
4530 {
4531 std::lock_guard<std::mutex> lock(mInflightLock);
4532 if (request->input_buffer != nullptr) {
4533 int32_t streamId = Camera3Stream::cast(request->input_buffer->stream)->getId();
4534 buffer_handle_t buf = *(request->input_buffer->buffer);
4535 auto pair = getBufferId(buf, streamId);
4536 bool isNewBuffer = pair.first;
4537 uint64_t bufferId = pair.second;
4538 captureRequest->inputBuffer.streamId = streamId;
4539 captureRequest->inputBuffer.bufferId = bufferId;
4540 captureRequest->inputBuffer.buffer = (isNewBuffer) ? buf : nullptr;
4541 captureRequest->inputBuffer.status = BufferStatus::OK;
4542 native_handle_t *acquireFence = nullptr;
4543 if (request->input_buffer->acquire_fence != -1) {
4544 acquireFence = native_handle_create(1,0);
4545 acquireFence->data[0] = request->input_buffer->acquire_fence;
4546 handlesCreated->push_back(acquireFence);
4547 }
4548 captureRequest->inputBuffer.acquireFence = acquireFence;
4549 captureRequest->inputBuffer.releaseFence = nullptr;
4550
4551 pushInflightBufferLocked(captureRequest->frameNumber, streamId,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004552 request->input_buffer->buffer);
4553 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004554 } else {
4555 captureRequest->inputBuffer.streamId = -1;
4556 captureRequest->inputBuffer.bufferId = BUFFER_ID_NO_BUFFER;
4557 }
4558
4559 captureRequest->outputBuffers.resize(request->num_output_buffers);
4560 for (size_t i = 0; i < request->num_output_buffers; i++) {
4561 const camera3_stream_buffer_t *src = request->output_buffers + i;
4562 StreamBuffer &dst = captureRequest->outputBuffers[i];
4563 int32_t streamId = Camera3Stream::cast(src->stream)->getId();
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004564 if (src->buffer != nullptr) {
4565 buffer_handle_t buf = *(src->buffer);
4566 auto pair = getBufferId(buf, streamId);
4567 bool isNewBuffer = pair.first;
4568 dst.bufferId = pair.second;
4569 dst.buffer = isNewBuffer ? buf : nullptr;
4570 native_handle_t *acquireFence = nullptr;
4571 if (src->acquire_fence != -1) {
4572 acquireFence = native_handle_create(1,0);
4573 acquireFence->data[0] = src->acquire_fence;
4574 handlesCreated->push_back(acquireFence);
4575 }
4576 dst.acquireFence = acquireFence;
4577 } else if (mUseHalBufManager) {
4578 // HAL buffer management path
4579 dst.bufferId = BUFFER_ID_NO_BUFFER;
4580 dst.buffer = nullptr;
4581 dst.acquireFence = nullptr;
4582 } else {
4583 ALOGE("%s: cannot send a null buffer in capture request!", __FUNCTION__);
4584 return BAD_VALUE;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004585 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004586 dst.streamId = streamId;
4587 dst.status = BufferStatus::OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004588 dst.releaseFence = nullptr;
4589
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004590 // Output buffers are empty when using HAL buffer manager
4591 if (!mUseHalBufManager) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004592 pushInflightBufferLocked(captureRequest->frameNumber, streamId, src->buffer);
4593 inflightBuffers->push_back(std::make_pair(captureRequest->frameNumber, streamId));
Yin-Chia Yeh5f840f82019-03-05 11:59:04 -08004594 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004595 }
4596 }
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004597 return OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004598}
4599
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004600void Camera3Device::HalInterface::cleanupNativeHandles(
4601 std::vector<native_handle_t*> *handles, bool closeFd) {
4602 if (handles == nullptr) {
4603 return;
4604 }
4605 if (closeFd) {
4606 for (auto& handle : *handles) {
4607 native_handle_close(handle);
4608 }
4609 }
4610 for (auto& handle : *handles) {
4611 native_handle_delete(handle);
4612 }
4613 handles->clear();
4614 return;
4615}
4616
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004617status_t Camera3Device::HalInterface::processBatchCaptureRequests(
4618 std::vector<camera3_capture_request_t*>& requests,/*out*/uint32_t* numRequestProcessed) {
4619 ATRACE_NAME("CameraHal::processBatchCaptureRequests");
4620 if (!valid()) return INVALID_OPERATION;
4621
Emilian Peevaebbe412018-01-15 13:53:24 +00004622 sp<device::V3_4::ICameraDeviceSession> hidlSession_3_4;
4623 auto castResult_3_4 = device::V3_4::ICameraDeviceSession::castFrom(mHidlSession);
4624 if (castResult_3_4.isOk()) {
4625 hidlSession_3_4 = castResult_3_4;
4626 }
4627
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004628 hardware::hidl_vec<device::V3_2::CaptureRequest> captureRequests;
Emilian Peevaebbe412018-01-15 13:53:24 +00004629 hardware::hidl_vec<device::V3_4::CaptureRequest> captureRequests_3_4;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004630 size_t batchSize = requests.size();
Emilian Peevaebbe412018-01-15 13:53:24 +00004631 if (hidlSession_3_4 != nullptr) {
4632 captureRequests_3_4.resize(batchSize);
4633 } else {
4634 captureRequests.resize(batchSize);
4635 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004636 std::vector<native_handle_t*> handlesCreated;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004637 std::vector<std::pair<int32_t, int32_t>> inflightBuffers;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004638
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004639 status_t res = OK;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004640 for (size_t i = 0; i < batchSize; i++) {
Emilian Peevaebbe412018-01-15 13:53:24 +00004641 if (hidlSession_3_4 != nullptr) {
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004642 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests_3_4[i].v3_2,
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004643 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Emilian Peevaebbe412018-01-15 13:53:24 +00004644 } else {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004645 res = wrapAsHidlRequest(requests[i], /*out*/&captureRequests[i],
4646 /*out*/&handlesCreated, /*out*/&inflightBuffers);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004647 }
4648 if (res != OK) {
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004649 popInflightBuffers(inflightBuffers);
4650 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh651fe2e2018-11-13 11:49:31 -08004651 return res;
Emilian Peevaebbe412018-01-15 13:53:24 +00004652 }
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004653 }
4654
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004655 std::vector<device::V3_2::BufferCache> cachesToRemove;
4656 {
4657 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4658 for (auto& pair : mFreedBuffers) {
4659 // The stream might have been removed since onBufferFreed
4660 if (mBufferIdMaps.find(pair.first) != mBufferIdMaps.end()) {
4661 cachesToRemove.push_back({pair.first, pair.second});
4662 }
4663 }
4664 mFreedBuffers.clear();
4665 }
4666
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004667 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4668 *numRequestProcessed = 0;
Yifan Hongf79b5542017-04-11 14:44:25 -07004669
4670 // Write metadata to FMQ.
4671 for (size_t i = 0; i < batchSize; i++) {
4672 camera3_capture_request_t* request = requests[i];
Emilian Peevaebbe412018-01-15 13:53:24 +00004673 device::V3_2::CaptureRequest* captureRequest;
4674 if (hidlSession_3_4 != nullptr) {
4675 captureRequest = &captureRequests_3_4[i].v3_2;
4676 } else {
4677 captureRequest = &captureRequests[i];
4678 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004679
4680 if (request->settings != nullptr) {
4681 size_t settingsSize = get_camera_metadata_size(request->settings);
4682 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4683 reinterpret_cast<const uint8_t*>(request->settings), settingsSize)) {
4684 captureRequest->settings.resize(0);
4685 captureRequest->fmqSettingsSize = settingsSize;
4686 } else {
4687 if (mRequestMetadataQueue != nullptr) {
4688 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4689 }
4690 captureRequest->settings.setToExternal(
4691 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(request->settings)),
4692 get_camera_metadata_size(request->settings));
4693 captureRequest->fmqSettingsSize = 0u;
4694 }
4695 } else {
4696 // A null request settings maps to a size-0 CameraMetadata
4697 captureRequest->settings.resize(0);
4698 captureRequest->fmqSettingsSize = 0u;
4699 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004700
4701 if (hidlSession_3_4 != nullptr) {
4702 captureRequests_3_4[i].physicalCameraSettings.resize(request->num_physcam_settings);
4703 for (size_t j = 0; j < request->num_physcam_settings; j++) {
Emilian Peev00420d22018-02-05 21:33:13 +00004704 if (request->physcam_settings != nullptr) {
4705 size_t settingsSize = get_camera_metadata_size(request->physcam_settings[j]);
4706 if (mRequestMetadataQueue != nullptr && mRequestMetadataQueue->write(
4707 reinterpret_cast<const uint8_t*>(request->physcam_settings[j]),
4708 settingsSize)) {
4709 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
4710 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize =
4711 settingsSize;
4712 } else {
4713 if (mRequestMetadataQueue != nullptr) {
4714 ALOGW("%s: couldn't utilize fmq, fallback to hwbinder", __FUNCTION__);
4715 }
4716 captureRequests_3_4[i].physicalCameraSettings[j].settings.setToExternal(
4717 reinterpret_cast<uint8_t*>(const_cast<camera_metadata_t*>(
4718 request->physcam_settings[j])),
4719 get_camera_metadata_size(request->physcam_settings[j]));
4720 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peevaebbe412018-01-15 13:53:24 +00004721 }
Emilian Peev00420d22018-02-05 21:33:13 +00004722 } else {
Emilian Peevaebbe412018-01-15 13:53:24 +00004723 captureRequests_3_4[i].physicalCameraSettings[j].fmqSettingsSize = 0u;
Emilian Peev00420d22018-02-05 21:33:13 +00004724 captureRequests_3_4[i].physicalCameraSettings[j].settings.resize(0);
Emilian Peevaebbe412018-01-15 13:53:24 +00004725 }
4726 captureRequests_3_4[i].physicalCameraSettings[j].physicalCameraId =
4727 request->physcam_id[j];
4728 }
4729 }
Yifan Hongf79b5542017-04-11 14:44:25 -07004730 }
Emilian Peevaebbe412018-01-15 13:53:24 +00004731
4732 hardware::details::return_status err;
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004733 auto resultCallback =
4734 [&status, &numRequestProcessed] (auto s, uint32_t n) {
4735 status = s;
4736 *numRequestProcessed = n;
4737 };
Emilian Peevaebbe412018-01-15 13:53:24 +00004738 if (hidlSession_3_4 != nullptr) {
4739 err = hidlSession_3_4->processCaptureRequest_3_4(captureRequests_3_4, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004740 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004741 } else {
4742 err = mHidlSession->processCaptureRequest(captureRequests, cachesToRemove,
Jayant Chowdharyc8d581e2018-07-16 14:46:23 -07004743 resultCallback);
Emilian Peevaebbe412018-01-15 13:53:24 +00004744 }
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004745 if (!err.isOk()) {
4746 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004747 status = common::V1_0::Status::CAMERA_DISCONNECTED;
Eino-Ville Talvalac5cbb872017-04-27 12:48:33 -07004748 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004749
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004750 if (status == common::V1_0::Status::OK && *numRequestProcessed != batchSize) {
4751 ALOGE("%s: processCaptureRequest returns OK but processed %d/%zu requests",
4752 __FUNCTION__, *numRequestProcessed, batchSize);
4753 status = common::V1_0::Status::INTERNAL_ERROR;
4754 }
4755
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004756 res = CameraProviderManager::mapToStatusT(status);
4757 if (res == OK) {
4758 if (mHidlSession->isRemote()) {
4759 // Only close acquire fence FDs when the HIDL transaction succeeds (so the FDs have been
4760 // sent to camera HAL processes)
4761 cleanupNativeHandles(&handlesCreated, /*closeFd*/true);
4762 } else {
4763 // In passthrough mode the FDs are now owned by HAL
4764 cleanupNativeHandles(&handlesCreated);
4765 }
4766 } else {
4767 popInflightBuffers(inflightBuffers);
4768 cleanupNativeHandles(&handlesCreated);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004769 }
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004770 return res;
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08004771}
4772
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004773status_t Camera3Device::HalInterface::flush() {
4774 ATRACE_NAME("CameraHal::flush");
4775 if (!valid()) return INVALID_OPERATION;
4776 status_t res = OK;
4777
Emilian Peev31abd0a2017-05-11 18:37:46 +01004778 auto err = mHidlSession->flush();
4779 if (!err.isOk()) {
4780 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4781 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004782 } else {
Emilian Peev31abd0a2017-05-11 18:37:46 +01004783 res = CameraProviderManager::mapToStatusT(err);
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004784 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004785
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004786 return res;
4787}
4788
Emilian Peev31abd0a2017-05-11 18:37:46 +01004789status_t Camera3Device::HalInterface::dump(int /*fd*/) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004790 ATRACE_NAME("CameraHal::dump");
4791 if (!valid()) return INVALID_OPERATION;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004792
Emilian Peev31abd0a2017-05-11 18:37:46 +01004793 // Handled by CameraProviderManager::dump
4794
4795 return OK;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004796}
4797
4798status_t Camera3Device::HalInterface::close() {
4799 ATRACE_NAME("CameraHal::close()");
4800 if (!valid()) return INVALID_OPERATION;
4801 status_t res = OK;
4802
Emilian Peev31abd0a2017-05-11 18:37:46 +01004803 auto err = mHidlSession->close();
4804 // Interface will be dead shortly anyway, so don't log errors
4805 if (!err.isOk()) {
4806 res = DEAD_OBJECT;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004807 }
Emilian Peev31abd0a2017-05-11 18:37:46 +01004808
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004809 return res;
4810}
4811
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004812void Camera3Device::HalInterface::signalPipelineDrain(const std::vector<int>& streamIds) {
4813 ATRACE_NAME("CameraHal::signalPipelineDrain");
4814 if (!valid() || mHidlSession_3_5 == nullptr) {
4815 ALOGE("%s called on invalid camera!", __FUNCTION__);
4816 return;
4817 }
4818
Yin-Chia Yehc300a072019-02-13 14:56:57 -08004819 auto err = mHidlSession_3_5->signalStreamFlush(streamIds, mNextStreamConfigCounter - 1);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07004820 if (!err.isOk()) {
4821 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4822 return;
4823 }
4824}
4825
Yin-Chia Yehb978c382019-10-30 00:22:37 -07004826status_t Camera3Device::HalInterface::switchToOffline(
4827 const std::vector<int32_t>& streamsToKeep,
4828 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
4829 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession) {
4830 ATRACE_NAME("CameraHal::switchToOffline");
4831 if (!valid() || mHidlSession_3_6 == nullptr) {
4832 ALOGE("%s called on invalid camera!", __FUNCTION__);
4833 return INVALID_OPERATION;
4834 }
4835
4836 if (offlineSessionInfo == nullptr || offlineSession == nullptr) {
4837 ALOGE("%s: offlineSessionInfo and offlineSession must not be null!", __FUNCTION__);
4838 return INVALID_OPERATION;
4839 }
4840
4841 common::V1_0::Status status = common::V1_0::Status::INTERNAL_ERROR;
4842
4843 auto resultCallback =
4844 [&status, &offlineSessionInfo, &offlineSession] (auto s, auto info, auto session) {
4845 status = s;
4846 *offlineSessionInfo = info;
4847 *offlineSession = session;
4848 };
4849 auto err = mHidlSession_3_6->switchToOffline(streamsToKeep, resultCallback);
4850
4851 if (!err.isOk()) {
4852 ALOGE("%s: Transaction error: %s", __FUNCTION__, err.description().c_str());
4853 return DEAD_OBJECT;
4854 }
4855 return CameraProviderManager::mapToStatusT(status);
4856}
4857
Yin-Chia Yehf3fe36f2017-07-07 18:23:18 -07004858void Camera3Device::HalInterface::getInflightBufferKeys(
4859 std::vector<std::pair<int32_t, int32_t>>* out) {
4860 std::lock_guard<std::mutex> lock(mInflightLock);
4861 out->clear();
4862 out->reserve(mInflightBufferMap.size());
4863 for (auto& pair : mInflightBufferMap) {
4864 uint64_t key = pair.first;
4865 int32_t streamId = key & 0xFFFFFFFF;
4866 int32_t frameNumber = (key >> 32) & 0xFFFFFFFF;
4867 out->push_back(std::make_pair(frameNumber, streamId));
4868 }
4869 return;
4870}
4871
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004872void Camera3Device::HalInterface::getInflightRequestBufferKeys(
4873 std::vector<uint64_t>* out) {
4874 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4875 out->clear();
4876 out->reserve(mRequestedBuffers.size());
4877 for (auto& pair : mRequestedBuffers) {
4878 out->push_back(pair.first);
4879 }
4880 return;
4881}
4882
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004883status_t Camera3Device::HalInterface::pushInflightBufferLocked(
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004884 int32_t frameNumber, int32_t streamId, buffer_handle_t *buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004885 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004886 mInflightBufferMap[key] = buffer;
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004887 return OK;
4888}
4889
4890status_t Camera3Device::HalInterface::popInflightBuffer(
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004891 int32_t frameNumber, int32_t streamId,
4892 /*out*/ buffer_handle_t **buffer) {
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004893 std::lock_guard<std::mutex> lock(mInflightLock);
4894
4895 uint64_t key = static_cast<uint64_t>(frameNumber) << 32 | static_cast<uint64_t>(streamId);
4896 auto it = mInflightBufferMap.find(key);
4897 if (it == mInflightBufferMap.end()) return NAME_NOT_FOUND;
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004898 if (buffer != nullptr) {
4899 *buffer = it->second;
Yin-Chia Yehf4650602017-01-10 13:13:39 -08004900 }
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08004901 mInflightBufferMap.erase(it);
4902 return OK;
4903}
4904
Yin-Chia Yehf8e28fb2019-05-16 11:46:54 -07004905void Camera3Device::HalInterface::popInflightBuffers(
4906 const std::vector<std::pair<int32_t, int32_t>>& buffers) {
4907 for (const auto& pair : buffers) {
4908 int32_t frameNumber = pair.first;
4909 int32_t streamId = pair.second;
4910 popInflightBuffer(frameNumber, streamId, nullptr);
4911 }
4912}
4913
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004914status_t Camera3Device::HalInterface::pushInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004915 uint64_t bufferId, buffer_handle_t* buf, int32_t streamId) {
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004916 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004917 auto pair = mRequestedBuffers.insert({bufferId, {streamId, buf}});
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004918 if (!pair.second) {
4919 ALOGE("%s: bufId %" PRIu64 " is already inflight!",
4920 __FUNCTION__, bufferId);
4921 return BAD_VALUE;
4922 }
4923 return OK;
4924}
4925
4926// Find and pop a buffer_handle_t based on bufferId
4927status_t Camera3Device::HalInterface::popInflightRequestBuffer(
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004928 uint64_t bufferId,
4929 /*out*/ buffer_handle_t** buffer,
4930 /*optional out*/ int32_t* streamId) {
4931 if (buffer == nullptr) {
4932 ALOGE("%s: buffer (%p) must not be null", __FUNCTION__, buffer);
4933 return BAD_VALUE;
4934 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004935 std::lock_guard<std::mutex> lock(mRequestedBuffersLock);
4936 auto it = mRequestedBuffers.find(bufferId);
4937 if (it == mRequestedBuffers.end()) {
4938 ALOGE("%s: bufId %" PRIu64 " is not inflight!",
4939 __FUNCTION__, bufferId);
4940 return BAD_VALUE;
4941 }
Yin-Chia Yeh84be5782019-03-01 11:47:02 -08004942 *buffer = it->second.second;
4943 if (streamId != nullptr) {
4944 *streamId = it->second.first;
4945 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07004946 mRequestedBuffers.erase(it);
4947 return OK;
4948}
4949
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004950std::pair<bool, uint64_t> Camera3Device::HalInterface::getBufferId(
4951 const buffer_handle_t& buf, int streamId) {
4952 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4953
4954 BufferIdMap& bIdMap = mBufferIdMaps.at(streamId);
4955 auto it = bIdMap.find(buf);
4956 if (it == bIdMap.end()) {
4957 bIdMap[buf] = mNextBufferId++;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004958 ALOGV("stream %d now have %zu buffer caches, buf %p",
4959 streamId, bIdMap.size(), buf);
Yin-Chia Yeh77327052017-01-09 18:23:07 -08004960 return std::make_pair(true, mNextBufferId - 1);
4961 } else {
4962 return std::make_pair(false, it->second);
4963 }
4964}
4965
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004966void Camera3Device::HalInterface::onBufferFreed(
4967 int streamId, const native_handle_t* handle) {
4968 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4969 uint64_t bufferId = BUFFER_ID_NO_BUFFER;
4970 auto mapIt = mBufferIdMaps.find(streamId);
4971 if (mapIt == mBufferIdMaps.end()) {
4972 // streamId might be from a deleted stream here
4973 ALOGI("%s: stream %d has been removed",
4974 __FUNCTION__, streamId);
4975 return;
4976 }
4977 BufferIdMap& bIdMap = mapIt->second;
4978 auto it = bIdMap.find(handle);
4979 if (it == bIdMap.end()) {
4980 ALOGW("%s: cannot find buffer %p in stream %d",
4981 __FUNCTION__, handle, streamId);
4982 return;
4983 } else {
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004984 bufferId = it->second;
Yin-Chia Yehbe83fa72017-03-30 13:35:36 -07004985 bIdMap.erase(it);
4986 ALOGV("%s: stream %d now have %zu buffer caches after removing buf %p",
4987 __FUNCTION__, streamId, bIdMap.size(), handle);
4988 }
4989 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
4990}
4991
Yin-Chia Yeh573a2702019-04-17 10:08:55 -07004992void Camera3Device::HalInterface::onStreamReConfigured(int streamId) {
4993 std::lock_guard<std::mutex> lock(mBufferIdMapLock);
4994 auto mapIt = mBufferIdMaps.find(streamId);
4995 if (mapIt == mBufferIdMaps.end()) {
4996 ALOGE("%s: streamId %d not found!", __FUNCTION__, streamId);
4997 return;
4998 }
4999
5000 BufferIdMap& bIdMap = mapIt->second;
5001 for (const auto& it : bIdMap) {
5002 uint64_t bufferId = it.second;
5003 mFreedBuffers.push_back(std::make_pair(streamId, bufferId));
5004 }
5005 bIdMap.clear();
5006}
5007
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08005008/**
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005009 * RequestThread inner class methods
5010 */
5011
5012Camera3Device::RequestThread::RequestThread(wp<Camera3Device> parent,
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005013 sp<StatusTracker> statusTracker,
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005014 sp<HalInterface> interface, const Vector<int32_t>& sessionParamKeys,
5015 bool useHalBufManager) :
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005016 Thread(/*canCallJava*/false),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005017 mParent(parent),
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005018 mStatusTracker(statusTracker),
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08005019 mInterface(interface),
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07005020 mListener(nullptr),
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005021 mId(getId(parent)),
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005022 mReconfigured(false),
5023 mDoPause(false),
5024 mPaused(true),
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07005025 mNotifyPipelineDrain(false),
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005026 mFrameNumber(0),
Jianing Weicb0652e2014-03-12 18:29:36 -07005027 mLatestRequestId(NAME_NOT_FOUND),
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07005028 mCurrentAfTriggerId(0),
5029 mCurrentPreCaptureTriggerId(0),
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005030 mRepeatingLastFrameNumber(
5031 hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES),
Shuzhen Wang686f6442017-06-20 16:16:04 -07005032 mPrepareVideoStream(false),
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005033 mConstrainedMode(false),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005034 mRequestLatency(kRequestLatencyBinSize),
5035 mSessionParamKeys(sessionParamKeys),
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005036 mLatestSessionParams(sessionParamKeys.size()),
5037 mUseHalBufManager(useHalBufManager) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005038 mStatusId = statusTracker->addComponent();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005039}
5040
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08005041Camera3Device::RequestThread::~RequestThread() {}
5042
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005043void Camera3Device::RequestThread::setNotificationListener(
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005044 wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005045 ATRACE_CALL();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005046 Mutex::Autolock l(mRequestLock);
5047 mListener = listener;
5048}
5049
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005050void Camera3Device::RequestThread::configurationComplete(bool isConstrainedHighSpeed,
5051 const CameraMetadata& sessionParams) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005052 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005053 Mutex::Autolock l(mRequestLock);
5054 mReconfigured = true;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005055 mLatestSessionParams = sessionParams;
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005056 // Prepare video stream for high speed recording.
5057 mPrepareVideoStream = isConstrainedHighSpeed;
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005058 mConstrainedMode = isConstrainedHighSpeed;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005059}
5060
Jianing Wei90e59c92014-03-12 18:29:36 -07005061status_t Camera3Device::RequestThread::queueRequestList(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005062 List<sp<CaptureRequest> > &requests,
5063 /*out*/
5064 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005065 ATRACE_CALL();
Jianing Wei90e59c92014-03-12 18:29:36 -07005066 Mutex::Autolock l(mRequestLock);
5067 for (List<sp<CaptureRequest> >::iterator it = requests.begin(); it != requests.end();
5068 ++it) {
5069 mRequestQueue.push_back(*it);
5070 }
5071
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005072 if (lastFrameNumber != NULL) {
5073 *lastFrameNumber = mFrameNumber + mRequestQueue.size() - 1;
5074 ALOGV("%s: requestId %d, mFrameNumber %" PRId32 ", lastFrameNumber %" PRId64 ".",
5075 __FUNCTION__, (*(requests.begin()))->mResultExtras.requestId, mFrameNumber,
5076 *lastFrameNumber);
5077 }
Jianing Weicb0652e2014-03-12 18:29:36 -07005078
Jianing Wei90e59c92014-03-12 18:29:36 -07005079 unpauseForNewRequests();
5080
5081 return OK;
5082}
5083
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005084
5085status_t Camera3Device::RequestThread::queueTrigger(
5086 RequestTrigger trigger[],
5087 size_t count) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005088 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005089 Mutex::Autolock l(mTriggerMutex);
5090 status_t ret;
5091
5092 for (size_t i = 0; i < count; ++i) {
5093 ret = queueTriggerLocked(trigger[i]);
5094
5095 if (ret != OK) {
5096 return ret;
5097 }
5098 }
5099
5100 return OK;
5101}
5102
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08005103const String8& Camera3Device::RequestThread::getId(const wp<Camera3Device> &device) {
5104 static String8 deadId("<DeadDevice>");
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005105 sp<Camera3Device> d = device.promote();
Eino-Ville Talvala0b1cb142016-12-19 16:29:17 -08005106 if (d != nullptr) return d->mId;
5107 return deadId;
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005108}
5109
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005110status_t Camera3Device::RequestThread::queueTriggerLocked(
5111 RequestTrigger trigger) {
5112
5113 uint32_t tag = trigger.metadataTag;
5114 ssize_t index = mTriggerMap.indexOfKey(tag);
5115
5116 switch (trigger.getTagType()) {
5117 case TYPE_BYTE:
5118 // fall-through
5119 case TYPE_INT32:
5120 break;
5121 default:
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005122 ALOGE("%s: Type not supported: 0x%x", __FUNCTION__,
5123 trigger.getTagType());
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005124 return INVALID_OPERATION;
5125 }
5126
5127 /**
5128 * Collect only the latest trigger, since we only have 1 field
5129 * in the request settings per trigger tag, and can't send more than 1
5130 * trigger per request.
5131 */
5132 if (index != NAME_NOT_FOUND) {
5133 mTriggerMap.editValueAt(index) = trigger;
5134 } else {
5135 mTriggerMap.add(tag, trigger);
5136 }
5137
5138 return OK;
5139}
5140
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005141status_t Camera3Device::RequestThread::setRepeatingRequests(
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005142 const RequestList &requests,
5143 /*out*/
5144 int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005145 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005146 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005147 if (lastFrameNumber != NULL) {
5148 *lastFrameNumber = mRepeatingLastFrameNumber;
5149 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005150 mRepeatingRequests.clear();
5151 mRepeatingRequests.insert(mRepeatingRequests.begin(),
5152 requests.begin(), requests.end());
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07005153
5154 unpauseForNewRequests();
5155
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005156 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005157 return OK;
5158}
5159
Chih-Hung Hsieh8b0b9712016-08-09 14:25:53 -07005160bool Camera3Device::RequestThread::isRepeatingRequestLocked(const sp<CaptureRequest>& requestIn) {
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005161 if (mRepeatingRequests.empty()) {
5162 return false;
5163 }
5164 int32_t requestId = requestIn->mResultExtras.requestId;
5165 const RequestList &repeatRequests = mRepeatingRequests;
5166 // All repeating requests are guaranteed to have same id so only check first quest
5167 const sp<CaptureRequest> firstRequest = *repeatRequests.begin();
5168 return (firstRequest->mResultExtras.requestId == requestId);
5169}
5170
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005171status_t Camera3Device::RequestThread::clearRepeatingRequests(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005172 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005173 Mutex::Autolock l(mRequestLock);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005174 return clearRepeatingRequestsLocked(lastFrameNumber);
5175
5176}
5177
5178status_t Camera3Device::RequestThread::clearRepeatingRequestsLocked(/*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005179 mRepeatingRequests.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005180 if (lastFrameNumber != NULL) {
5181 *lastFrameNumber = mRepeatingLastFrameNumber;
5182 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005183 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005184 return OK;
5185}
5186
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005187status_t Camera3Device::RequestThread::clear(
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005188 /*out*/int64_t *lastFrameNumber) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005189 ATRACE_CALL();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005190 Mutex::Autolock l(mRequestLock);
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005191 ALOGV("RequestThread::%s:", __FUNCTION__);
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005192
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005193 mRepeatingRequests.clear();
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005194
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005195 // Send errors for all requests pending in the request queue, including
5196 // pending repeating requests
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005197 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005198 if (listener != NULL) {
5199 for (RequestList::iterator it = mRequestQueue.begin();
5200 it != mRequestQueue.end(); ++it) {
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005201 // Abort the input buffers for reprocess requests.
5202 if ((*it)->mInputStream != NULL) {
5203 camera3_stream_buffer_t inputBuffer;
Eino-Ville Talvalaba435252017-06-21 16:07:25 -07005204 status_t res = (*it)->mInputStream->getInputBuffer(&inputBuffer,
5205 /*respectHalLimit*/ false);
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005206 if (res != OK) {
5207 ALOGW("%s: %d: couldn't get input buffer while clearing the request "
5208 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5209 } else {
Shuzhen Wang0cf01cb2019-09-05 13:33:06 -07005210 inputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07005211 res = (*it)->mInputStream->returnInputBuffer(inputBuffer);
5212 if (res != OK) {
5213 ALOGE("%s: %d: couldn't return input buffer while clearing the request "
5214 "list: %s (%d)", __FUNCTION__, __LINE__, strerror(-res), res);
5215 }
5216 }
5217 }
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005218 // Set the frame number this request would have had, if it
5219 // had been submitted; this frame number will not be reused.
5220 // The requestId and burstId fields were set when the request was
5221 // submitted originally (in convertMetadataListToRequestListLocked)
5222 (*it)->mResultExtras.frameNumber = mFrameNumber++;
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005223 listener->notifyError(hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Eino-Ville Talvala17543512014-08-06 14:32:02 -07005224 (*it)->mResultExtras);
Yin-Chia Yeh8684b7f2014-06-13 14:53:05 -07005225 }
5226 }
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005227 mRequestQueue.clear();
Jinguang Dongb26e7a02016-11-14 16:04:02 +08005228
5229 Mutex::Autolock al(mTriggerMutex);
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005230 mTriggerMap.clear();
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07005231 if (lastFrameNumber != NULL) {
5232 *lastFrameNumber = mRepeatingLastFrameNumber;
5233 }
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08005234 mRepeatingLastFrameNumber = hardware::camera2::ICameraDeviceUser::NO_IN_FLIGHT_REPEATING_FRAMES;
Emilian Peev8dae54c2019-12-02 15:17:17 -08005235 mRequestSignal.signal();
Eino-Ville Talvalaabaa51d2013-08-14 11:37:00 -07005236 return OK;
5237}
5238
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005239status_t Camera3Device::RequestThread::flush() {
5240 ATRACE_CALL();
5241 Mutex::Autolock l(mFlushLock);
5242
Emilian Peev08dd2452017-04-06 16:55:14 +01005243 return mInterface->flush();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005244}
5245
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005246void Camera3Device::RequestThread::setPaused(bool paused) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005247 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005248 Mutex::Autolock l(mPauseLock);
5249 mDoPause = paused;
5250 mDoPauseSignal.signal();
5251}
5252
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005253status_t Camera3Device::RequestThread::waitUntilRequestProcessed(
5254 int32_t requestId, nsecs_t timeout) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005255 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005256 Mutex::Autolock l(mLatestRequestMutex);
5257 status_t res;
5258 while (mLatestRequestId != requestId) {
5259 nsecs_t startTime = systemTime();
5260
5261 res = mLatestRequestSignal.waitRelative(mLatestRequestMutex, timeout);
5262 if (res != OK) return res;
5263
5264 timeout -= (systemTime() - startTime);
5265 }
5266
5267 return OK;
5268}
5269
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005270void Camera3Device::RequestThread::requestExit() {
5271 // Call parent to set up shutdown
5272 Thread::requestExit();
5273 // The exit from any possible waits
5274 mDoPauseSignal.signal();
5275 mRequestSignal.signal();
Shuzhen Wang686f6442017-06-20 16:16:04 -07005276
5277 mRequestLatency.log("ProcessCaptureRequest latency histogram");
5278 mRequestLatency.reset();
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005279}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005280
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005281void Camera3Device::RequestThread::checkAndStopRepeatingRequest() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005282 ATRACE_CALL();
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005283 bool surfaceAbandoned = false;
5284 int64_t lastFrameNumber = 0;
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005285 sp<NotificationListener> listener;
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005286 {
5287 Mutex::Autolock l(mRequestLock);
5288 // Check all streams needed by repeating requests are still valid. Otherwise, stop
5289 // repeating requests.
5290 for (const auto& request : mRepeatingRequests) {
5291 for (const auto& s : request->mOutputStreams) {
5292 if (s->isAbandoned()) {
5293 surfaceAbandoned = true;
5294 clearRepeatingRequestsLocked(&lastFrameNumber);
5295 break;
5296 }
5297 }
5298 if (surfaceAbandoned) {
5299 break;
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005300 }
5301 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005302 listener = mListener.promote();
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005303 }
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07005304
5305 if (listener != NULL && surfaceAbandoned) {
5306 listener->notifyRepeatingRequestError(lastFrameNumber);
Yin-Chia Yeh473fad92016-05-23 15:54:41 -07005307 }
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005308}
5309
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005310bool Camera3Device::RequestThread::sendRequestsBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005311 ATRACE_CALL();
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005312 status_t res;
5313 size_t batchSize = mNextRequests.size();
5314 std::vector<camera3_capture_request_t*> requests(batchSize);
5315 uint32_t numRequestProcessed = 0;
5316 for (size_t i = 0; i < batchSize; i++) {
5317 requests[i] = &mNextRequests.editItemAt(i).halRequest;
Yin-Chia Yeh885691c2018-05-01 15:54:24 -07005318 ATRACE_ASYNC_BEGIN("frame capture", mNextRequests[i].halRequest.frame_number);
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005319 }
5320
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005321 res = mInterface->processBatchCaptureRequests(requests, &numRequestProcessed);
5322
5323 bool triggerRemoveFailed = false;
5324 NextRequest& triggerFailedRequest = mNextRequests.editItemAt(0);
5325 for (size_t i = 0; i < numRequestProcessed; i++) {
5326 NextRequest& nextRequest = mNextRequests.editItemAt(i);
5327 nextRequest.submitted = true;
5328
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005329 updateNextRequest(nextRequest);
Emilian Peevaebbe412018-01-15 13:53:24 +00005330
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005331 if (!triggerRemoveFailed) {
5332 // Remove any previously queued triggers (after unlock)
5333 status_t removeTriggerRes = removeTriggers(mPrevRequest);
5334 if (removeTriggerRes != OK) {
5335 triggerRemoveFailed = true;
5336 triggerFailedRequest = nextRequest;
5337 }
5338 }
5339 }
5340
5341 if (triggerRemoveFailed) {
5342 SET_ERR("RequestThread: Unable to remove triggers "
5343 "(capture request %d, HAL device: %s (%d)",
5344 triggerFailedRequest.halRequest.frame_number, strerror(-res), res);
5345 cleanUpFailedRequests(/*sendRequestError*/ false);
5346 return false;
5347 }
5348
5349 if (res != OK) {
5350 // Should only get a failure here for malformed requests or device-level
5351 // errors, so consider all errors fatal. Bad metadata failures should
5352 // come through notify.
5353 SET_ERR("RequestThread: Unable to submit capture request %d to HAL device: %s (%d)",
5354 mNextRequests[numRequestProcessed].halRequest.frame_number,
5355 strerror(-res), res);
5356 cleanUpFailedRequests(/*sendRequestError*/ false);
5357 return false;
5358 }
5359 return true;
5360}
5361
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005362nsecs_t Camera3Device::RequestThread::calculateMaxExpectedDuration(const camera_metadata_t *request) {
5363 nsecs_t maxExpectedDuration = kDefaultExpectedDuration;
5364 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5365 find_camera_metadata_ro_entry(request,
5366 ANDROID_CONTROL_AE_MODE,
5367 &e);
5368 if (e.count == 0) return maxExpectedDuration;
5369
5370 switch (e.data.u8[0]) {
5371 case ANDROID_CONTROL_AE_MODE_OFF:
5372 find_camera_metadata_ro_entry(request,
5373 ANDROID_SENSOR_EXPOSURE_TIME,
5374 &e);
5375 if (e.count > 0) {
5376 maxExpectedDuration = e.data.i64[0];
5377 }
5378 find_camera_metadata_ro_entry(request,
5379 ANDROID_SENSOR_FRAME_DURATION,
5380 &e);
5381 if (e.count > 0) {
5382 maxExpectedDuration = std::max(e.data.i64[0], maxExpectedDuration);
5383 }
5384 break;
5385 default:
5386 find_camera_metadata_ro_entry(request,
5387 ANDROID_CONTROL_AE_TARGET_FPS_RANGE,
5388 &e);
5389 if (e.count > 1) {
5390 maxExpectedDuration = 1e9 / e.data.u8[0];
5391 }
5392 break;
5393 }
5394
5395 return maxExpectedDuration;
5396}
5397
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005398bool Camera3Device::RequestThread::skipHFRTargetFPSUpdate(int32_t tag,
5399 const camera_metadata_ro_entry_t& newEntry, const camera_metadata_entry_t& currentEntry) {
5400 if (mConstrainedMode && (ANDROID_CONTROL_AE_TARGET_FPS_RANGE == tag) &&
5401 (newEntry.count == currentEntry.count) && (currentEntry.count == 2) &&
5402 (currentEntry.data.i32[1] == newEntry.data.i32[1])) {
5403 return true;
5404 }
5405
5406 return false;
5407}
5408
Shuzhen Wangc2cba122018-05-17 18:10:24 -07005409void Camera3Device::RequestThread::updateNextRequest(NextRequest& nextRequest) {
5410 // Update the latest request sent to HAL
5411 if (nextRequest.halRequest.settings != NULL) { // Don't update if they were unchanged
5412 Mutex::Autolock al(mLatestRequestMutex);
5413
5414 camera_metadata_t* cloned = clone_camera_metadata(nextRequest.halRequest.settings);
5415 mLatestRequest.acquire(cloned);
5416
5417 mLatestPhysicalRequest.clear();
5418 for (uint32_t i = 0; i < nextRequest.halRequest.num_physcam_settings; i++) {
5419 cloned = clone_camera_metadata(nextRequest.halRequest.physcam_settings[i]);
5420 mLatestPhysicalRequest.emplace(nextRequest.halRequest.physcam_id[i],
5421 CameraMetadata(cloned));
5422 }
5423
5424 sp<Camera3Device> parent = mParent.promote();
5425 if (parent != NULL) {
5426 parent->monitorMetadata(TagMonitor::REQUEST,
5427 nextRequest.halRequest.frame_number,
5428 0, mLatestRequest, mLatestPhysicalRequest);
5429 }
5430 }
5431
5432 if (nextRequest.halRequest.settings != NULL) {
5433 nextRequest.captureRequest->mSettingsList.begin()->metadata.unlock(
5434 nextRequest.halRequest.settings);
5435 }
5436
5437 cleanupPhysicalSettings(nextRequest.captureRequest, &nextRequest.halRequest);
5438}
5439
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005440bool Camera3Device::RequestThread::updateSessionParameters(const CameraMetadata& settings) {
5441 ATRACE_CALL();
5442 bool updatesDetected = false;
5443
Emilian Peev4ec17882019-01-24 17:16:58 -08005444 CameraMetadata updatedParams(mLatestSessionParams);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005445 for (auto tag : mSessionParamKeys) {
5446 camera_metadata_ro_entry entry = settings.find(tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005447 camera_metadata_entry lastEntry = updatedParams.find(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005448
5449 if (entry.count > 0) {
5450 bool isDifferent = false;
5451 if (lastEntry.count > 0) {
5452 // Have a last value, compare to see if changed
5453 if (lastEntry.type == entry.type &&
5454 lastEntry.count == entry.count) {
5455 // Same type and count, compare values
5456 size_t bytesPerValue = camera_metadata_type_size[lastEntry.type];
5457 size_t entryBytes = bytesPerValue * lastEntry.count;
5458 int cmp = memcmp(entry.data.u8, lastEntry.data.u8, entryBytes);
5459 if (cmp != 0) {
5460 isDifferent = true;
5461 }
5462 } else {
5463 // Count or type has changed
5464 isDifferent = true;
5465 }
5466 } else {
5467 // No last entry, so always consider to be different
5468 isDifferent = true;
5469 }
5470
5471 if (isDifferent) {
5472 ALOGV("%s: Session parameter tag id %d changed", __FUNCTION__, tag);
Emilian Peeva14b4dd2018-05-15 11:00:31 +01005473 if (!skipHFRTargetFPSUpdate(tag, entry, lastEntry)) {
5474 updatesDetected = true;
5475 }
Emilian Peev4ec17882019-01-24 17:16:58 -08005476 updatedParams.update(entry);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005477 }
5478 } else if (lastEntry.count > 0) {
5479 // Value has been removed
5480 ALOGV("%s: Session parameter tag id %d removed", __FUNCTION__, tag);
Emilian Peev4ec17882019-01-24 17:16:58 -08005481 updatedParams.erase(tag);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005482 updatesDetected = true;
5483 }
5484 }
5485
Emilian Peev4ec17882019-01-24 17:16:58 -08005486 bool reconfigureRequired;
5487 if (updatesDetected) {
5488 reconfigureRequired = mInterface->isReconfigurationRequired(mLatestSessionParams,
5489 updatedParams);
5490 mLatestSessionParams = updatedParams;
5491 } else {
5492 reconfigureRequired = false;
5493 }
5494
5495 return reconfigureRequired;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005496}
5497
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005498bool Camera3Device::RequestThread::threadLoop() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005499 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005500 status_t res;
5501
5502 // Handle paused state.
5503 if (waitIfPaused()) {
5504 return true;
5505 }
5506
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005507 // Wait for the next batch of requests.
5508 waitForNextRequestBatch();
5509 if (mNextRequests.size() == 0) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005510 return true;
5511 }
5512
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005513 // Get the latest request ID, if any
5514 int latestRequestId;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005515 camera_metadata_entry_t requestIdEntry = mNextRequests[mNextRequests.size() - 1].
Emilian Peevaebbe412018-01-15 13:53:24 +00005516 captureRequest->mSettingsList.begin()->metadata.find(ANDROID_REQUEST_ID);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005517 if (requestIdEntry.count > 0) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005518 latestRequestId = requestIdEntry.data.i32[0];
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005519 } else {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005520 ALOGW("%s: Did not have android.request.id set in the request.", __FUNCTION__);
5521 latestRequestId = NAME_NOT_FOUND;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07005522 }
5523
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005524 // 'mNextRequests' will at this point contain either a set of HFR batched requests
5525 // or a single request from streaming or burst. In either case the first element
5526 // should contain the latest camera settings that we need to check for any session
5527 // parameter updates.
Emilian Peevaebbe412018-01-15 13:53:24 +00005528 if (updateSessionParameters(mNextRequests[0].captureRequest->mSettingsList.begin()->metadata)) {
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005529 res = OK;
5530
5531 //Input stream buffers are already acquired at this point so an input stream
5532 //will not be able to move to idle state unless we force it.
5533 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5534 res = mNextRequests[0].captureRequest->mInputStream->forceToIdle();
5535 if (res != OK) {
5536 ALOGE("%s: Failed to force idle input stream: %d", __FUNCTION__, res);
5537 cleanUpFailedRequests(/*sendRequestError*/ false);
5538 return false;
5539 }
5540 }
5541
5542 if (res == OK) {
5543 sp<StatusTracker> statusTracker = mStatusTracker.promote();
5544 if (statusTracker != 0) {
Eino-Ville Talvala002001b2018-01-23 16:53:50 -08005545 sp<Camera3Device> parent = mParent.promote();
5546 if (parent != nullptr) {
5547 parent->pauseStateNotify(true);
5548 }
5549
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005550 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
5551
Emilian Peevac3ce6c2017-12-12 15:27:02 +00005552 if (parent != nullptr) {
5553 mReconfigured |= parent->reconfigureCamera(mLatestSessionParams);
5554 }
5555
5556 statusTracker->markComponentActive(mStatusId);
5557 setPaused(false);
5558 }
5559
5560 if (mNextRequests[0].captureRequest->mInputStream != nullptr) {
5561 mNextRequests[0].captureRequest->mInputStream->restoreConfiguredState();
5562 if (res != OK) {
5563 ALOGE("%s: Failed to restore configured input stream: %d", __FUNCTION__, res);
5564 cleanUpFailedRequests(/*sendRequestError*/ false);
5565 return false;
5566 }
5567 }
5568 }
5569 }
5570
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005571 // Prepare a batch of HAL requests and output buffers.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005572 res = prepareHalRequests();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005573 if (res == TIMED_OUT) {
5574 // Not a fatal error if getting output buffers time out.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005575 cleanUpFailedRequests(/*sendRequestError*/ true);
Chien-Yu Chene8c535e2016-04-14 12:18:26 -07005576 // Check if any stream is abandoned.
5577 checkAndStopRepeatingRequest();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005578 return true;
5579 } else if (res != OK) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005580 cleanUpFailedRequests(/*sendRequestError*/ false);
Eino-Ville Talvala42368d92013-04-09 14:13:50 -07005581 return false;
5582 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005583
Zhijun Hecc27e112013-10-03 16:12:43 -07005584 // Inform waitUntilRequestProcessed thread of a new request ID
5585 {
5586 Mutex::Autolock al(mLatestRequestMutex);
5587
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005588 mLatestRequestId = latestRequestId;
Zhijun Hecc27e112013-10-03 16:12:43 -07005589 mLatestRequestSignal.signal();
5590 }
5591
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005592 // Submit a batch of requests to HAL.
5593 // Use flush lock only when submitting multilple requests in a batch.
5594 // TODO: The problem with flush lock is flush() will be blocked by process_capture_request()
5595 // which may take a long time to finish so synchronizing flush() and
5596 // process_capture_request() defeats the purpose of cancelling requests ASAP with flush().
5597 // For now, only synchronize for high speed recording and we should figure something out for
5598 // removing the synchronization.
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005599 bool useFlushLock = mNextRequests.size() > 1;
Eino-Ville Talvala17a61ad2013-06-03 16:53:32 -07005600
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005601 if (useFlushLock) {
5602 mFlushLock.lock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005603 }
5604
Zhijun Hef0645c12016-08-02 00:58:11 -07005605 ALOGVV("%s: %d: submitting %zu requests in a batch.", __FUNCTION__, __LINE__,
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005606 mNextRequests.size());
Igor Murashkin1e479c02013-09-06 16:55:14 -07005607
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08005608 sp<Camera3Device> parent = mParent.promote();
5609 if (parent != nullptr) {
5610 parent->mRequestBufferSM.onSubmittingRequest();
5611 }
5612
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005613 bool submitRequestSuccess = false;
Shuzhen Wang686f6442017-06-20 16:16:04 -07005614 nsecs_t tRequestStart = systemTime(SYSTEM_TIME_MONOTONIC);
Yin-Chia Yeh11648852019-05-16 10:42:54 -07005615 submitRequestSuccess = sendRequestsBatch();
5616
Shuzhen Wang686f6442017-06-20 16:16:04 -07005617 nsecs_t tRequestEnd = systemTime(SYSTEM_TIME_MONOTONIC);
5618 mRequestLatency.add(tRequestStart, tRequestEnd);
Igor Murashkin1e479c02013-09-06 16:55:14 -07005619
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005620 if (useFlushLock) {
5621 mFlushLock.unlock();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005622 }
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07005623
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005624 // Unset as current request
5625 {
5626 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005627 mNextRequests.clear();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005628 }
Yin-Chia Yehb978c382019-10-30 00:22:37 -07005629 mRequestSubmittedSignal.signal();
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005630
Yin-Chia Yeh94c68e02017-03-06 14:09:44 -08005631 return submitRequestSuccess;
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08005632}
5633
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005634status_t Camera3Device::RequestThread::prepareHalRequests() {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005635 ATRACE_CALL();
5636
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005637 bool batchedRequest = mNextRequests[0].captureRequest->mBatchSize > 1;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005638 for (size_t i = 0; i < mNextRequests.size(); i++) {
5639 auto& nextRequest = mNextRequests.editItemAt(i);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005640 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
5641 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
5642 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
5643
5644 // Prepare a request to HAL
5645 halRequest->frame_number = captureRequest->mResultExtras.frameNumber;
5646
5647 // Insert any queued triggers (before metadata is locked)
5648 status_t res = insertTriggers(captureRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005649 if (res < 0) {
5650 SET_ERR("RequestThread: Unable to insert triggers "
5651 "(capture request %d, HAL device: %s (%d)",
5652 halRequest->frame_number, strerror(-res), res);
5653 return INVALID_OPERATION;
5654 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005655
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005656 int triggerCount = res;
5657 bool triggersMixedIn = (triggerCount > 0 || mPrevTriggers > 0);
5658 mPrevTriggers = triggerCount;
5659
5660 // If the request is the same as last, or we had triggers last time
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005661 bool newRequest = (mPrevRequest != captureRequest || triggersMixedIn) &&
5662 // Request settings are all the same within one batch, so only treat the first
5663 // request in a batch as new
Zhijun He54c36822018-07-18 09:33:39 -07005664 !(batchedRequest && i > 0);
Emilian Peev00420d22018-02-05 21:33:13 +00005665 if (newRequest) {
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005666 std::set<std::string> cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005667 /**
5668 * HAL workaround:
5669 * Insert a dummy trigger ID if a trigger is set but no trigger ID is
5670 */
5671 res = addDummyTriggerIds(captureRequest);
5672 if (res != OK) {
5673 SET_ERR("RequestThread: Unable to insert dummy trigger IDs "
5674 "(capture request %d, HAL device: %s (%d)",
5675 halRequest->frame_number, strerror(-res), res);
5676 return INVALID_OPERATION;
5677 }
5678
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005679 {
5680 // Correct metadata regions for distortion correction if enabled
5681 sp<Camera3Device> parent = mParent.promote();
5682 if (parent != nullptr) {
Shuzhen Wang4f6fa9d2019-03-29 10:40:35 -07005683 List<PhysicalCameraSettings>::iterator it;
5684 for (it = captureRequest->mSettingsList.begin();
5685 it != captureRequest->mSettingsList.end(); it++) {
5686 if (parent->mDistortionMappers.find(it->cameraId) ==
5687 parent->mDistortionMappers.end()) {
5688 continue;
5689 }
5690 res = parent->mDistortionMappers[it->cameraId].correctCaptureRequest(
5691 &(it->metadata));
5692 if (res != OK) {
5693 SET_ERR("RequestThread: Unable to correct capture requests "
5694 "for lens distortion for request %d: %s (%d)",
5695 halRequest->frame_number, strerror(-res), res);
5696 return INVALID_OPERATION;
5697 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005698 }
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005699
5700 for (it = captureRequest->mSettingsList.begin();
5701 it != captureRequest->mSettingsList.end(); it++) {
5702 if (parent->mZoomRatioMappers.find(it->cameraId) ==
5703 parent->mZoomRatioMappers.end()) {
5704 continue;
5705 }
5706
5707 camera_metadata_entry_t e = it->metadata.find(ANDROID_CONTROL_ZOOM_RATIO);
5708 if (e.count > 0 && e.data.f[0] != 1.0f) {
5709 cameraIdsWithZoom.insert(it->cameraId);
5710 }
5711
5712 res = parent->mZoomRatioMappers[it->cameraId].updateCaptureRequest(
5713 &(it->metadata));
5714 if (res != OK) {
5715 SET_ERR("RequestThread: Unable to correct capture requests "
5716 "for zoom ratio for request %d: %s (%d)",
5717 halRequest->frame_number, strerror(-res), res);
5718 return INVALID_OPERATION;
5719 }
5720 }
Eino-Ville Talvala7b8a1fd2018-05-22 15:30:35 -07005721 }
5722 }
5723
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005724 /**
5725 * The request should be presorted so accesses in HAL
5726 * are O(logn). Sidenote, sorting a sorted metadata is nop.
5727 */
Emilian Peevaebbe412018-01-15 13:53:24 +00005728 captureRequest->mSettingsList.begin()->metadata.sort();
5729 halRequest->settings = captureRequest->mSettingsList.begin()->metadata.getAndLock();
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005730 mPrevRequest = captureRequest;
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005731 mPrevCameraIdsWithZoom = cameraIdsWithZoom;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005732 ALOGVV("%s: Request settings are NEW", __FUNCTION__);
5733
5734 IF_ALOGV() {
5735 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5736 find_camera_metadata_ro_entry(
5737 halRequest->settings,
5738 ANDROID_CONTROL_AF_TRIGGER,
5739 &e
5740 );
5741 if (e.count > 0) {
5742 ALOGV("%s: Request (frame num %d) had AF trigger 0x%x",
5743 __FUNCTION__,
5744 halRequest->frame_number,
5745 e.data.u8[0]);
5746 }
5747 }
5748 } else {
5749 // leave request.settings NULL to indicate 'reuse latest given'
5750 ALOGVV("%s: Request settings are REUSED",
5751 __FUNCTION__);
5752 }
5753
Emilian Peevaebbe412018-01-15 13:53:24 +00005754 if (captureRequest->mSettingsList.size() > 1) {
5755 halRequest->num_physcam_settings = captureRequest->mSettingsList.size() - 1;
5756 halRequest->physcam_id = new const char* [halRequest->num_physcam_settings];
Emilian Peev00420d22018-02-05 21:33:13 +00005757 if (newRequest) {
5758 halRequest->physcam_settings =
5759 new const camera_metadata* [halRequest->num_physcam_settings];
5760 } else {
5761 halRequest->physcam_settings = nullptr;
5762 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005763 auto it = ++captureRequest->mSettingsList.begin();
5764 size_t i = 0;
5765 for (; it != captureRequest->mSettingsList.end(); it++, i++) {
5766 halRequest->physcam_id[i] = it->cameraId.c_str();
Emilian Peev00420d22018-02-05 21:33:13 +00005767 if (newRequest) {
5768 it->metadata.sort();
5769 halRequest->physcam_settings[i] = it->metadata.getAndLock();
5770 }
Emilian Peevaebbe412018-01-15 13:53:24 +00005771 }
5772 }
5773
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005774 uint32_t totalNumBuffers = 0;
5775
5776 // Fill in buffers
5777 if (captureRequest->mInputStream != NULL) {
5778 halRequest->input_buffer = &captureRequest->mInputBuffer;
5779 totalNumBuffers += 1;
5780 } else {
5781 halRequest->input_buffer = NULL;
5782 }
5783
5784 outputBuffers->insertAt(camera3_stream_buffer_t(), 0,
5785 captureRequest->mOutputStreams.size());
5786 halRequest->output_buffers = outputBuffers->array();
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005787 std::set<String8> requestedPhysicalCameras;
Yin-Chia Yehb3a80b12018-09-04 12:13:05 -07005788
5789 sp<Camera3Device> parent = mParent.promote();
5790 if (parent == NULL) {
5791 // Should not happen, and nowhere to send errors to, so just log it
5792 CLOGE("RequestThread: Parent is gone");
5793 return INVALID_OPERATION;
5794 }
5795 nsecs_t waitDuration = kBaseGetBufferWait + parent->getExpectedInFlightDuration();
5796
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005797 SurfaceMap uniqueSurfaceIdMap;
Shuzhen Wang4a472662017-02-26 23:29:04 -08005798 for (size_t j = 0; j < captureRequest->mOutputStreams.size(); j++) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005799 sp<Camera3OutputStreamInterface> outputStream =
5800 captureRequest->mOutputStreams.editItemAt(j);
5801 int streamId = outputStream->getId();
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005802
5803 // Prepare video buffers for high speed recording on the first video request.
5804 if (mPrepareVideoStream && outputStream->isVideoStream()) {
5805 // Only try to prepare video stream on the first video request.
5806 mPrepareVideoStream = false;
5807
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07005808 res = outputStream->startPrepare(Camera3StreamInterface::ALLOCATE_PIPELINE_MAX,
5809 false /*blockRequest*/);
Chien-Yu Chenc66969b2016-05-19 16:37:51 -07005810 while (res == NOT_ENOUGH_DATA) {
5811 res = outputStream->prepareNextBuffer();
5812 }
5813 if (res != OK) {
5814 ALOGW("%s: Preparing video buffers for high speed failed: %s (%d)",
5815 __FUNCTION__, strerror(-res), res);
5816 outputStream->cancelPrepare();
5817 }
5818 }
5819
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005820 std::vector<size_t> uniqueSurfaceIds;
5821 res = outputStream->getUniqueSurfaceIds(
5822 captureRequest->mOutputSurfaces[streamId],
5823 &uniqueSurfaceIds);
5824 // INVALID_OPERATION is normal output for streams not supporting surfaceIds
5825 if (res != OK && res != INVALID_OPERATION) {
5826 ALOGE("%s: failed to query stream %d unique surface IDs",
5827 __FUNCTION__, streamId);
5828 return res;
5829 }
5830 if (res == OK) {
5831 uniqueSurfaceIdMap.insert({streamId, std::move(uniqueSurfaceIds)});
5832 }
5833
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005834 if (mUseHalBufManager) {
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005835 if (outputStream->isAbandoned()) {
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005836 ALOGV("%s: stream %d is abandoned, skipping request", __FUNCTION__, streamId);
Yin-Chia Yeh110342b2018-11-19 11:47:46 -08005837 return TIMED_OUT;
5838 }
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005839 // HAL will request buffer through requestStreamBuffer API
5840 camera3_stream_buffer_t& buffer = outputBuffers->editItemAt(j);
5841 buffer.stream = outputStream->asHalStream();
5842 buffer.buffer = nullptr;
5843 buffer.status = CAMERA3_BUFFER_STATUS_OK;
5844 buffer.acquire_fence = -1;
5845 buffer.release_fence = -1;
5846 } else {
5847 res = outputStream->getBuffer(&outputBuffers->editItemAt(j),
5848 waitDuration,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005849 captureRequest->mOutputSurfaces[streamId]);
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005850 if (res != OK) {
5851 // Can't get output buffer from gralloc queue - this could be due to
5852 // abandoned queue or other consumer misbehavior, so not a fatal
5853 // error
Yin-Chia Yeha1b56c82019-03-27 15:50:39 -07005854 ALOGV("RequestThread: Can't get output buffer, skipping request:"
Yin-Chia Yehd5cd5ff2018-10-01 14:43:04 -07005855 " %s (%d)", strerror(-res), res);
5856
5857 return TIMED_OUT;
5858 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005859 }
Shuzhen Wang68ac7ad2019-01-30 14:03:28 -08005860
5861 {
5862 sp<Camera3Device> parent = mParent.promote();
5863 if (parent != nullptr) {
5864 const String8& streamCameraId = outputStream->getPhysicalCameraId();
5865 for (const auto& settings : captureRequest->mSettingsList) {
5866 if ((streamCameraId.isEmpty() &&
5867 parent->getId() == settings.cameraId.c_str()) ||
5868 streamCameraId == settings.cameraId.c_str()) {
5869 outputStream->fireBufferRequestForFrameNumber(
5870 captureRequest->mResultExtras.frameNumber,
5871 settings.metadata);
5872 }
5873 }
5874 }
5875 }
Shuzhen Wang0129d522016-10-30 22:43:41 -07005876
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005877 String8 physicalCameraId = outputStream->getPhysicalCameraId();
5878
5879 if (!physicalCameraId.isEmpty()) {
5880 // Physical stream isn't supported for input request.
5881 if (halRequest->input_buffer) {
5882 CLOGE("Physical stream is not supported for input request");
5883 return INVALID_OPERATION;
5884 }
5885 requestedPhysicalCameras.insert(physicalCameraId);
5886 }
5887 halRequest->num_output_buffers++;
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005888 }
5889 totalNumBuffers += halRequest->num_output_buffers;
5890
5891 // Log request in the in-flight queue
Shuzhen Wang4a472662017-02-26 23:29:04 -08005892 // If this request list is for constrained high speed recording (not
5893 // preview), and the current request is not the last one in the batch,
5894 // do not send callback to the app.
5895 bool hasCallback = true;
Yin-Chia Yehd07b11e2018-06-01 12:50:02 -07005896 if (batchedRequest && i != mNextRequests.size()-1) {
Shuzhen Wang4a472662017-02-26 23:29:04 -08005897 hasCallback = false;
5898 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005899 bool isStillCapture = false;
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005900 bool isZslCapture = false;
Emilian Peev9dd21f42018-08-03 13:39:29 +01005901 if (!mNextRequests[0].captureRequest->mSettingsList.begin()->metadata.isEmpty()) {
5902 camera_metadata_ro_entry_t e = camera_metadata_ro_entry_t();
5903 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_CAPTURE_INTENT, &e);
5904 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_CAPTURE_INTENT_STILL_CAPTURE)) {
5905 isStillCapture = true;
5906 ATRACE_ASYNC_BEGIN("still capture", mNextRequests[i].halRequest.frame_number);
5907 }
Shuzhen Wang26abaf42018-08-28 15:41:20 -07005908
5909 find_camera_metadata_ro_entry(halRequest->settings, ANDROID_CONTROL_ENABLE_ZSL, &e);
5910 if ((e.count > 0) && (e.data.u8[0] == ANDROID_CONTROL_ENABLE_ZSL_TRUE)) {
5911 isZslCapture = true;
5912 }
Emilian Peev9dd21f42018-08-03 13:39:29 +01005913 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005914 res = parent->registerInFlight(halRequest->frame_number,
5915 totalNumBuffers, captureRequest->mResultExtras,
5916 /*hasInput*/halRequest->input_buffer != NULL,
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07005917 hasCallback,
Shuzhen Wang5c22c152017-12-31 17:12:25 -08005918 calculateMaxExpectedDuration(halRequest->settings),
Shuzhen Wangdbdf72b2019-11-13 11:22:12 -08005919 requestedPhysicalCameras, isStillCapture, isZslCapture, mPrevCameraIdsWithZoom,
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005920 (mUseHalBufManager) ? uniqueSurfaceIdMap :
5921 SurfaceMap{});
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005922 ALOGVV("%s: registered in flight requestId = %" PRId32 ", frameNumber = %" PRId64
5923 ", burstId = %" PRId32 ".",
5924 __FUNCTION__,
5925 captureRequest->mResultExtras.requestId, captureRequest->mResultExtras.frameNumber,
5926 captureRequest->mResultExtras.burstId);
5927 if (res != OK) {
5928 SET_ERR("RequestThread: Unable to register new in-flight request:"
5929 " %s (%d)", strerror(-res), res);
5930 return INVALID_OPERATION;
5931 }
5932 }
5933
5934 return OK;
5935}
5936
Igor Murashkin1e479c02013-09-06 16:55:14 -07005937CameraMetadata Camera3Device::RequestThread::getLatestRequest() const {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005938 ATRACE_CALL();
Igor Murashkin1e479c02013-09-06 16:55:14 -07005939 Mutex::Autolock al(mLatestRequestMutex);
5940
5941 ALOGV("RequestThread::%s", __FUNCTION__);
5942
5943 return mLatestRequest;
5944}
5945
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005946bool Camera3Device::RequestThread::isStreamPending(
5947 sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07005948 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005949 Mutex::Autolock l(mRequestLock);
5950
Chien-Yu Chen85a64552015-08-28 15:46:12 -07005951 for (const auto& nextRequest : mNextRequests) {
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07005952 if (!nextRequest.submitted) {
5953 for (const auto& s : nextRequest.captureRequest->mOutputStreams) {
5954 if (stream == s) return true;
5955 }
5956 if (stream == nextRequest.captureRequest->mInputStream) return true;
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005957 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07005958 }
5959
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07005960 for (const auto& request : mRequestQueue) {
5961 for (const auto& s : request->mOutputStreams) {
5962 if (stream == s) return true;
5963 }
5964 if (stream == request->mInputStream) return true;
5965 }
5966
5967 for (const auto& request : mRepeatingRequests) {
5968 for (const auto& s : request->mOutputStreams) {
5969 if (stream == s) return true;
5970 }
5971 if (stream == request->mInputStream) return true;
5972 }
5973
5974 return false;
5975}
Jianing Weicb0652e2014-03-12 18:29:36 -07005976
Emilian Peev40ead602017-09-26 15:46:36 +01005977bool Camera3Device::RequestThread::isOutputSurfacePending(int streamId, size_t surfaceId) {
5978 ATRACE_CALL();
5979 Mutex::Autolock l(mRequestLock);
5980
5981 for (const auto& nextRequest : mNextRequests) {
5982 for (const auto& s : nextRequest.captureRequest->mOutputSurfaces) {
5983 if (s.first == streamId) {
5984 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5985 if (it != s.second.end()) {
5986 return true;
5987 }
5988 }
5989 }
5990 }
5991
5992 for (const auto& request : mRequestQueue) {
5993 for (const auto& s : request->mOutputSurfaces) {
5994 if (s.first == streamId) {
5995 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
5996 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07005997 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01005998 }
5999 }
6000 }
6001 }
6002
6003 for (const auto& request : mRepeatingRequests) {
6004 for (const auto& s : request->mOutputSurfaces) {
6005 if (s.first == streamId) {
6006 const auto &it = std::find(s.second.begin(), s.second.end(), surfaceId);
6007 if (it != s.second.end()) {
Yin-Chia Yeh58b1b4e2018-10-15 12:18:36 -07006008 return true;
Emilian Peev40ead602017-09-26 15:46:36 +01006009 }
6010 }
6011 }
6012 }
6013
6014 return false;
6015}
6016
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006017void Camera3Device::RequestThread::signalPipelineDrain(const std::vector<int>& streamIds) {
6018 if (!mUseHalBufManager) {
6019 ALOGE("%s called for camera device not supporting HAL buffer management", __FUNCTION__);
6020 return;
6021 }
6022
6023 Mutex::Autolock pl(mPauseLock);
6024 if (mPaused) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006025 mInterface->signalPipelineDrain(streamIds);
6026 return;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006027 }
6028 // If request thread is still busy, wait until paused then notify HAL
6029 mNotifyPipelineDrain = true;
6030 mStreamIdsToBeDrained = streamIds;
6031}
6032
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006033status_t Camera3Device::RequestThread::switchToOffline(
6034 const std::vector<int32_t>& streamsToKeep,
6035 /*out*/hardware::camera::device::V3_6::CameraOfflineSessionInfo* offlineSessionInfo,
6036 /*out*/sp<hardware::camera::device::V3_6::ICameraOfflineSession>* offlineSession) {
6037 Mutex::Autolock l(mRequestLock);
6038 clearRepeatingRequestsLocked(/*lastFrameNumber*/nullptr);
6039
6040 // Theoretically we should also check for mRepeatingRequests.empty(), but the API interface
6041 // is serialized by mInterfaceLock so skip that check.
6042 bool queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
6043 while (!queueEmpty) {
6044 status_t res = mRequestSubmittedSignal.waitRelative(mRequestLock, kRequestSubmitTimeout);
6045 if (res == TIMED_OUT) {
6046 ALOGE("%s: request thread failed to submit a request within timeout!", __FUNCTION__);
6047 return res;
6048 } else if (res != OK) {
6049 ALOGE("%s: request thread failed to submit a request: %s (%d)!",
6050 __FUNCTION__, strerror(-res), res);
6051 return res;
6052 }
6053 queueEmpty = mNextRequests.empty() && mRequestQueue.empty();
6054 }
6055 return mInterface->switchToOffline(
6056 streamsToKeep, offlineSessionInfo, offlineSession);
6057}
6058
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07006059nsecs_t Camera3Device::getExpectedInFlightDuration() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006060 ATRACE_CALL();
Yin-Chia Yeh598fc602017-07-24 11:37:23 -07006061 Mutex::Autolock al(mInFlightLock);
Eino-Ville Talvala10bd57e2017-06-23 16:22:44 -07006062 return mExpectedInflightDuration > kMinInflightDuration ?
6063 mExpectedInflightDuration : kMinInflightDuration;
6064}
6065
Emilian Peevaebbe412018-01-15 13:53:24 +00006066void Camera3Device::RequestThread::cleanupPhysicalSettings(sp<CaptureRequest> request,
6067 camera3_capture_request_t *halRequest) {
6068 if ((request == nullptr) || (halRequest == nullptr)) {
6069 ALOGE("%s: Invalid request!", __FUNCTION__);
6070 return;
6071 }
6072
6073 if (halRequest->num_physcam_settings > 0) {
6074 if (halRequest->physcam_id != nullptr) {
6075 delete [] halRequest->physcam_id;
6076 halRequest->physcam_id = nullptr;
6077 }
6078 if (halRequest->physcam_settings != nullptr) {
6079 auto it = ++(request->mSettingsList.begin());
6080 size_t i = 0;
6081 for (; it != request->mSettingsList.end(); it++, i++) {
6082 it->metadata.unlock(halRequest->physcam_settings[i]);
6083 }
6084 delete [] halRequest->physcam_settings;
6085 halRequest->physcam_settings = nullptr;
6086 }
6087 }
6088}
6089
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006090void Camera3Device::RequestThread::cleanUpFailedRequests(bool sendRequestError) {
6091 if (mNextRequests.empty()) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006092 return;
6093 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006094
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006095 for (auto& nextRequest : mNextRequests) {
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006096 // Skip the ones that have been submitted successfully.
6097 if (nextRequest.submitted) {
6098 continue;
6099 }
6100
6101 sp<CaptureRequest> captureRequest = nextRequest.captureRequest;
6102 camera3_capture_request_t* halRequest = &nextRequest.halRequest;
6103 Vector<camera3_stream_buffer_t>* outputBuffers = &nextRequest.outputBuffers;
6104
6105 if (halRequest->settings != NULL) {
Emilian Peevaebbe412018-01-15 13:53:24 +00006106 captureRequest->mSettingsList.begin()->metadata.unlock(halRequest->settings);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006107 }
6108
Emilian Peevaebbe412018-01-15 13:53:24 +00006109 cleanupPhysicalSettings(captureRequest, halRequest);
6110
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006111 if (captureRequest->mInputStream != NULL) {
6112 captureRequest->mInputBuffer.status = CAMERA3_BUFFER_STATUS_ERROR;
6113 captureRequest->mInputStream->returnInputBuffer(captureRequest->mInputBuffer);
6114 }
6115
Yin-Chia Yeh21cb47b2019-01-18 15:08:17 -08006116 // No output buffer can be returned when using HAL buffer manager
6117 if (!mUseHalBufManager) {
6118 for (size_t i = 0; i < halRequest->num_output_buffers; i++) {
6119 //Buffers that failed processing could still have
6120 //valid acquire fence.
6121 int acquireFence = (*outputBuffers)[i].acquire_fence;
6122 if (0 <= acquireFence) {
6123 close(acquireFence);
6124 outputBuffers->editItemAt(i).acquire_fence = -1;
6125 }
6126 outputBuffers->editItemAt(i).status = CAMERA3_BUFFER_STATUS_ERROR;
6127 captureRequest->mOutputStreams.editItemAt(i)->returnBuffer((*outputBuffers)[i], 0,
6128 /*timestampIncreasing*/true, std::vector<size_t> (),
6129 captureRequest->mResultExtras.frameNumber);
Emilian Peevc58cf4c2017-05-11 17:23:41 +01006130 }
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006131 }
6132
6133 if (sendRequestError) {
6134 Mutex::Autolock l(mRequestLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006135 sp<NotificationListener> listener = mListener.promote();
6136 if (listener != NULL) {
6137 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006138 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006139 captureRequest->mResultExtras);
6140 }
6141 }
Shuzhen Wangcadb3302016-11-04 14:17:56 -07006142
6143 // Remove yet-to-be submitted inflight request from inflightMap
6144 {
6145 sp<Camera3Device> parent = mParent.promote();
6146 if (parent != NULL) {
6147 Mutex::Autolock l(parent->mInFlightLock);
6148 ssize_t idx = parent->mInFlightMap.indexOfKey(captureRequest->mResultExtras.frameNumber);
6149 if (idx >= 0) {
6150 ALOGV("%s: Remove inflight request from queue: frameNumber %" PRId64,
6151 __FUNCTION__, captureRequest->mResultExtras.frameNumber);
6152 parent->removeInFlightMapEntryLocked(idx);
6153 }
6154 }
6155 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006156 }
Eino-Ville Talvalae74c2282015-05-27 14:46:23 -07006157
6158 Mutex::Autolock l(mRequestLock);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006159 mNextRequests.clear();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006160}
6161
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006162void Camera3Device::RequestThread::waitForNextRequestBatch() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006163 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006164 // Optimized a bit for the simple steady-state case (single repeating
6165 // request), to avoid putting that request in the queue temporarily.
6166 Mutex::Autolock l(mRequestLock);
6167
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006168 assert(mNextRequests.empty());
6169
6170 NextRequest nextRequest;
6171 nextRequest.captureRequest = waitForNextRequestLocked();
6172 if (nextRequest.captureRequest == nullptr) {
6173 return;
6174 }
6175
6176 nextRequest.halRequest = camera3_capture_request_t();
6177 nextRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006178 mNextRequests.add(nextRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006179
6180 // Wait for additional requests
6181 const size_t batchSize = nextRequest.captureRequest->mBatchSize;
6182
6183 for (size_t i = 1; i < batchSize; i++) {
6184 NextRequest additionalRequest;
6185 additionalRequest.captureRequest = waitForNextRequestLocked();
6186 if (additionalRequest.captureRequest == nullptr) {
6187 break;
6188 }
6189
6190 additionalRequest.halRequest = camera3_capture_request_t();
6191 additionalRequest.submitted = false;
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006192 mNextRequests.add(additionalRequest);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006193 }
6194
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006195 if (mNextRequests.size() < batchSize) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006196 ALOGE("RequestThread: only get %zu out of %zu requests. Skipping requests.",
Chien-Yu Chen57ea2922015-09-04 12:58:56 -07006197 mNextRequests.size(), batchSize);
6198 cleanUpFailedRequests(/*sendRequestError*/true);
Chien-Yu Chen85a64552015-08-28 15:46:12 -07006199 }
6200
6201 return;
6202}
6203
6204sp<Camera3Device::CaptureRequest>
6205 Camera3Device::RequestThread::waitForNextRequestLocked() {
6206 status_t res;
6207 sp<CaptureRequest> nextRequest;
6208
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006209 while (mRequestQueue.empty()) {
6210 if (!mRepeatingRequests.empty()) {
6211 // Always atomically enqueue all requests in a repeating request
6212 // list. Guarantees a complete in-sequence set of captures to
6213 // application.
6214 const RequestList &requests = mRepeatingRequests;
6215 RequestList::const_iterator firstRequest =
6216 requests.begin();
6217 nextRequest = *firstRequest;
6218 mRequestQueue.insert(mRequestQueue.end(),
6219 ++firstRequest,
6220 requests.end());
6221 // No need to wait any longer
Jianing Weicb0652e2014-03-12 18:29:36 -07006222
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006223 mRepeatingLastFrameNumber = mFrameNumber + requests.size() - 1;
Jianing Weicb0652e2014-03-12 18:29:36 -07006224
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006225 break;
6226 }
6227
6228 res = mRequestSignal.waitRelative(mRequestLock, kRequestTimeout);
6229
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006230 if ((mRequestQueue.empty() && mRepeatingRequests.empty()) ||
6231 exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006232 Mutex::Autolock pl(mPauseLock);
6233 if (mPaused == false) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006234 ALOGV("%s: RequestThread: Going idle", __FUNCTION__);
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006235 mPaused = true;
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006236 if (mNotifyPipelineDrain) {
6237 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6238 mNotifyPipelineDrain = false;
6239 mStreamIdsToBeDrained.clear();
6240 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006241 // Let the tracker know
6242 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6243 if (statusTracker != 0) {
6244 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6245 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006246 sp<Camera3Device> parent = mParent.promote();
6247 if (parent != nullptr) {
6248 parent->mRequestBufferSM.onRequestThreadPaused();
6249 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006250 }
6251 // Stop waiting for now and let thread management happen
6252 return NULL;
6253 }
6254 }
6255
6256 if (nextRequest == NULL) {
6257 // Don't have a repeating request already in hand, so queue
6258 // must have an entry now.
6259 RequestList::iterator firstRequest =
6260 mRequestQueue.begin();
6261 nextRequest = *firstRequest;
6262 mRequestQueue.erase(firstRequest);
Shuzhen Wang9d066012016-09-30 11:30:20 -07006263 if (mRequestQueue.empty() && !nextRequest->mRepeating) {
6264 sp<NotificationListener> listener = mListener.promote();
6265 if (listener != NULL) {
6266 listener->notifyRequestQueueEmpty();
6267 }
6268 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006269 }
6270
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006271 // In case we've been unpaused by setPaused clearing mDoPause, need to
6272 // update internal pause state (capture/setRepeatingRequest unpause
6273 // directly).
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006274 Mutex::Autolock pl(mPauseLock);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006275 if (mPaused) {
6276 ALOGV("%s: RequestThread: Unpaused", __FUNCTION__);
6277 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6278 if (statusTracker != 0) {
6279 statusTracker->markComponentActive(mStatusId);
6280 }
6281 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006282 mPaused = false;
6283
6284 // Check if we've reconfigured since last time, and reset the preview
6285 // request if so. Can't use 'NULL request == repeat' across configure calls.
6286 if (mReconfigured) {
6287 mPrevRequest.clear();
6288 mReconfigured = false;
6289 }
6290
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006291 if (nextRequest != NULL) {
6292 nextRequest->mResultExtras.frameNumber = mFrameNumber++;
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006293 nextRequest->mResultExtras.afTriggerId = mCurrentAfTriggerId;
6294 nextRequest->mResultExtras.precaptureTriggerId = mCurrentPreCaptureTriggerId;
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006295
6296 // Since RequestThread::clear() removes buffers from the input stream,
6297 // get the right buffer here before unlocking mRequestLock
6298 if (nextRequest->mInputStream != NULL) {
6299 res = nextRequest->mInputStream->getInputBuffer(&nextRequest->mInputBuffer);
6300 if (res != OK) {
6301 // Can't get input buffer from gralloc queue - this could be due to
6302 // disconnected queue or other producer misbehavior, so not a fatal
6303 // error
6304 ALOGE("%s: Can't get input buffer, skipping request:"
6305 " %s (%d)", __FUNCTION__, strerror(-res), res);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006306
6307 sp<NotificationListener> listener = mListener.promote();
6308 if (listener != NULL) {
6309 listener->notifyError(
Eino-Ville Talvalad56db1d2015-12-17 16:50:35 -08006310 hardware::camera2::ICameraDeviceCallbacks::ERROR_CAMERA_REQUEST,
Chien-Yu Chenc2adf482015-05-27 14:27:49 -07006311 nextRequest->mResultExtras);
6312 }
6313 return NULL;
6314 }
6315 }
Jianing Wei2d6bb3f2014-04-11 10:00:31 -07006316 }
Chien-Yu Chend196d612015-06-22 19:49:01 -07006317
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006318 return nextRequest;
6319}
6320
6321bool Camera3Device::RequestThread::waitIfPaused() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006322 ATRACE_CALL();
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006323 status_t res;
6324 Mutex::Autolock l(mPauseLock);
6325 while (mDoPause) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006326 if (mPaused == false) {
6327 mPaused = true;
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006328 ALOGV("%s: RequestThread: Paused", __FUNCTION__);
Yin-Chia Yeh7447f0f2018-10-11 15:28:12 -07006329 if (mNotifyPipelineDrain) {
6330 mInterface->signalPipelineDrain(mStreamIdsToBeDrained);
6331 mNotifyPipelineDrain = false;
6332 mStreamIdsToBeDrained.clear();
6333 }
Yin-Chia Yehc300a072019-02-13 14:56:57 -08006334 // Let the tracker know
6335 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6336 if (statusTracker != 0) {
6337 statusTracker->markComponentIdle(mStatusId, Fence::NO_FENCE);
6338 }
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006339 sp<Camera3Device> parent = mParent.promote();
6340 if (parent != nullptr) {
6341 parent->mRequestBufferSM.onRequestThreadPaused();
6342 }
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006343 }
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006344
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006345 res = mDoPauseSignal.waitRelative(mPauseLock, kRequestTimeout);
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006346 if (res == TIMED_OUT || exitPending()) {
Eino-Ville Talvalaf76e0272013-02-27 18:02:26 -08006347 return true;
6348 }
6349 }
6350 // We don't set mPaused to false here, because waitForNextRequest needs
6351 // to further manage the paused state in case of starvation.
6352 return false;
6353}
6354
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006355void Camera3Device::RequestThread::unpauseForNewRequests() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006356 ATRACE_CALL();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006357 // With work to do, mark thread as unpaused.
6358 // If paused by request (setPaused), don't resume, to avoid
6359 // extra signaling/waiting overhead to waitUntilPaused
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006360 mRequestSignal.signal();
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006361 Mutex::Autolock p(mPauseLock);
6362 if (!mDoPause) {
Eino-Ville Talvalaf1e98d82013-09-06 09:32:43 -07006363 ALOGV("%s: RequestThread: Going active", __FUNCTION__);
6364 if (mPaused) {
6365 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6366 if (statusTracker != 0) {
6367 statusTracker->markComponentActive(mStatusId);
6368 }
6369 }
Eino-Ville Talvala26fe6c72013-08-29 12:46:18 -07006370 mPaused = false;
6371 }
6372}
6373
Eino-Ville Talvalab2058d12013-04-09 13:49:56 -07006374void Camera3Device::RequestThread::setErrorState(const char *fmt, ...) {
6375 sp<Camera3Device> parent = mParent.promote();
6376 if (parent != NULL) {
6377 va_list args;
6378 va_start(args, fmt);
6379
6380 parent->setErrorStateV(fmt, args);
6381
6382 va_end(args);
6383 }
6384}
6385
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006386status_t Camera3Device::RequestThread::insertTriggers(
6387 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006388 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006389 Mutex::Autolock al(mTriggerMutex);
6390
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006391 sp<Camera3Device> parent = mParent.promote();
6392 if (parent == NULL) {
6393 CLOGE("RequestThread: Parent is gone");
6394 return DEAD_OBJECT;
6395 }
6396
Emilian Peevaebbe412018-01-15 13:53:24 +00006397 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006398 size_t count = mTriggerMap.size();
6399
6400 for (size_t i = 0; i < count; ++i) {
6401 RequestTrigger trigger = mTriggerMap.valueAt(i);
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006402 uint32_t tag = trigger.metadataTag;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006403
6404 if (tag == ANDROID_CONTROL_AF_TRIGGER_ID || tag == ANDROID_CONTROL_AE_PRECAPTURE_ID) {
6405 bool isAeTrigger = (trigger.metadataTag == ANDROID_CONTROL_AE_PRECAPTURE_ID);
6406 uint32_t triggerId = static_cast<uint32_t>(trigger.entryValue);
Yin-Chia Yehc00a25c2014-08-21 14:27:44 -07006407 if (isAeTrigger) {
6408 request->mResultExtras.precaptureTriggerId = triggerId;
6409 mCurrentPreCaptureTriggerId = triggerId;
6410 } else {
6411 request->mResultExtras.afTriggerId = triggerId;
6412 mCurrentAfTriggerId = triggerId;
6413 }
Emilian Peev7e25e5e2017-04-07 15:48:49 +01006414 continue;
Yin-Chia Yeh741ace82014-06-23 14:07:56 -07006415 }
6416
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006417 camera_metadata_entry entry = metadata.find(tag);
6418
6419 if (entry.count > 0) {
6420 /**
6421 * Already has an entry for this trigger in the request.
6422 * Rewrite it with our requested trigger value.
6423 */
6424 RequestTrigger oldTrigger = trigger;
6425
6426 oldTrigger.entryValue = entry.data.u8[0];
6427
6428 mTriggerReplacedMap.add(tag, oldTrigger);
6429 } else {
6430 /**
6431 * More typical, no trigger entry, so we just add it
6432 */
6433 mTriggerRemovedMap.add(tag, trigger);
6434 }
6435
6436 status_t res;
6437
6438 switch (trigger.getTagType()) {
6439 case TYPE_BYTE: {
6440 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6441 res = metadata.update(tag,
6442 &entryValue,
6443 /*count*/1);
6444 break;
6445 }
6446 case TYPE_INT32:
6447 res = metadata.update(tag,
6448 &trigger.entryValue,
6449 /*count*/1);
6450 break;
6451 default:
6452 ALOGE("%s: Type not supported: 0x%x",
6453 __FUNCTION__,
6454 trigger.getTagType());
6455 return INVALID_OPERATION;
6456 }
6457
6458 if (res != OK) {
6459 ALOGE("%s: Failed to update request metadata with trigger tag %s"
6460 ", value %d", __FUNCTION__, trigger.getTagName(),
6461 trigger.entryValue);
6462 return res;
6463 }
6464
6465 ALOGV("%s: Mixed in trigger %s, value %d", __FUNCTION__,
6466 trigger.getTagName(),
6467 trigger.entryValue);
6468 }
6469
6470 mTriggerMap.clear();
6471
6472 return count;
6473}
6474
6475status_t Camera3Device::RequestThread::removeTriggers(
6476 const sp<CaptureRequest> &request) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006477 ATRACE_CALL();
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006478 Mutex::Autolock al(mTriggerMutex);
6479
Emilian Peevaebbe412018-01-15 13:53:24 +00006480 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006481
6482 /**
6483 * Replace all old entries with their old values.
6484 */
6485 for (size_t i = 0; i < mTriggerReplacedMap.size(); ++i) {
6486 RequestTrigger trigger = mTriggerReplacedMap.valueAt(i);
6487
6488 status_t res;
6489
6490 uint32_t tag = trigger.metadataTag;
6491 switch (trigger.getTagType()) {
6492 case TYPE_BYTE: {
6493 uint8_t entryValue = static_cast<uint8_t>(trigger.entryValue);
6494 res = metadata.update(tag,
6495 &entryValue,
6496 /*count*/1);
6497 break;
6498 }
6499 case TYPE_INT32:
6500 res = metadata.update(tag,
6501 &trigger.entryValue,
6502 /*count*/1);
6503 break;
6504 default:
6505 ALOGE("%s: Type not supported: 0x%x",
6506 __FUNCTION__,
6507 trigger.getTagType());
6508 return INVALID_OPERATION;
6509 }
6510
6511 if (res != OK) {
6512 ALOGE("%s: Failed to restore request metadata with trigger tag %s"
6513 ", trigger value %d", __FUNCTION__,
6514 trigger.getTagName(), trigger.entryValue);
6515 return res;
6516 }
6517 }
6518 mTriggerReplacedMap.clear();
6519
6520 /**
6521 * Remove all new entries.
6522 */
6523 for (size_t i = 0; i < mTriggerRemovedMap.size(); ++i) {
6524 RequestTrigger trigger = mTriggerRemovedMap.valueAt(i);
6525 status_t res = metadata.erase(trigger.metadataTag);
6526
6527 if (res != OK) {
6528 ALOGE("%s: Failed to erase metadata with trigger tag %s"
6529 ", trigger value %d", __FUNCTION__,
6530 trigger.getTagName(), trigger.entryValue);
6531 return res;
6532 }
6533 }
6534 mTriggerRemovedMap.clear();
6535
6536 return OK;
6537}
6538
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006539status_t Camera3Device::RequestThread::addDummyTriggerIds(
6540 const sp<CaptureRequest> &request) {
Eino-Ville Talvalad309fb92015-11-25 12:12:45 -08006541 // Trigger ID 0 had special meaning in the HAL2 spec, so avoid it here
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006542 static const int32_t dummyTriggerId = 1;
6543 status_t res;
6544
Emilian Peevaebbe412018-01-15 13:53:24 +00006545 CameraMetadata &metadata = request->mSettingsList.begin()->metadata;
Eino-Ville Talvala2f876f92013-09-13 11:39:24 -07006546
6547 // If AF trigger is active, insert a dummy AF trigger ID if none already
6548 // exists
6549 camera_metadata_entry afTrigger = metadata.find(ANDROID_CONTROL_AF_TRIGGER);
6550 camera_metadata_entry afId = metadata.find(ANDROID_CONTROL_AF_TRIGGER_ID);
6551 if (afTrigger.count > 0 &&
6552 afTrigger.data.u8[0] != ANDROID_CONTROL_AF_TRIGGER_IDLE &&
6553 afId.count == 0) {
6554 res = metadata.update(ANDROID_CONTROL_AF_TRIGGER_ID, &dummyTriggerId, 1);
6555 if (res != OK) return res;
6556 }
6557
6558 // If AE precapture trigger is active, insert a dummy precapture trigger ID
6559 // if none already exists
6560 camera_metadata_entry pcTrigger =
6561 metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER);
6562 camera_metadata_entry pcId = metadata.find(ANDROID_CONTROL_AE_PRECAPTURE_ID);
6563 if (pcTrigger.count > 0 &&
6564 pcTrigger.data.u8[0] != ANDROID_CONTROL_AE_PRECAPTURE_TRIGGER_IDLE &&
6565 pcId.count == 0) {
6566 res = metadata.update(ANDROID_CONTROL_AE_PRECAPTURE_ID,
6567 &dummyTriggerId, 1);
6568 if (res != OK) return res;
6569 }
6570
6571 return OK;
6572}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006573
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006574/**
6575 * PreparerThread inner class methods
6576 */
6577
6578Camera3Device::PreparerThread::PreparerThread() :
Eino-Ville Talvala77c1a352016-06-13 12:32:43 -07006579 Thread(/*canCallJava*/false), mListener(nullptr),
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006580 mActive(false), mCancelNow(false), mCurrentMaxCount(0), mCurrentPrepareComplete(false) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006581}
6582
6583Camera3Device::PreparerThread::~PreparerThread() {
6584 Thread::requestExitAndWait();
6585 if (mCurrentStream != nullptr) {
6586 mCurrentStream->cancelPrepare();
6587 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6588 mCurrentStream.clear();
6589 }
6590 clear();
6591}
6592
Ruben Brunkc78ac262015-08-13 17:58:46 -07006593status_t Camera3Device::PreparerThread::prepare(int maxCount, sp<Camera3StreamInterface>& stream) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006594 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006595 status_t res;
6596
6597 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006598 sp<NotificationListener> listener = mListener.promote();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006599
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006600 res = stream->startPrepare(maxCount, true /*blockRequest*/);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006601 if (res == OK) {
6602 // No preparation needed, fire listener right off
6603 ALOGV("%s: Stream %d already prepared", __FUNCTION__, stream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006604 if (listener != NULL) {
6605 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006606 }
6607 return OK;
6608 } else if (res != NOT_ENOUGH_DATA) {
6609 return res;
6610 }
6611
6612 // Need to prepare, start up thread if necessary
6613 if (!mActive) {
6614 // mRunning will change to false before the thread fully shuts down, so wait to be sure it
6615 // isn't running
6616 Thread::requestExitAndWait();
6617 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6618 if (res != OK) {
6619 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__, res, strerror(-res));
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006620 if (listener != NULL) {
6621 listener->notifyPrepared(stream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006622 }
6623 return res;
6624 }
6625 mCancelNow = false;
6626 mActive = true;
6627 ALOGV("%s: Preparer stream started", __FUNCTION__);
6628 }
6629
6630 // queue up the work
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006631 mPendingStreams.emplace(maxCount, stream);
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006632 ALOGV("%s: Stream %d queued for preparing", __FUNCTION__, stream->getId());
6633
6634 return OK;
6635}
6636
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006637void Camera3Device::PreparerThread::pause() {
6638 ATRACE_CALL();
6639
6640 Mutex::Autolock l(mLock);
6641
6642 std::unordered_map<int, sp<camera3::Camera3StreamInterface> > pendingStreams;
6643 pendingStreams.insert(mPendingStreams.begin(), mPendingStreams.end());
6644 sp<camera3::Camera3StreamInterface> currentStream = mCurrentStream;
6645 int currentMaxCount = mCurrentMaxCount;
6646 mPendingStreams.clear();
6647 mCancelNow = true;
6648 while (mActive) {
6649 auto res = mThreadActiveSignal.waitRelative(mLock, kActiveTimeout);
6650 if (res == TIMED_OUT) {
6651 ALOGE("%s: Timed out waiting on prepare thread!", __FUNCTION__);
6652 return;
6653 } else if (res != OK) {
6654 ALOGE("%s: Encountered an error: %d waiting on prepare thread!", __FUNCTION__, res);
6655 return;
6656 }
6657 }
6658
6659 //Check whether the prepare thread was able to complete the current
6660 //stream. In case work is still pending emplace it along with the rest
6661 //of the streams in the pending list.
6662 if (currentStream != nullptr) {
6663 if (!mCurrentPrepareComplete) {
6664 pendingStreams.emplace(currentMaxCount, currentStream);
6665 }
6666 }
6667
6668 mPendingStreams.insert(pendingStreams.begin(), pendingStreams.end());
6669 for (const auto& it : mPendingStreams) {
6670 it.second->cancelPrepare();
6671 }
6672}
6673
6674status_t Camera3Device::PreparerThread::resume() {
6675 ATRACE_CALL();
6676 status_t res;
6677
6678 Mutex::Autolock l(mLock);
6679 sp<NotificationListener> listener = mListener.promote();
6680
6681 if (mActive) {
6682 ALOGE("%s: Trying to resume an already active prepare thread!", __FUNCTION__);
6683 return NO_INIT;
6684 }
6685
6686 auto it = mPendingStreams.begin();
6687 for (; it != mPendingStreams.end();) {
Shuzhen Wangb3a0fb52018-09-13 17:24:08 -07006688 res = it->second->startPrepare(it->first, true /*blockRequest*/);
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006689 if (res == OK) {
6690 if (listener != NULL) {
6691 listener->notifyPrepared(it->second->getId());
6692 }
6693 it = mPendingStreams.erase(it);
6694 } else if (res != NOT_ENOUGH_DATA) {
6695 ALOGE("%s: Unable to start preparer stream: %d (%s)", __FUNCTION__,
6696 res, strerror(-res));
6697 it = mPendingStreams.erase(it);
6698 } else {
6699 it++;
6700 }
6701 }
6702
6703 if (mPendingStreams.empty()) {
6704 return OK;
6705 }
6706
6707 res = Thread::run("C3PrepThread", PRIORITY_BACKGROUND);
6708 if (res != OK) {
6709 ALOGE("%s: Unable to start preparer stream: %d (%s)",
6710 __FUNCTION__, res, strerror(-res));
6711 return res;
6712 }
6713 mCancelNow = false;
6714 mActive = true;
6715 ALOGV("%s: Preparer stream started", __FUNCTION__);
6716
6717 return OK;
6718}
6719
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006720status_t Camera3Device::PreparerThread::clear() {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006721 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006722 Mutex::Autolock l(mLock);
6723
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006724 for (const auto& it : mPendingStreams) {
6725 it.second->cancelPrepare();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006726 }
6727 mPendingStreams.clear();
6728 mCancelNow = true;
6729
6730 return OK;
6731}
6732
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006733void Camera3Device::PreparerThread::setNotificationListener(wp<NotificationListener> listener) {
Eino-Ville Talvala6aeb8882017-08-07 17:40:49 -07006734 ATRACE_CALL();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006735 Mutex::Autolock l(mLock);
6736 mListener = listener;
6737}
6738
6739bool Camera3Device::PreparerThread::threadLoop() {
6740 status_t res;
6741 {
6742 Mutex::Autolock l(mLock);
6743 if (mCurrentStream == nullptr) {
6744 // End thread if done with work
6745 if (mPendingStreams.empty()) {
6746 ALOGV("%s: Preparer stream out of work", __FUNCTION__);
6747 // threadLoop _must not_ re-acquire mLock after it sets mActive to false; would
6748 // cause deadlock with prepare()'s requestExitAndWait triggered by !mActive.
6749 mActive = false;
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006750 mThreadActiveSignal.signal();
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006751 return false;
6752 }
6753
6754 // Get next stream to prepare
6755 auto it = mPendingStreams.begin();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006756 mCurrentStream = it->second;
6757 mCurrentMaxCount = it->first;
6758 mCurrentPrepareComplete = false;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006759 mPendingStreams.erase(it);
6760 ATRACE_ASYNC_BEGIN("stream prepare", mCurrentStream->getId());
6761 ALOGV("%s: Preparing stream %d", __FUNCTION__, mCurrentStream->getId());
6762 } else if (mCancelNow) {
6763 mCurrentStream->cancelPrepare();
6764 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6765 ALOGV("%s: Cancelling stream %d prepare", __FUNCTION__, mCurrentStream->getId());
6766 mCurrentStream.clear();
6767 mCancelNow = false;
6768 return true;
6769 }
6770 }
6771
6772 res = mCurrentStream->prepareNextBuffer();
6773 if (res == NOT_ENOUGH_DATA) return true;
6774 if (res != OK) {
6775 // Something bad happened; try to recover by cancelling prepare and
6776 // signalling listener anyway
6777 ALOGE("%s: Stream %d returned error %d (%s) during prepare", __FUNCTION__,
6778 mCurrentStream->getId(), res, strerror(-res));
6779 mCurrentStream->cancelPrepare();
6780 }
6781
6782 // This stream has finished, notify listener
6783 Mutex::Autolock l(mLock);
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006784 sp<NotificationListener> listener = mListener.promote();
6785 if (listener != NULL) {
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006786 ALOGV("%s: Stream %d prepare done, signaling listener", __FUNCTION__,
6787 mCurrentStream->getId());
Yin-Chia Yehe1c80632016-08-08 14:48:05 -07006788 listener->notifyPrepared(mCurrentStream->getId());
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006789 }
6790
6791 ATRACE_ASYNC_END("stream prepare", mCurrentStream->getId());
6792 mCurrentStream.clear();
Emilian Peevac3ce6c2017-12-12 15:27:02 +00006793 mCurrentPrepareComplete = true;
Eino-Ville Talvala4d44cad2015-04-11 13:15:45 -07006794
6795 return true;
6796}
Igor Murashkin4d2f2e82013-04-01 17:29:07 -07006797
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006798status_t Camera3Device::RequestBufferStateMachine::initialize(
6799 sp<camera3::StatusTracker> statusTracker) {
6800 if (statusTracker == nullptr) {
6801 ALOGE("%s: statusTracker is null", __FUNCTION__);
6802 return BAD_VALUE;
6803 }
6804
6805 std::lock_guard<std::mutex> lock(mLock);
6806 mStatusTracker = statusTracker;
6807 mRequestBufferStatusId = statusTracker->addComponent();
6808 return OK;
6809}
6810
6811bool Camera3Device::RequestBufferStateMachine::startRequestBuffer() {
6812 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006813 if (mStatus == RB_STATUS_READY || mStatus == RB_STATUS_PENDING_STOP) {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006814 mRequestBufferOngoing = true;
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006815 notifyTrackerLocked(/*active*/true);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006816 return true;
6817 }
6818 return false;
6819}
6820
6821void Camera3Device::RequestBufferStateMachine::endRequestBuffer() {
6822 std::lock_guard<std::mutex> lock(mLock);
6823 if (!mRequestBufferOngoing) {
6824 ALOGE("%s called without a successful startRequestBuffer call first!", __FUNCTION__);
6825 return;
6826 }
6827 mRequestBufferOngoing = false;
6828 if (mStatus == RB_STATUS_PENDING_STOP) {
6829 checkSwitchToStopLocked();
6830 }
Yin-Chia Yeh8a4ccb02018-11-16 15:43:36 -08006831 notifyTrackerLocked(/*active*/false);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006832}
6833
6834void Camera3Device::RequestBufferStateMachine::onStreamsConfigured() {
6835 std::lock_guard<std::mutex> lock(mLock);
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006836 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006837 return;
6838}
6839
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006840void Camera3Device::RequestBufferStateMachine::onSubmittingRequest() {
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006841 std::lock_guard<std::mutex> lock(mLock);
6842 mRequestThreadPaused = false;
Yin-Chia Yehcd333fe2019-02-08 13:45:41 -08006843 // inflight map register actually happens in prepareHalRequest now, but it is close enough
6844 // approximation.
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006845 mInflightMapEmpty = false;
6846 if (mStatus == RB_STATUS_STOPPED) {
6847 mStatus = RB_STATUS_READY;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006848 }
6849 return;
6850}
6851
6852void Camera3Device::RequestBufferStateMachine::onRequestThreadPaused() {
6853 std::lock_guard<std::mutex> lock(mLock);
6854 mRequestThreadPaused = true;
6855 if (mStatus == RB_STATUS_PENDING_STOP) {
6856 checkSwitchToStopLocked();
6857 }
6858 return;
6859}
6860
6861void Camera3Device::RequestBufferStateMachine::onInflightMapEmpty() {
6862 std::lock_guard<std::mutex> lock(mLock);
6863 mInflightMapEmpty = true;
6864 if (mStatus == RB_STATUS_PENDING_STOP) {
6865 checkSwitchToStopLocked();
6866 }
6867 return;
6868}
6869
6870void Camera3Device::RequestBufferStateMachine::onWaitUntilIdle() {
6871 std::lock_guard<std::mutex> lock(mLock);
6872 if (!checkSwitchToStopLocked()) {
6873 mStatus = RB_STATUS_PENDING_STOP;
6874 }
6875 return;
6876}
6877
6878void Camera3Device::RequestBufferStateMachine::notifyTrackerLocked(bool active) {
6879 sp<StatusTracker> statusTracker = mStatusTracker.promote();
6880 if (statusTracker != nullptr) {
6881 if (active) {
6882 statusTracker->markComponentActive(mRequestBufferStatusId);
6883 } else {
6884 statusTracker->markComponentIdle(mRequestBufferStatusId, Fence::NO_FENCE);
6885 }
6886 }
6887}
6888
6889bool Camera3Device::RequestBufferStateMachine::checkSwitchToStopLocked() {
6890 if (mInflightMapEmpty && mRequestThreadPaused && !mRequestBufferOngoing) {
6891 mStatus = RB_STATUS_STOPPED;
Yin-Chia Yeh30ab5ed2018-10-12 15:57:04 -07006892 return true;
6893 }
6894 return false;
6895}
6896
Shuzhen Wang268a1362018-10-16 16:32:59 -07006897status_t Camera3Device::fixupMonochromeTags(const CameraMetadata& deviceInfo,
6898 CameraMetadata& resultMetadata) {
6899 status_t res = OK;
6900 if (!mNeedFixupMonochromeTags) {
6901 return res;
6902 }
6903
6904 // Remove tags that are not applicable to monochrome camera.
6905 int32_t tagsToRemove[] = {
6906 ANDROID_SENSOR_GREEN_SPLIT,
6907 ANDROID_SENSOR_NEUTRAL_COLOR_POINT,
6908 ANDROID_COLOR_CORRECTION_MODE,
6909 ANDROID_COLOR_CORRECTION_TRANSFORM,
6910 ANDROID_COLOR_CORRECTION_GAINS,
6911 };
6912 for (auto tag : tagsToRemove) {
6913 res = resultMetadata.erase(tag);
6914 if (res != OK) {
6915 ALOGE("%s: Failed to remove tag %d for monochrome camera", __FUNCTION__, tag);
6916 return res;
6917 }
6918 }
6919
6920 // ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL
6921 camera_metadata_entry blEntry = resultMetadata.find(ANDROID_SENSOR_DYNAMIC_BLACK_LEVEL);
6922 for (size_t i = 1; i < blEntry.count; i++) {
6923 blEntry.data.f[i] = blEntry.data.f[0];
6924 }
6925
6926 // ANDROID_SENSOR_NOISE_PROFILE
6927 camera_metadata_entry npEntry = resultMetadata.find(ANDROID_SENSOR_NOISE_PROFILE);
6928 if (npEntry.count > 0 && npEntry.count % 2 == 0) {
6929 double np[] = {npEntry.data.d[0], npEntry.data.d[1]};
6930 res = resultMetadata.update(ANDROID_SENSOR_NOISE_PROFILE, np, 2);
6931 if (res != OK) {
6932 ALOGE("%s: Failed to update SENSOR_NOISE_PROFILE: %s (%d)",
6933 __FUNCTION__, strerror(-res), res);
6934 return res;
6935 }
6936 }
6937
6938 // ANDROID_STATISTICS_LENS_SHADING_MAP
6939 camera_metadata_ro_entry lsSizeEntry = deviceInfo.find(ANDROID_LENS_INFO_SHADING_MAP_SIZE);
6940 camera_metadata_entry lsEntry = resultMetadata.find(ANDROID_STATISTICS_LENS_SHADING_MAP);
6941 if (lsSizeEntry.count == 2 && lsEntry.count > 0
6942 && (int32_t)lsEntry.count == 4 * lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]) {
6943 for (int32_t i = 0; i < lsSizeEntry.data.i32[0] * lsSizeEntry.data.i32[1]; i++) {
6944 lsEntry.data.f[4*i+1] = lsEntry.data.f[4*i];
6945 lsEntry.data.f[4*i+2] = lsEntry.data.f[4*i];
6946 lsEntry.data.f[4*i+3] = lsEntry.data.f[4*i];
6947 }
6948 }
6949
6950 // ANDROID_TONEMAP_CURVE_BLUE
6951 // ANDROID_TONEMAP_CURVE_GREEN
6952 // ANDROID_TONEMAP_CURVE_RED
6953 camera_metadata_entry tcbEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_BLUE);
6954 camera_metadata_entry tcgEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_GREEN);
6955 camera_metadata_entry tcrEntry = resultMetadata.find(ANDROID_TONEMAP_CURVE_RED);
6956 if (tcbEntry.count > 0
6957 && tcbEntry.count == tcgEntry.count
6958 && tcbEntry.count == tcrEntry.count) {
6959 for (size_t i = 0; i < tcbEntry.count; i++) {
6960 tcbEntry.data.f[i] = tcrEntry.data.f[i];
6961 tcgEntry.data.f[i] = tcrEntry.data.f[i];
6962 }
6963 }
6964
6965 return res;
6966}
6967
Yin-Chia Yehb978c382019-10-30 00:22:37 -07006968status_t Camera3Device::switchToOffline(
6969 const std::vector<int32_t>& streamsToKeep,
6970 /*out*/ sp<CameraOfflineSessionBase>* session) {
6971 ATRACE_CALL();
6972 if (session == nullptr) {
6973 ALOGE("%s: session must not be null", __FUNCTION__);
6974 return BAD_VALUE;
6975 }
6976
6977 Mutex::Autolock il(mInterfaceLock);
6978 Mutex::Autolock l(mLock);
6979
6980 // 1. Stop repeating request, wait until request thread submitted all requests, then
6981 // call HAL switchToOffline
6982 hardware::camera::device::V3_6::CameraOfflineSessionInfo offlineSessionInfo;
6983 sp<hardware::camera::device::V3_6::ICameraOfflineSession> offlineSession;
6984
6985 mRequestThread->switchToOffline(streamsToKeep, &offlineSessionInfo, &offlineSession);
6986
6987
6988 // 2. Verify offlineSessionInfo
6989 // 3. create Camera3OfflineSession and transfer object ownership
6990 // (streams, inflight requests, buffer caches)
6991 *session = new Camera3OfflineSession(mId);
6992
6993 // 4. Delete unneeded streams
6994 // 5. Verify Camera3Device is in unconfigured state
6995 return OK;
6996}
6997
Eino-Ville Talvala7fa43f32013-02-06 17:20:07 -08006998}; // namespace android